I don’t want to add every code block cpp or java.
can you provide someone?
I can give you this:
import * as obsidian from 'obsidian';
const LANGUAGE_OPTIONS = [
"bash",
"c",
"c++",
"c#",
"dart",
"go",
"hs", // Haskell
"java",
"js", // JavaScript
"kt", // Kotlin
"lua",
"objc", // Objective-C
"pl", // Perl
"php",
"ps1", // PowerShell
"py", // Python
"r",
"rb", // Ruby
"rs", // Rust
"scala",
"swift",
"ts" // TypeScript
] as const;
class OptionModal extends obsidian.SuggestModal<string> {
private resolvePromise: (value: string | null) => void;
constructor(app: obsidian.App, private options: string[]) {
super(app);
}
getSuggestions(query: string): string[] {
return this.options.filter(option =>
option.toLowerCase().includes(query.toLowerCase())
);
}
renderSuggestion(value: string, el: HTMLElement): void {
el.createEl("div", { text: value });
}
onChooseSuggestion(choice: string): void {
this.resolvePromise(choice);
}
async openAndGetValue(): Promise<string | null> {
return new Promise((resolve) => {
this.resolvePromise = resolve;
this.open();
});
}
}
const wrapWithTag = (selection: string, language: string): string => {
const cursor = '←→';
return `\`\`\`${language}\n${selection}${cursor}\n\`\`\``;
};
const insertCodeBlock = async (app: obsidian.App): Promise<void> => {
const editor = app.workspace.activeLeaf?.view?.editor;
if (!editor) return;
const selection = editor.getSelection();
const modal = new OptionModal(app, LANGUAGE_OPTIONS);
const language = await modal.openAndGetValue();
if (!language) return;
const wrappedText = wrapWithTag(selection, language);
editor.replaceSelection(wrappedText);
const content = editor.getValue();
const cursorPos = content.indexOf('←→');
if (cursorPos !== -1) {
const from = editor.offsetToPos(cursorPos);
const to = editor.offsetToPos(cursorPos + 2);
editor.replaceRange('', from, to);
editor.setCursor(from);
}
};
export class InsertCodeBlockPlugin extends obsidian.Plugin {
async onload() {
this.addCommand({
id: 'insert-code-block',
name: 'Insert Code Block',
callback: () => insertCodeBlock(this.app)
});
}
}
export async function invoke(app: obsidian.App): Promise<void> {
return insertCodeBlock(app);
}
Works on selection and no selection. Edit list of programming languages to your liking.
Save as ‘Insert-Code-Block.ts’. To be used with Codescript Toolkit. Shortcut can be bound to script.
Here’s some more potential useful info found on reddit:
https://www.reddit.com/r/ObsidianMD/comments/1fxrj7i/set_default_programming_language_for_code_blocks/
Personally, I don’t see how saving 3-4 keystrokes is worth setting all of this up.