GithubHelp home page GithubHelp logo

twibiral / obsidian-execute-code Goto Github PK

View Code? Open in Web Editor NEW
1.0K 10.0 65.0 4.01 MB

Obsidian Plugin to execute code in a note.

License: MIT License

JavaScript 1.56% TypeScript 95.88% CSS 2.57%
javascript obsidian obsidian-md obsidian-plugin typescript hacktoberfest note-taking

obsidian-execute-code's Introduction

Obsidian Execute Code Plugin

Obsidian Downloads GitHub package.json version GitHub Release Date

This plugin allows you to execute code snippets in code blocks in your notes. The plugin adds a 'run' button for code blocks in supported languages. Clicking them results in the code of the block being executed. After the execution the result of the execution is showed. An interactive input element is created when your code snippets reads expects user input.

The result is shown only after the execution is finished. It is not possible to enter text on the command line into the executed program now.

Video that shows how the plugin works.



Note

Advertisement on my behalf: I am working on my master's thesis and looking for a PhD position in explainable AI or foundations of learning - if you have or know about an open position in that field, I would love to hear about it ๐Ÿ˜„


The following languages are supported: 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, Zig and OCaml.

Python, Rust, and Octave support embedded plots. All languages support "magic" commands that help you to access paths in obsidian or show images in your notes.

You can create code blocks that are executed before or after each code block of the same language and define global code injections.

Take a look at the changelog to see what has changed in recent versions.

Here you can find some other tools and plugins that might are compatible with this plugin and might be useful for you.

Buy us a coffee

Featured In

Video by I Versus AI Video by Michel's Science Speedrun
"Escape ChatGPT. Make your own Code Interpreter EASY" by I Versus AI "Obsidian & quarto integration" by Michel's Science Speedrun

In blogs:

Are you featuring this plugin in your content? Let me know and I will add it here.

Supported programming languages ๐Ÿ’ป

JavaScript
  • Requirements: Node.js is installed and the correct path is set in the settings.
function hello(name) {
	console.log(`Hello ${name}!`);
}

hello("Bob")
  • By default, Javascript runs in Notebook Mode. You can turn this off in the settings.
TypeScript
  • Requirements: Node.js installed then run in command line npm install typescript -g and npm install ts-node -g. (-g means global install)
  • Problems: If you use your global node.js installation and it doesn't work try to set your ts-node path in the settings to npx ts-node instead of ts-node.
let message: string = 'Hello, World!';
console.log(message);  
CSharp
  • Requirements: install dotnet core sdk and run in command line dotnet tool install -g dotnet-script, then config dotnet-script fullpath.
Console.WriteLine("Hello, World!");  
Dart
  • Requirements: dart sdk is installed and the correct path is set in the settings.
void main() {
  print("Hello World");
}
Python
  • Requirements: Python is installed and the correct path is set in the settings.
def hello(name):
	print("Hello", name)

if __name__ == "__main__":
	hello("Eve")
  • By default, Python runs in Notebook Mode. You can turn this off in the settings.
  • Plots with matplotlib/seaborn are embedded in the note by default. You can turn this off in the settings.
import seaborn as sns
import matplotlib.pyplot as plt
sns.set_style("darkgrid")
iris = sns.load_dataset('iris')
sns.FacetGrid(iris, hue ="species", height = 5)
		.map(plt.scatter, 'sepal_length', 'petal_length')
		.add_legend()

plt.show()

Example of an embedded plot.

R
  • Requirements: R is installed and the correct path is set in the settings.
hello <- function(name){
	print(paste("Hello", name, sep = " "))
}

hello("Bob")
  • Plots can be embedded in the note by default. You can turn this off in the settings.
y = c(12, 15, 28, 17, 18)
x = 1:length(y)
plot(x, y, type="l")
Java
  • Requirements: Java 11 or higher is installed and the correct path is set in the settings.
public class HelloWorld {
	public static void main(String[] args) {
		System.out.println("Hello World!");
	}
}
Lua
  • Requirements: install lua and config lua path.
