Skip to content

Commit

Permalink
updated fork to newer version
Browse files Browse the repository at this point in the history
  • Loading branch information
melo-afk committed Dec 15, 2023
2 parents 59414ab + 6ee175e commit 7ccf3c9
Show file tree
Hide file tree
Showing 17 changed files with 171 additions and 19 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,4 @@ data.json

# Exclude macOS Finder (System Explorer) View States
.DS_Store
*.log
18 changes: 18 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,24 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),


## [1.10.0]
### Added
- Support for zig (Thanks to @slar)
- Support for enabling WSL Mode for the shell language only (Thanks to @mihai-vlc)

### Changed
- Update README.md


## [1.9.1]
### Changed
- Fix bug produced by duplicate labeled code blocks (Thanks to @qiaogaojian)

### Added
- Option for better handling of logs (Thanks to @qiaogaojian)
- Make labels work with code blocks with `run-` prefix (Thanks to @qiaogaojian)


## [1.9.0]
### Changed
- Fix app://local deprecation (New minimal Obsidian version: v1.2.8) (Thanks to @mayurankv)
Expand Down
16 changes: 13 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ The result is shown only after the execution is finished. It is not possible to
![Video that shows how the plugin works.](https://github.com/twibiral/obsidian-execute-code/blob/master/images/execute_code_example.gif?raw=true)


The following [languages are supported](#supported-programming-languages-): C, CPP, Dart, Golang, Groovy, Kotlin, Java, JavaScript, TypeScript, Lean, Lua, CSharp, Prolog, Rust, Python, R, Ruby, Wolfram Mathematica, Haskell, Scala, Racket, F#, Batch, Shell & Powershell, Octave, and Maxima.
The following [languages are supported](#supported-programming-languages-): C, CPP, Dart, Golang, Groovy, Kotlin, Java, JavaScript, TypeScript, Lean, Lua, CSharp, Prolog, Rust, Python, R, Ruby, Wolfram Mathematica, Haskell, Scala, Racket, F#, Batch, Shell & Powershell, Octave, Maxima and Zig.


Python, Rust, and Octave support embedded plots. All languages support ["magic" commands](#magic-commands-) that help you to access paths in obsidian or show images in your notes.
Expand All @@ -23,6 +23,8 @@ You can create code blocks that are executed before or after each code block of

Take a look at the [changelog](CHANGELOG.md) to see what has changed in recent versions.

[Here](#misc-) you can find some other tools and plugins that might are compatible with this plugin and might be useful for you.

<div align='center'>

[![Buy us a coffee](https://img.shields.io/badge/-buy_us_a%C2%A0coffee-gray?logo=buy-me-a-coffee)](https://www.buymeacoffee.com/timwibiral)
Expand Down Expand Up @@ -627,9 +629,17 @@ undefined
To manage the open runtimes for Notebook Mode, you can use the `Open Code Runtime Management` command in the command palette. From this sidebar window, you can stop kernels. **Note: force-stopping requires `taskkill` on Windows and `pkill` on Unix. 99% of systems should have these preinstalled: if yours doesn't, please [file an issue](https://github.com/twibiral/obsidian-execute-code/issues/new/choose)**


## Style Settings 🎨
## Misc 📦
### Style Settings 🎨

This plugin supports customising styles using the [Style Settings plugin](https://github.com/mgmeyers/obsidian-style-settings)
or the [Obsidian Code Styler plugin](https://github.com/mayurankv/Obsidian-Code-Styler).

### Other Tools

Take a look at the [Obsidian Tools python package](https://github.com/mfarragher/obsidiantools) to find some useful
tools for interacting with your vault.

This plugin supports customising styles using the [Style Settings plugin](https://github.com/mgmeyers/obsidian-style-settings). It's possible to customise the color of code block outputs and errors.

## Installation 💾

Expand Down
2 changes: 1 addition & 1 deletion esbuild.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -48,5 +48,5 @@ esbuild.build({
logLevel: "info",
sourcemap: prod ? false : 'inline',
treeShaking: true,
outfile: 'src/main.js',
outfile: 'main.js',
}).catch(() => process.exit(1));
2 changes: 1 addition & 1 deletion manifest.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"id": "execute-code",
"name": "Execute Code",
"version": "1.9.0",
"version": "1.10.0",
"minAppVersion": "1.2.8",
"description": "Allows to execute code snippets within a note. Supported programming languages: C, CPP, Dart, Golang, Groovy, Kotlin, Java, JavaScript, TypeScript, Lean, Lua, CSharp, Prolog, Rust, Python, R, Ruby, Wolfram Mathematica, Haskell, Scala, Racket, F#, Batch, Shell & Powershell.",
"author": "twibiral",
Expand Down
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "execute-code",
"version": "1.9.0",
"version": "1.10.0",
"description": "This is a sample plugin for Obsidian (https://obsidian.md)",
"main": "src/main.js",
"scripts": {
Expand Down
18 changes: 14 additions & 4 deletions src/executors/NonInteractiveCodeExecutor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@ import Executor from "./Executor";
import {Outputter} from "src/Outputter";
import {LanguageId} from "src/main";
import { ExecutorSettings } from "../settings/Settings.js";
import { sep } from "path";
import { join } from "path/posix";
import windowsPathToWsl from "../transforms/windowsPathToWsl.js";
import { error } from "console";

Expand Down Expand Up @@ -40,12 +38,12 @@ export default class NonInteractiveCodeExecutor extends Executor {
fs.promises.writeFile(tempFileName, codeBlockContent).then(() => {
const args = cmdArgs ? cmdArgs.split(" ") : [];

if (this.settings.wslMode) {
if (this.isWSLEnabled()) {
args.unshift("-e", cmd);
cmd = "wsl";
args.push(windowsPathToWsl(tempFileName));
} else {
args.push(tempFileName);
args.push(tempFileName);
}


Expand Down Expand Up @@ -86,6 +84,18 @@ export default class NonInteractiveCodeExecutor extends Executor {
});
}

private isWSLEnabled(): boolean {
if (this.settings.wslMode) {
return true;
}

if (this.language == 'shell' && this.settings.shellWSLMode) {
return true;
}

return false;
}

/**
* Handles the output of a child process and redirects stdout and stderr to the given {@link Outputter} element.
* Removes the temporary file after the code execution. Creates a new Notice after the code execution.
Expand Down
8 changes: 7 additions & 1 deletion src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import runAllCodeBlocks from './runAllCodeBlocks';
export const languageAliases = ["javascript", "typescript", "bash", "csharp", "wolfram", "nb", "wl", "hs", "py"] as const;
export const canonicalLanguages = ["js", "ts", "cs", "lean", "lua", "python", "cpp", "prolog", "shell", "groovy", "r",
"go", "rust", "java", "powershell", "kotlin", "mathematica", "haskell", "scala", "racket", "fsharp", "c", "dart",
"ruby", "batch", "sql", "octave", "maxima"] as const;
"ruby", "batch", "sql", "octave", "maxima", "applescript", "zig"] as const;
export const supportedLanguages = [...languageAliases, ...canonicalLanguages] as const;
export type LanguageId = typeof canonicalLanguages[number];

Expand Down Expand Up @@ -385,6 +385,12 @@ export default class ExecuteCodePlugin extends Plugin {
transformedCode = addInlinePlotsToMaxima(transformedCode);
this.runCodeInShell(transformedCode, out, button, this.settings.maximaPath, this.settings.maximaArgs, "maxima", language, file);
})
} else if (language === "zig") {
button.addEventListener("click", async () => {
button.className = runButtonDisabledClass;
const transformedCode = await new CodeInjector(this.app, this.settings, language).injectCode(srcCode);
this.runCodeInShell(transformedCode, out, button, this.settings.zigPath, this.settings.zigArgs, "zig", language, file);
})
}

}
Expand Down
22 changes: 22 additions & 0 deletions src/settings/Settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ export interface ExecutorSettings {
timeout: number;
allowInput: boolean;
wslMode: boolean;
shellWSLMode: boolean;
onlyCurrentBlock: boolean;
nodePath: string;
nodeArgs: string;
jsInject: string;
Expand Down Expand Up @@ -115,6 +117,13 @@ export interface ExecutorSettings {
sqlPath: string;
sqlArgs: string;
sqlInject: string;
applescriptPath: string;
applescriptArgs: string;
applescriptFileExtension: string;
applescriptInject: string;
zigPath: string;
zigArgs: string;
zigInject: string;

jsInteractive: boolean;
tsInteractive: boolean;
Expand Down Expand Up @@ -145,6 +154,8 @@ export interface ExecutorSettings {
sqlInteractive: boolean;
octaveInteractive: boolean;
maximaInteractive: boolean;
applescriptInteractive: boolean;
zigInteractive: boolean;
}


Expand All @@ -157,6 +168,8 @@ export const DEFAULT_SETTINGS: ExecutorSettings = {
timeout: 10000,
allowInput: true,
wslMode: false,
shellWSLMode: false,
onlyCurrentBlock: false,
nodePath: "node",
nodeArgs: "",
jsInject: "",
Expand Down Expand Up @@ -263,6 +276,13 @@ export const DEFAULT_SETTINGS: ExecutorSettings = {
maximaArgs: "-qb",
maximaFileExtension: "mx",
maximaInject: "",
applescriptPath: "osascript",
applescriptArgs: "",
applescriptFileExtension: "scpt",
applescriptInject: "",
zigPath: "zig",
zigArgs: "run",
zigInject: "",
jsInteractive: true,
tsInteractive: false,
csInteractive: false,
Expand Down Expand Up @@ -292,4 +312,6 @@ export const DEFAULT_SETTINGS: ExecutorSettings = {
sqlInteractive: false,
octaveInteractive: false,
maximaInteractive: false,
applescriptInteractive: false,
zigInteractive: false,
}
19 changes: 19 additions & 0 deletions src/settings/SettingsTab.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ import {ExecutorSettings} from "./Settings";
import makeSQLSettings from "./per-lang/makeSQLSettings";
import makeOctaviaSettings from "./per-lang/makeOctaveSettings";
import makeMaximaSettings from "./per-lang/makeMaximaSettings";
import makeApplescriptSettings from "./per-lang/makeApplescriptSettings";
import makeZigSettings from "./per-lang/makeZigSettings";


/**
Expand Down Expand Up @@ -99,6 +101,17 @@ export class SettingsTab extends PluginSettingTab {
}));
}

new Setting(containerEl)
.setName('Only Current Log')
.setDesc("Whether or not show print log only in current code block.")
.addToggle(text => text
.setValue(this.plugin.settings.onlyCurrentBlock)
.onChange(async (value) => {
console.log('Only Show Current Block Log set to: ' + value);
this.plugin.settings.onlyCurrentBlock = value
await this.plugin.saveSettings();
}));

// TODO setting per language that requires main function if main function should be implicitly made or not, if not, non-main blocks will not have a run button

containerEl.createEl("hr");
Expand Down Expand Up @@ -203,6 +216,12 @@ export class SettingsTab extends PluginSettingTab {
// ========== Maxima ============
makeMaximaSettings(this, this.makeContainerFor("maxima"));

// ========== Applescript ============
makeApplescriptSettings(this, this.makeContainerFor("applescript"));

// ========== Zig ============
makeZigSettings(this, this.makeContainerFor("zig"));

this.focusContainer(this.plugin.settings.lastOpenLanguageTab || canonicalLanguages[0]);
}

Expand Down
2 changes: 2 additions & 0 deletions src/settings/languageDisplayName.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,6 @@ export const DISPLAY_NAMES: Record<LanguageId, string> = {
sql: "SQL",
octave: "Octave",
maxima: "Maxima",
applescript: "Applescript",
zig: "Zig",
} as const;
14 changes: 13 additions & 1 deletion src/settings/per-lang/makeShellSettings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,5 +33,17 @@ export default (tab: SettingsTab, containerEl: HTMLElement) => {
console.log('Shell file extension set to: ' + value);
await tab.plugin.saveSettings();
}));

new Setting(containerEl)
.setName('Shell WSL mode')
.setDesc('Run the shell script in Windows Subsystem for Linux. This option is used if the global "WSL Mode" is disabled.')
.addToggle((toggle) =>
toggle
.setValue(tab.plugin.settings.shellWSLMode)
.onChange(async (value) => {
tab.plugin.settings.shellWSLMode = value;
await tab.plugin.saveSettings();
})
);
tab.makeInjectSetting(containerEl, "shell");
}
}
27 changes: 27 additions & 0 deletions src/settings/per-lang/makeZigSettings.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { Setting } from "obsidian";
import { SettingsTab } from "../SettingsTab";

export default (tab: SettingsTab, containerEl: HTMLElement) => {
containerEl.createEl('h3', { text: 'Zig Settings' });
new Setting(containerEl)
.setName('zig path')
.setDesc("Path to your zig installation")
.addText(text => text
.setValue(tab.plugin.settings.zigPath)
.onChange(async (value) => {
const sanitized = tab.sanitizePath(value);
tab.plugin.settings.zigPath = sanitized;
console.log('zig path set to: ' + sanitized);
await tab.plugin.saveSettings();
}));
new Setting(containerEl)
.setName('zig arguments')
.addText(text => text
.setValue(tab.plugin.settings.zigArgs)
.onChange(async (value) => {
tab.plugin.settings.zigArgs = value;
console.log('zig args set to: ' + value);
await tab.plugin.saveSettings();
}));
tab.makeInjectSetting(containerEl, "zig");
}
17 changes: 13 additions & 4 deletions src/transforms/CodeInjector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ export class CodeInjector {
new Notice(`Named export "${namedImport}" does not exist but was imported`);
return true;
}
this.namedImportSrcCode += `${this.namedExports[namedImport]}\n`;
this.namedImportSrcCode += `${this.disable_print(this.namedExports[namedImport])}\n`;
return false;
};
// Single import
Expand Down Expand Up @@ -145,13 +145,13 @@ export class CodeInjector {
if (!Array.isArray(currentArgs.export))
currentArgs.export = [currentArgs.export];
if (currentArgs.export.contains("pre"))
this.prependSrcCode += `${currentCode}\n`;
this.prependSrcCode += `${this.disable_print(currentCode)}\n`;
if (currentArgs.export.contains("post"))
this.appendSrcCode += `${currentCode}\n`;
this.appendSrcCode += `${this.disable_print(currentCode)}\n`;
currentLanguage = "";
currentCode = "";
insideCodeBlock = false;

currentArgs = {};
}

// reached start of code block
Expand All @@ -170,4 +170,13 @@ export class CodeInjector {
}
}
}

private disable_print(code: String): String {
if (!this.settings.onlyCurrentBlock) {
return code;
}
const pattern: RegExp = /^print\s*(.*)/gm;
// 使用正则表达式替换函数将符合条件的内容注释掉
return code.replace(pattern, ' ');
}
}
16 changes: 15 additions & 1 deletion src/transforms/TransformCode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,5 +56,19 @@ export function transformMagicCommands(app: App, srcCode: string) {
* @returns The language of the code block.
*/
export function getCodeBlockLanguage(firstLineOfCode: string) {
return getLanguageAlias(firstLineOfCode.split("```")[1].trim().split(" ")[0].split("{")[0])
let currentLanguage: string = firstLineOfCode.split("```")[1].trim().split(" ")[0].split("{")[0];
if (isStringNotEmpty(currentLanguage) && currentLanguage.startsWith("run-")) {
currentLanguage = currentLanguage.replace("run-", "");
}
return getLanguageAlias(currentLanguage);
}

/**
* Check if a string is not empty
*
* @param str Input string
* @returns True when string not empty, False when the string is Empty
*/
export function isStringNotEmpty(str: string): boolean {
return !!str && str.trim().length > 0;
}
4 changes: 3 additions & 1 deletion versions.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,5 +42,7 @@
"1.7.1": "0.12.0",
"1.8.0": "0.12.0",
"1.8.1": "0.12.0",
"1.9.0": "1.2.8"
"1.9.0": "1.2.8",
"1.9.1": "1.2.8",
"1.10.0": "1.2.8"
}

0 comments on commit 7ccf3c9

Please sign in to comment.