Scripting Obsidian
Make what you want to do in Obsidian easier with a dash of JavaScript.
Obsidian+PR Cookbook - 𝕏 - YouTube - Official Obsidian Docs
Obsidian is at its core an extensible markdown editor. You can extend it with plugins, but sometimes there is no plugin to do what you want, often because your tasks is quite specific to what you are trying to do. I wrote Plugin REPL to help you quickly script Obsidian for some tasks.
For this, you might want to do a tiny bit of scripting. From my perspective there are three sorts of thinks you might want to automate in Obsidian.
Content that gets generated based on content you have already made
Templates
Code that you want to run from the Command Palette or hotkeys
Generated content
For this you tend to want to “embed” the code to generate the content into your page. People tend to use dataview for this. Dataview has two languages - a query language inspired by SQL and JavaScript language for more general scripting.
Here is a query which outputs all nodes with two tags.
```dataview
LIST from #howto AND #javascript
```
This can be good to add to “index / structure notes” to index other notes.
JavaScript queries can do more complicated and dynamic things. For example the query below returns the number of pages with identically tags to the current page.
```dataviewjs
let pageTabs = dv.current().tags
let matchingQuery = "LIST FROM " + pageTabs.map((x) => "#" + x).join(" AND ")
let result = await dv.query(matchingQuery)
dv.paragraph(result.value.values.length)
```
A thing to bear in mind about this code is that it is reexecuted when you reopen the page or when things change so it should not have side effects. For example, you for sometihng like a command you might want it to prompt for text.
Templates
It is quite common to want to generate content in a consistent form (potentially depending upon custom values and insert it into your document). Templater is a good tool for this.
Custom Commands
If you want to run a command that can do things and that you call often (such as creating new notes, or inserting them into your document) then you can use Plugin REPL.
Here is a command to insert the current timestamp in Plugin REPL.
newCommand(function insert_timestamp() {
insert((new Date()).toISOString())
})
People also have used Templater templates to for “commands” since when executed they can run javascript code which can have side effects. If you have more complicated functionality or want to share your code you might want to write your own plugin.
This is part of a cookbook of things that you can do with Obsidian and Plugin REPL. If you found this interesting you might like to read some other pages I might looking at some examples of thinks you can do by automating Obsidian, such as this timeline of twitter posts.
I am not afilliated with Obsidian, I am the author of Plugin REPL. I am @readwithai - read about me here.