print('Hello, World!')
Lean
  • Requirements: install lean and config lean path.
def main : IO Unit :=
  IO.println s!"Hello, World!"

#eval main
C++
  • Requirements: Cling is installed and correct path is set in the settings.
  • Code will be executed line-by-line without needing a main function.
#include <iostream>
#include <string>

using namespace std;

void hello(string name) {
	cout << "Hello " << name << "!\n";
}

hello("Alice);
  • Main functions can be used as an entrypoint by toggling the option in settings.
#include <iostream>

void main() {
	std::cout << "Hello, World!" << std::endl;
}
C
  • Requirements: Cling is installed and correct path is set in the settings.
  • Code will be executed line-by-line without needing a main function.
#include <stdio.h>

printf("Hello, World!");
  • Main functions can be used as an entrypoint by toggling the option in settings.
#include <stdio.h>

int main() {
	printf("Hello, World!");
	return 0;
}
Shell
  • Requirements: Set the path to your preferred shell in the settings. Default is Bash. (Only on Linux and macOS)
echo "Hello World!"
ls -la
Powershell
  • Requirements: Used to execute shell commands on Windows. Default is Powershell but can be set to your preferred shell in the settings.
  • On MacOS: You probably need to change the command to use from powershell to pwsh in the plugin settings. Make sure you set the right path.
echo "Hello World!"
  • If you prefer batch: change the path settings in the menu for powershell Example how to use the magic commands.
Batch
  • Requirements: Used to execute batch commands on Windows (also known as BAT or CMD). Default is command prompt, but can be set to your preferred shell in the settings.
  • Important:
    The percent sign is used in batch files to represent command line parameters: e.g. %1, %2, ...
    Two percent signs in a batch file are treated like a single percent sign in a command: e.g. %%f
    When using variables in execute code, use 2 percent signs. More info here
ECHO Hello World!
Prolog
  • Requirements: NO requirements, works with Tau-Prolog.
  • Important: Add your queries after a line "% query" in the code block like in the following
likes(john, pizza).
likes(john, cheese).
likes(jane, beer).

% query
likes(john, X).
Groovy
  • Requirements: Groovy is installed and the correct path is set in the settings.
def hello(name){  
	println "Hello ${name}!" 
}  

def helloClosure = {  
	println "Hello ${it}!" 
}  
  
hello("Bob")
  
helloClosure "Bob"
Golang
  • Requirements: Golang is installed and correct path is set in the settings(go binary is available).
  • Every code block must contain package declaration and a main function.
package main

import "fmt"

func main() {
	fmt.Println("Hello World")
}
Rust
  • Requirements: Cargo is installed and correct path is set in the settings(cargo binary is available).
  • cargo-eval is installed. Install using cargo install cargo-eval.
  • Import statements and external crates is supported by cargo-eval. Read their documentation.
  • Every code block must have a main function.
fn main() {
	println!("Hello World");
}
Kotlin
  • Requirements: Kotlin is installed and correct path is set in the settings.
hello(name: String) {
	println("Hello $name!")
}

hello("Bob")
Wolfram Mathematica
  • Requirements: Mathematica is installed and correct path is set in the settings.
  • You can add -cloud as argument in the settings to use the Wolfram Cloud instead of the local installation.
Haskell
  • You can either use runghc (compiler) or ghci (interpreter) to run your code.
    • runghc requirements:
      • runghc and ghc are installed and correct paths are set in the settings.
      • Every code block must contain a main function.
    • ghci requirements:
      • ghci is installed and correct path is set in the settings.
      • If you have a main function you have to manually call it.
mySum:: Num a => a -> a -> a
mySum a b = a+b
Scala
  • Requirements: Scala is installed and the correct path is set in the settings.
println("Hello, World!")
Racket
  • Requirements: Racket is installed and the correct path is set in the settings.
"Hello, world!"
Ruby
  • Requirements: Ruby is installed and the correct path is set in the settings.
puts "Hello, World!"
Octave
  • Requirements: Octave is installed and the correct path is set in the settings.
exp(i*pi)

x = -10:0.1:10;
plot (x, sin(x));

(Thanks to Michael M. Tung for the code example.)

  • Figures are set to invisible by default. They are store in a file and directly embedded in the note.
Maxima
  • Requirements: Maxima is installed and the correct path is set in the settings.
integrate(x,x);
plot2d(sin(x), [x,0,%pi]);

(Thanks to Michael M. Tung for the code example.)

  • By default, plots are saved in a file and directly embedded in the note.
OCaml
  • Requirements: OCaml is installed and the correct path is set in the settings.
print_endline "Hello, OCaml!"
Swift
  • Requirements: Swift is installed and the correct path is set in the settings.
print("Hello, world!")

Squiggle: For Squiggle support take a look at the Obsidian Squiggle plugin by @jqhoogland.

Support for the following is planned:

  • Matlab
  • Julia Lang

Open for suggestions.

Magic Commands ๐Ÿช„

Magic commands are some meta commands that can be used in the code block. They are processed by the plugin before the source code is executed.

The following magic commands are supported:

  • @vault_path: Inserts the vault path as string (e.g. "/User/path/to/vault")
  • @vault_url: Inserts the vault url as string. (e.g. "app://local/path/to/vault")
  • @note_path: Inserts the vault path as string (e.g. "/User/path/to/vault/Note.md")
  • @note_url: Inserts the vault url as string. (e.g. "app://local/path/to/vault/Note.md")
  • @title: Inserts the note title as string.
  • @show(ImagePath): Displays an image at the given path in the note.
  • @show(ImagePath, Width, Height): Displays an image at the given path in the note.
  • @show(ImagePath, Width, Height, Alignment[center|left|right]): Displays an image at the given path in the note.
  • @html(HtmlSource): Displays HTML in the note

(@show(...) and @html(...) are only supported for JavaScript and Python yet.) (The old commands @note and @vault are still supported, but may be removed in the future.)

Examples for the magic commands with Python:

print("Vault path:", @vault_path)
print("Vault url:", @vault_url)

print("Note path:", @note_path)
print("Note url:", @note_url)

print("Note title:", @title)
@show("image.png")
@show("image.png", 100, 100)
@show("https://upload.wikimedia.org/wikipedia/commons/d/de/TestScreen_square.svg", 10%, 10%, "center")
@html("<h1>HTML Caption</h1>")
@html('''
<svg width="100%" height="100%" viewBox="0 0 600 600" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  <circle cx="300" cy="300" r="250" style="fill:peru;" />
  <circle cx="200" cy="250" r="50" style="fill:black;" />
  <circle cx="400" cy="250" r="50" style="fill:black;" />
  <circle cx="190" cy="230" r="20" style="fill:white;" />
  <circle cx="390" cy="230" r="20" style="fill:white;" />
  <circle cx="250" cy="400" r="85" style="fill:saddlebrown;" />
  <circle cx="350" cy="400" r="85" style="fill:saddlebrown;" />
  <ellipse cx="300" cy="380" rx="50" ry="35" style="fill:black;" />
  <ellipse cx="130" cy="100" rx="110" ry="70" style="fill:saddlebrown;"/>
<ellipse cx="470" cy="100" rx="110" ry="70" style="fill:saddlebrown;" />
</svg> 
''')

Try it out yourself!

Example how to use the magic commands.

Running in Preview โฉ

Adding run- before the language name in the code blocks (as in the example below) renders the code block in the preview already. This allows you to execute the code in the preview.

```run-python
def hello(name):
print("Hello", name)

    if __name__ == "__main__":
        hello("Eve")

Code Block Arguments ๐Ÿท

Code blocks support specifying additional arguments in the form {key='value', otherkey=['val1', 'val2']}. Add them to code blocks like so:

```python {label='my label'}
print('my labelled code block')
```

Global Code Injection and Reusing Code Blocks ๐Ÿ“˜

Sometimes it is helpful to have code that is executed before or after each other block of the same language. This plugin supports this in a few ways:

Global Injection in the Settings

All languages have a 'global inject' option in the settings that allows defining code to be added to the top of every single code block on a per-language basis. Code reuse fully works with all languages, and all existing magic commands, including showing images, and inline plot outputs. This can be used to define e.g. often used functions or import your favourite packages or libraries.

Note-wide Pre- and Post-Code Blocks

You can specify the pre argument to create a block that is executed before each following code block:

```python {pre}
import pandas as pd
```

This code block is added before each python block you define below in the note and import the pandas package.

post blocks work the same way, but the code in post blocks is executed after your other code blocks.

Pre/Post blocks will only apply to code blocks defined below them, and will only apply to code blocks from the same language.

You can also have a pre and post block at the same time by specifying {pre, post}

Note, the pre/post arguments are special in that you don't need to explicitly state a key/value pair, however you can do so if you wish:

{pre} is equivalent to {export='pre'}, {pre, post} is equivalent to {export=['pre', 'post']}.

Labelled Code Blocks

You can label specific code blocks with the label='string' argument, then import them explicitly in other blocks with the import='string' or import=['string1', 'string2', ...] argument so they aren't automatically imported as with pre / post blocks:

```python {label='block 1'}
print('running block 1')
```

```python {label='block 2'}
print('running block 2')
```

```python {import=['block 1', 'block 2']}
print('should run block 1 and 2')
```

Labelled code blocks will be executed before the code block being run, however after global injects and pre blocks.

Ignoring Code Exports

In case you want to manually ignore specific exports in a code block like pre / post / global exports, you can do so with the ignore argument that accepts either pre, post, global, an array of any of these 3, or all to ignore all exports:

```python {ignore='all'}
print('should not run any global injects or pre / post blocks')
```

```python {ignore=['global', 'pre']}
print('should not run any pre blocks or global injects')
```

Notebook Mode

A few languages (currently JS and Python) support Notebook Mode. If a language is using Notebook Mode (configurable in Settings), then all code blocks in a given file will execute in the same environment.

Variables functions, etc. defined in one code block will be available in other code blocks. Code blocks are executed on demand; the order of code blocks in the file does not affect the order in which they are executed:

```js
console.log(f)
```
```js
var f = 3;
```

Running the first code block, then the second, then the first again will give:

Uncaught ReferenceError: f is not defined
undefined
3

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

Misc ๐Ÿ“ฆ

Style Settings ๐ŸŽจ

This plugin supports customising styles using the Style Settings plugin or the Obsidian Code Styler plugin.

Other Tools

Take a look at the Obsidian Tools python package to find some useful tools for interacting with your vault.

Installation ๐Ÿ’พ

In your vault go to Settings > Community plugins > Browse and search for "Execute Code". Select the plugin, install it and activate it.

or

Follow this link and click "Open in Obsidian".

Locating Path Settings ( ex. JavaScript | Node )

To avoid or resolve errors from an incorrect path.

('where' for Mac and Windows) --- (for Linux Users, replace 'where' with 'which')

  1. In your terminal, type 'where node' Type 'where node' in terminal
  2. Copy path from terminal ( ex. /opt/homebrew/bin/node )
  3. Paste in path under settings ( ex. Node path ) Update path under settings with path from step 2

Warning โš 

Do not execute code from sources you don't know or code you don't understand. Executing code can cause irreparable damage.

Known Problems ๐Ÿ› 

  • On Linux, Snap/Flatpak/AppImage installations of Obsidian run in an isolated environment. As such, they will not have access to any of your installed programs. If you are on Linux, make sure to install the .deb version of Obsidian. If your distro isn't compatible with .deb files, you may see issues.
  • Missing when run button after switching the theme: Try to close and reopen your notes and wait for a few minutes. It seems like obsidian doesn't call the postprocessors after the theme switch.
  • Pre- / Post-blocks may not be executed if the file contains duplicate code blocks.
  • In Python, Embed Plots may not be off while Notebook Mode is on

Future Work ๐Ÿ“‘

  • Notebook Mode similar to Jupyter
  • Error warning when the execution fails (e.g. when python isn't installed)
  • Test if this plugin works in combination with dataview.

Contribution ๐Ÿค

All contributions are welcome. Just create a merge request or email me: tim.wibiral(at)uni-ulm.de

The bullet points in Future Work are a good starting point if you want to help.

Contributors โ™ฅ

List of contributors to this project.

Made with contrib.rocks.

obsidian-execute-code's People

Contributors

afonsofrancof avatar andremeireles avatar cbarond avatar chlohal avatar davnn avatar drsect0r avatar gluton-official avatar hannesdelbeke avatar hanwolf3d avatar ihomway avatar jamesbtan avatar latenitecoding avatar mayurankv avatar melo-afk avatar mihai-vlc avatar milan338 avatar nfiles avatar nieomylnieja avatar pspiagicw avatar qiaogaojian avatar raphaelremorosa avatar rmchale avatar santry avatar scoopsdev avatar slar avatar standtrooper avatar thylane avatar twibiral avatar vkmb avatar zanets avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

obsidian-execute-code's Issues

matplotlib svg embed error (insider v0.15.2)

Hi thanks for the awesome plugin!

I get the following error when checking the option to embed the "Embed Python Plots" on the latest insider obsidian build (v0.15.2)
I read they changed a bunch of things with codemirror behind the scenes so perhaps it's relevant for you!

image

[FR] Implementation of interactive plotly charts (like the matplotlib implementation)

Hi, thanks again for a great obsidian plugin. Would love to be able to make plotly charts in obsidian to create an interactive data representation to spice up the notes.

Plotly is a js based charting library also supported in python: https://github.com/plotly/plotly.py

Plotly have been implemented into jupyterlab through an npm plugin: https://www.npmjs.com/package/jupyterlab-plotly

Similarly it would also be nice to implement ipython widgets to the output: https://github.com/jupyter-widgets/ipywidgets
ipython widgets are interactive HTML widgets for Jupyter notebook that for instance is used by pandas to generate great looking interactive tables, among many other things.

If interactive outputs are implemented it would also be useful if the code block output is stored together with the notes. Currently the outputs gets cleared if you leave the note.

Thanks a lot =)

Feature Request : Add switch to export as HTML content

Hi,
Is it possible to add a switch near the button Run or in the menu to be able to export as html ?

I have found that if I change this line

this.stdoutElem.setText(this.stdoutText);

To

this.stdoutElem.innerHTML = (this.stdoutText);

It can export as a html content and not be interpreted only as text.

Why would I like this new feature ?

To be able to export images. With that, it will be possible to execute code and have the output (like matplotlib graphs) directly in Obsidian (I tried and it work).

Here a screenshot of the content as html.
image

Thank you.

[FR] Reuse code blocks defined above

When writing in a document, it might be helpful to be able to define some functions in code blocks above, then use them later in code blocks below, kind of like Jupyter notebooks. I'm working on a prototype, it looks like this right now:

image

Right now, it works by making a distinction between 'runnable' and 'non-runnable' code blocks, where runnable code blocks have a main function defined. You can toggle the feature in the settings per-language, and when enabled, it prevents running code blocks without a main function, and those code blocks are instead prepended to any runnable code blocks. It will also only prepend any code blocks above the one being run. I'd like to get some feedback on this idea to see how it can be developed further.

As a consequence of how the feature is implemented, it should be trivial to implement both solutions proposed by by @twibiral in #22 (comment) and close #22, however the pre and post scripts would be restricted to the note they are defined in.

[Feature] Read ```{x} for Rmd/quatro compatability

Rmarkdown and quatro are commonly used markdown derivatives used in data science. In these formats, code blocks begin with ```{name} rather than ```name (eg. ```{r} or ```{python} instead of ```r or ```python). Would it be possible to read and execute code blocks with the language name in curly brackets the same as if the curly brackets weren't there. This would make it easy to edit rmarkdown/quartro documents within obsidian.

I feel like this would only be a minor change and I tried to find where in the code to make it, but got lost in all the unfamiliar javascript.

Can't run Rust

I get this error every time I try to run Rust code.
error: could not find Cargo.toml in /home/user or any parent directory
My cargo path is set in the settings.
I think this might be looking for a Rust project where one doesn't exist.

Restructure src directory

Right now, all config files are in the src directory, could config files be moved outside into root and have src left for implementation only? With configs in src, developers must cd into src, but then all code and configs are still in the same directory.

Code formatting

With the repo getting larger, it could be good to have formatting set up with e.g. prettier to enforce a consistent style.

Golang support

Hi, It would be awesome if Golang support is added. I may look into integrating it myself, but I have limited experience in TypeScript/Javascript.

Typescript Not Working

With ts-node path set to /opt/homebrew/bin/ts-node, I get this error:
Screen Shot 2022-10-02 at 18 00 58

With ts-node path set to /opt/homebrew/bin/npx ts-node I get this error:
Screen Shot 2022-10-02 at 18 02 47
Also tried setting ts-node as an argument

Also tried just ts-node, and settings ts-node as an argument under npx.

Everything works fine from the terminal. Any ideas?

Thanks for a brilliant plugin, I absolutely love this!

Running macOS

On windows, "\" are replaced with "/" in option paths and snippet do not run

Windows-only bug :
If you try to enter a path with backslashes in the plugin options, and then close the option panel and reopen it, then "\" are systematically replaced with "/" .
Therefore the run button will trigger an ENOENT error on javascript or python snippets because the windows executable (resp. node.js and python) is not found.

The workaround is to edit the file data.json and replace "/" with "". Then it works. But this should not be necessary.

[FR] Piston support

Piston is a code execution server that supports a ton of languages, all of which run as isolated scripts. I feel support would be a very desirable addition in a notebook like enviroment where you want to just quickly run some test/demo code. There are a couple drawbacks like no network access however, so this would probably be an opt-in feature.

If your curious, I made a quick poc on my fork.

Rust support

I been using your plugin for python and it works great, how you kindly add Rust support ?

R Code Injection/Code Reuse not working

If I put the following code in an R code block, it will output a scatterplot as expected.

library(ggplot2)
scatterplot <- ggplot() +
	geom_point(aes(x=rnorm(10),y=rnorm(10)))
plot(scatterplot)

However, if I move the library(ggplot2) statement to the "Inject R code" box in the plugin settings or to a pre-r code block, I get the following error message:

Error in ggplot() : could not find function "ggplot"
Execution halted

In this example, it seems as if the package cannot load unless I include it in the original code block. Is this a bug, or am I using these two features incorrectly?

support numpy

numpy as a very popular python package is not supported.

import numpy as np
a = np.random.rand(10)
b = np.random.rand(10)
c = np.dot(a, b)

I have number pip installed and then run above script and set the python path to be where my python was installed:
/Library/Frameworks/Python.framework/Versions/3.10/bin/python3

however when run this script, i saw error on Traceback (most recent call last), such error does not exist outside of obsidian, and i have tried uninstall/install numpy serveral times but no magic:

Importing the numpy C-extensions failed. This error can happen for
many reasons, often due to issues with your setup or how NumPy was
installed.

We have compiled some common reasons and troubleshooting tips at:

    https://numpy.org/devdocs/user/troubleshooting-importerror.html

Please note and check the following:

  * The Python version is: Python3.10 from "/Library/Frameworks/Python.framework/Versions/3.10/bin/python3"
  * The NumPy version is: "1.23.2"

and make sure that they are the versions you expect.
Please carefully study the documentation linked above for further help.

Original error was: dlopen(/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/numpy/core/_multiarray_umath.cpython-310-darwin.so, 0x0002): tried: '/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/numpy/core/_multiarray_umath.cpython-310-darwin.so' (mach-o file, but is an incompatible architecture (have 'x86_64', need 'arm64e'))

Failed to load some notes after updating

Hello, I have a problem after updating to the latest version.
The message is: "Failed to load diagrams.md notes
Cannot read properties of null (reading 'vaultpath')
"
There is no code in these notes
Everything is ok when I disable the plugin.

Environment
OS Windows 11 (21H2)
Obsidian Version : 0.15.9

Rust support

It would be awesome if this plugin supported rust. I have a lot of notes and samples that would like to run.
Looking at the code, it seems it should be possible. I think I could provide a PR somewhere in the future.

Thanks!

[FR] open to run scripts before and after running code

Just a thought people may be using languages in particular setups or environment using tools such as asdf, nx, nvm, pyenv etc or may need to set configuration up in the background such as move files, importing, database, downloads, package manager etc.

You could get around this by allowing the user to run setup and teardown scripts before and after code runs.
you could have default scripts in the settings page and fields in the forntmatter.

Failure on pyplot with `numpy.sin`

Hey! Amazing work with this library! Overall everything has worked but had some issues with plotting.

I'm running a fairly simple example and have had some limited success plotting, however I've had a number of suprises.

Using numpy.sin causes a very weird error:

import seaborn as sns
import matplotlib.pyplot as plt
sns.set_style("darkgrid")
import matplotlib.pyplot as plt
import numpy

x = numpy.array(list(range(10)))
y = numpy.sin( x )

plt.plot( x , y )
plt.show()

And the error:

Traceback (most recent call last):
  File "C:\Users\Sup\AppData\Local\Temp\temp_1659324923767.py", line 11, in <module>
    import io; __obsidian_execute_code_temp_pyplot_var__=io.StringIO(); plt.plot(); plt.savefig(__obsidian_execute_code_temp_pyplot_var__, format='svg'); plt.close(); print(f"<div align=\"center\">{__obsidian_execute_code_temp_pyplot_var__.getvalue()}</div>")
  File "C:\Users\Sup\Anaconda3\envs\triton\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u2212' in position 7994: character maps to <undefined>

Bug when using line numbering

When I use the line number display function of codemirror options, the python code cannot run. However, when using the code block enhancer plugin to display line numbers, I did not encounter the problem of inability to run.

However, this plugin sometimes conflicts with code block enhancer. When starting obsidian, it fails to start, and no run button appears. Sometimes restarting ob or reloading the plugin can solve this problem.

type() function not working in python

For some reason I cannot run the print out a data type.

e.g.

print(type(35))

This simply does not return anything in obsidian although we would expect it to return int

[FR] Better plot support for R

The plugin only supports only normal plots generated by plot(...). Add support for more commands (e.g. boxplot(...)).

This issue replaces #59

[FR] Run Command

Thanks for this amazing plugin!

A small feature request: add a command to run the codeblock when the cursor is in it. Then we can assign a hotkey to it, without the need to hit the run button using a mouse.

This is implemented in Snippets Plugin.

Java Support

Java support is in the future plans. From what I can gather JDK11 and after, support running single file programs without the intermediate compiling step.
Source: https://www.infoq.com/articles/single-file-execution-java11/

I have personally tested and confirmed the above article.
It means a single-file java program can be run using java program.java .
But this means

  • We have locked the user to use JDK11 and higher.

Can we use it ? If yes implementing it is easy.

Inconsistency with python version and modules (wrong python binary being run ?)

On options, I have set python path to be '/user/bin/python3'.
When I run the following code

import sys
print(sys.executable)

it prints /usr/bin/python3


/usr/bin/python3 is version 3.10.4 and has matplotlib installed (as you can see on the image below)
image


However, when running any script on obsidian-execute-code with the python parameter "--version" set under the plugin options, the result is always Python 3.6.9, and when importing matplotlib, it says ModuleNotFoundError: No module named 'matplotlib'


Any idea of what might solve? Thanks!

Kotlin Support

I did this out of order, but I have added Kotlin support and am creating this issue to pair with my PR.

[FR] Different Syntax for Codeblock Identifier

Thanks for this amazing plugin!

Global code injection is a game changer. However, I am a little unsure about the future-proofness of the syntax, i.e., pre-, post-, and run- prefixes. Have you considered the convention used in other Markdown apps like

Then the syntax could be:

```python {run pre}
import numpy as np
```

By using this, the Markdown parser still recognizes it as a Python codeblock, hence things like syntax highlighting persist.
Also this syntax is more flexible and allows combinations.

Install problems only at first use.

I use this code (Win10) with line numbers, Python 3.8 path: C:\Python38\python.exe, dark theme:

def hello(name):
    print(name)

if __name__ == "__main__":
    hello("Eve")

When changing from ITS Theme to Standard Obsidian Theme, there is no "copy" and "run"-Button anymore.
Closing and restarting the application does not solve the problem.
But when I wait (~1-2 minutes?), the buttons "copy" and "run" appear again (hovering nesseccary).
After this, I can use the plugin without problems: The buttons don't dissapear anymore.
(The "clear" button is always visible.)

At least in these themes, the buttons have to hover with the mouse to see them:
80s Neon
Obsidian Nord
Dracula for Obsidian
Things
Night Owl
Deep Work (The copy button gets colored, the run button not.)
Blue Topaz, Obsidianite (only the run button can be made visible via hover; the copy button is an icon, not well positioned)

My external plugins are

  • Advances Tables
  • Execute Code
  • Kanban
  • Mind Map
  • Obsidian Git
  • Outliner
  • Ozan's Image in Editor Plugin

The main problem is, that every user has to figure out this by himself. Could you please add a hint in the installing documentation?
Example path with included python.exe for windows users.
Waiting before giving up. ;-)

