silverbulletmd / silverbullet

The knowledge tinkerer's notebook
https://silverbullet.md
MIT License
2.48k stars 179 forks source link

[Plugs] Expose a syscall to register a new function #1004

Open zefhemel opened 2 months ago

zefhemel commented 2 months ago

You can currently only define custom functions (https://silverbullet.md/Functions) in space script, not through plugs. This is a bit silly and should be made possible.

Likely design:

system.registerFunction({name: "myFunction"}, `() => 10`);

The second argument will need to be a string with JavaScript code (to be eval'ed) because custom functions must (for performance reasons) run in the main browser thread. So we need to ship the code from a plug over to the main thread in JavaScript text form, unfortunately.

justyns commented 2 months ago

This would be a great addition!

You might be able to convert a function to a string and then eval it later? It'd need some testing, but looks like it might be possible: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/toString

zefhemel commented 2 months ago

You can, but you'd lose regular JavaScript semantics like closures (referencing variables outside the function). So I'd like to avoid weird surprises like that.