Security concern with spawning in shell

The current implementation of spawning in shell seems like a security hole. Issues with programs not found should be fixable by providing an absolute path to the binary in the settings. This might be an inconvenience to some users, but it should add some protection against malicious code. If nothing else, I think it would also be good to sanitise the commands being passed to spawn with something like shell-quote. It might be good to have a toggle for running shell / powershell that's disabled by default to further protect users.

Inline code error inside tables

Inline code (single backticks) does not work inside tables. Switching to another file and then switching back will fail to open the file and produce the notice Failed to load "Lorem Ipsum.md". Cannot read properties of null (reading 'vaultPath').

More organized settings

The settings tab is getting a bit messy. It would be great for the user if we only displayed one language's settings at a time, and offered a dropdown menu to pick which one is open.

[BUG] Inline plots don't always work

When using R for example,

library(datasets)
data(mtcars)
boxplot(mtcars$mpg, col="green")

does not work, throwing the error could not find function "boxpng". I suspect this is because of the implementation in Magic.ts where it uses the regex /plot\(.*\)/g to capture everything with plot and replaces it with a call to png, however like in this example, this doesn't always work. It looks like the inline plots will only work specifically for calls to plot(), and Python is similarly limited to only plt.show().

[FR] "Run all cells" command

Hi there,

Is there any possibility of running all code blocks using the command pallet at once?

This would be great!

[FR] access to dataviewjs dv variable

Hello, this would be nice if a javascript snippet could have access to the dataviewjs dv variable (provided the dataview plugin is also installed in obsidian).
This would allow js code snippets to create on the fly html elements like text, divs or buttons in the doc in preview mode (just below the snippet) and to attach event handlers to them.
This might not be too difficult to do, as dataview already provides an API for plugin developpers :https://blacksmithgu.github.io/obsidian-dataview/plugin/develop-against-dataview/

for example, this works in a dataviewjs snippet, but it would be nice if it worked also right in a js snippet by clicking the "run" button

const bouton=dv.el("button","hello");
const inp = dv.el("input","type something");
const sortie = dv.el("p","???");

bouton.addEventListener('click', (e) => 
		{ inp.value="hello, edit me!"});
inp.addEventListener('input', (e) => 
		{test(e.target.value)});
function test(val) {
	sortie.innerHTML=val;
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.