ytliu74_obsidian-pseudocode/main.ts

375 lines
8.6 KiB
TypeScript
Raw Normal View History

2023-03-14 14:13:41 +00:00
import {
App,
Editor,
EditorPosition,
EditorSuggest,
EditorSuggestContext,
EditorSuggestTriggerInfo,
MarkdownView,
2023-03-14 14:13:41 +00:00
Plugin,
PluginSettingTab,
Setting,
TFile,
} from "obsidian";
2023-03-13 11:40:20 +00:00
import * as pseudocode from "pseudocode";
2023-03-13 07:05:19 +00:00
2023-04-29 05:15:40 +00:00
// This is the setting for pseudocode.js
interface PseudocodeJsSettings {
2023-03-14 14:13:41 +00:00
indentSize: string;
commentDelimiter: string;
lineNumber: boolean;
lineNumberPunc: string;
noEnd: boolean;
captionCount: undefined;
2023-03-13 07:05:19 +00:00
}
2023-04-29 05:15:40 +00:00
// Setting for this plugin
interface PseudocodeSettings {
blockSize: number;
jsSettings: PseudocodeJsSettings;
}
2023-03-13 11:40:20 +00:00
const DEFAULT_SETTINGS: PseudocodeSettings = {
2023-04-29 05:15:40 +00:00
blockSize: 99,
jsSettings: {
indentSize: "1.2em",
commentDelimiter: "//",
lineNumber: false,
lineNumberPunc: ":",
noEnd: false,
captionCount: undefined,
}
2023-03-14 14:13:41 +00:00
};
2023-03-13 07:05:19 +00:00
const PseudocodeBlockInit =
"```pseudo\n\t\\begin{algorithm}\n\t\\caption{Algo Caption}\n\t\\begin{algorithmic}\n\n\t\\end{algorithmic}\n\t\\end{algorithm} \n```";
2023-03-17 03:03:13 +00:00
const BLOCK_NAME = "pseudo";
2023-03-13 11:40:20 +00:00
export default class PseudocodePlugin extends Plugin {
settings: PseudocodeSettings;
2023-03-14 14:13:41 +00:00
async pseudocodeHandler(
source: string,
el: HTMLElement,
ctx: any
): Promise<any> {
2023-04-29 05:15:40 +00:00
const blockDiv = el.createDiv({ cls: "pseudocode-block" });
const blockWidth = this.settings.blockSize;
blockDiv.style.width = `${blockWidth}em`;
const preEl = blockDiv.createEl("pre", { cls: "code", text: source });
2023-03-13 11:40:20 +00:00
2023-03-24 11:52:02 +00:00
try {
2023-04-29 05:24:02 +00:00
pseudocode.renderElement(preEl, this.settings.jsSettings);
2023-03-24 11:52:02 +00:00
} catch (error) {
console.log(error);
2023-04-29 05:15:40 +00:00
const errorSpan = blockDiv.createEl("span", { text: "\u274C " + error.message });
errorSpan.classList.add("error-message");
2023-04-29 05:15:40 +00:00
blockDiv.empty();
blockDiv.appendChild(errorSpan);
2023-03-24 11:52:02 +00:00
}
2023-03-13 11:40:20 +00:00
}
2023-03-13 07:05:19 +00:00
async onload() {
await this.loadSettings();
2023-03-14 14:13:41 +00:00
this.registerMarkdownCodeBlockProcessor(
2023-03-17 03:03:13 +00:00
BLOCK_NAME,
2023-03-14 14:13:41 +00:00
this.pseudocodeHandler.bind(this)
);
// Register suggest
this.registerEditorSuggest(new PseudocodeSuggestor(this));
2023-03-13 07:05:19 +00:00
// This adds a settings tab so the user can configure various aspects of the plugin
2023-03-13 11:40:20 +00:00
this.addSettingTab(new PseudocodeSettingTab(this.app, this));
2023-03-13 07:05:19 +00:00
// Auto-gen pseudocode block command.
this.addCommand({
id: "pseudocode-in-obs",
name: "Insert a new pseudocode block",
editorCallback: (editor: Editor, view: MarkdownView) => {
editor.replaceSelection(PseudocodeBlockInit);
},
});
2023-03-13 07:05:19 +00:00
}
onunload() { }
2023-03-13 07:05:19 +00:00
async loadSettings() {
2023-03-14 14:13:41 +00:00
this.settings = Object.assign(
{},
DEFAULT_SETTINGS,
await this.loadData()
);
2023-03-13 07:05:19 +00:00
}
async saveSettings() {
await this.saveData(this.settings);
}
}
2023-03-13 11:40:20 +00:00
class PseudocodeSettingTab extends PluginSettingTab {
plugin: PseudocodePlugin;
2023-03-13 07:05:19 +00:00
2023-03-13 11:40:20 +00:00
constructor(app: App, plugin: PseudocodePlugin) {
2023-03-13 07:05:19 +00:00
super(app, plugin);
this.plugin = plugin;
}
display(): void {
2023-03-13 11:40:20 +00:00
const { containerEl } = this;
2023-03-13 07:05:19 +00:00
containerEl.empty();
2023-03-14 14:13:41 +00:00
containerEl.createEl("h1", { text: "Pseudocode Plugin Settings" });
2023-03-13 07:05:19 +00:00
2023-04-29 05:15:40 +00:00
// Instantiate Block Size setting
new Setting(containerEl)
.setName("Block Size")
.setDesc(
"The width of the pseudocode block. The unit is 'em'." +
" The default value is 99, which will work as the max width of the editor." +
" '30' looks good for me."
)
.addText((text) =>
text
.setValue(this.plugin.settings.blockSize.toString())
.onChange(async (value) => {
this.plugin.settings.blockSize = Number(value);
await this.plugin.saveSettings();
})
);
2023-03-13 11:40:20 +00:00
// Instantiate Indent Size setting
2023-03-13 07:05:19 +00:00
new Setting(containerEl)
2023-03-13 11:40:20 +00:00
.setName("Indent Size")
2023-03-14 14:13:41 +00:00
.setDesc(
"The indent size of inside a control block, e.g. if, for, etc. The unit must be in 'em'."
)
.addText((text) =>
text
2023-04-29 05:15:40 +00:00
.setValue(this.plugin.settings.jsSettings.indentSize)
2023-03-14 14:13:41 +00:00
.onChange(async (value) => {
2023-04-29 05:15:40 +00:00
this.plugin.settings.jsSettings.indentSize = value;
2023-03-14 14:13:41 +00:00
await this.plugin.saveSettings();
})
2023-03-13 11:40:20 +00:00
);
// Instantiate Comment Delimiter setting
new Setting(containerEl)
.setName("Comment Delimiter")
.setDesc("The string used to indicate a comment in the pseudocode.")
2023-03-14 14:13:41 +00:00
.addText((text) =>
text
2023-04-29 05:15:40 +00:00
.setValue(this.plugin.settings.jsSettings.commentDelimiter)
2023-03-14 14:13:41 +00:00
.onChange(async (value) => {
2023-04-29 05:15:40 +00:00
this.plugin.settings.jsSettings.commentDelimiter = value;
2023-03-14 14:13:41 +00:00
await this.plugin.saveSettings();
})
2023-03-13 11:40:20 +00:00
);
// Instantiate Show Line Numbers setting
new Setting(containerEl)
.setName("Show Line Numbers")
.setDesc("Whether line numbering is enabled.")
2023-03-14 14:13:41 +00:00
.addToggle((toggle) =>
toggle
2023-04-29 05:15:40 +00:00
.setValue(this.plugin.settings.jsSettings.lineNumber)
2023-03-14 14:13:41 +00:00
.onChange(async (value) => {
2023-04-29 05:15:40 +00:00
this.plugin.settings.jsSettings.lineNumber = value;
2023-03-14 14:13:41 +00:00
await this.plugin.saveSettings();
})
2023-03-13 11:40:20 +00:00
);
// Instantiate Line Number Punctuation setting
new Setting(containerEl)
.setName("Line Number Punctuation")
2023-03-14 14:13:41 +00:00
.setDesc(
"The punctuation used to separate the line number from the pseudocode."
)
.addText((text) =>
text
2023-04-29 05:15:40 +00:00
.setValue(this.plugin.settings.jsSettings.lineNumberPunc)
2023-03-14 14:13:41 +00:00
.onChange(async (value) => {
2023-04-29 05:15:40 +00:00
this.plugin.settings.jsSettings.lineNumberPunc = value;
2023-03-14 14:13:41 +00:00
await this.plugin.saveSettings();
})
2023-03-13 11:40:20 +00:00
);
// Instantiate No End setting
new Setting(containerEl)
.setName("No End")
2023-03-14 14:13:41 +00:00
.setDesc(
"If enabled, pseudocode blocks will not have an 'end' statement."
)
.addToggle((toggle) =>
toggle
2023-04-29 05:15:40 +00:00
.setValue(this.plugin.settings.jsSettings.noEnd)
2023-03-14 14:13:41 +00:00
.onChange(async (value) => {
2023-04-29 05:15:40 +00:00
this.plugin.settings.jsSettings.noEnd = value;
2023-03-14 14:13:41 +00:00
await this.plugin.saveSettings();
})
2023-03-13 11:40:20 +00:00
);
2023-03-13 07:05:19 +00:00
}
}
2023-03-13 11:40:20 +00:00
2023-03-14 14:13:41 +00:00
class PseudocodeSuggestor extends EditorSuggest<string> {
plugin: PseudocodePlugin;
constructor(plugin: PseudocodePlugin) {
super(plugin.app);
this.plugin = plugin;
}
onTrigger(
cursor: EditorPosition,
editor: Editor,
file: TFile
): EditorSuggestTriggerInfo | null {
// perf: Use the "\" to tell whether to return.
const currentLineToCursor = editor
.getLine(cursor.line)
.slice(0, cursor.ch);
const currentLineLastWordStart = currentLineToCursor.lastIndexOf("\\");
// if there is no word, return null
if (currentLineLastWordStart === -1) return null;
2023-03-24 13:00:50 +00:00
// If is within a LaTeX $$ wrap, return null
const currentLineLastMoneyMark = currentLineToCursor.lastIndexOf("$");
if (currentLineLastMoneyMark != -1) return null;
2023-03-14 14:13:41 +00:00
const currentFileToCursor = editor.getRange({ line: 0, ch: 0 }, cursor);
const indexOfLastCodeBlockStart =
currentFileToCursor.lastIndexOf("```");
2023-03-17 03:03:13 +00:00
// check if this is a pseudocode block
const isPseudocode =
2023-03-14 14:13:41 +00:00
currentFileToCursor.slice(
indexOfLastCodeBlockStart + 3,
2023-03-17 03:03:13 +00:00
indexOfLastCodeBlockStart + 3 + BLOCK_NAME.length
) == BLOCK_NAME;
2023-03-14 14:13:41 +00:00
2023-03-17 03:03:13 +00:00
if (!isPseudocode) return null;
2023-03-14 14:13:41 +00:00
return {
start: { line: cursor.line, ch: currentLineLastWordStart },
end: cursor,
query: currentLineToCursor.slice(currentLineLastWordStart),
};
}
getSuggestions(
context: EditorSuggestContext
): string[] | Promise<string[]> {
const query = context.query;
2023-03-17 03:03:13 +00:00
const suggestions = this.pseudocodeKeywords.filter((value) =>
value.toLowerCase().startsWith(query.toLowerCase())
2023-03-14 14:13:41 +00:00
);
return suggestions;
}
renderSuggestion(value: string, el: HTMLElement): void {
el.addClass("suggestion");
const suggestContent = el.createDiv({ cls: "suggestion-content" });
suggestContent.setText(value);
}
selectSuggestion(value: string, evt: MouseEvent | KeyboardEvent): void {
if (this.context) {
const editor = this.context.editor;
const suggestion = value;
const start = this.context.start;
const end = editor.getCursor();
editor.replaceRange(suggestion, start, end);
const newCursor = end;
newCursor.ch = start.ch + suggestion.length;
editor.setCursor(newCursor);
this.close();
}
}
2023-03-17 03:03:13 +00:00
private pseudocodeKeywords: string[] = [
2023-03-14 14:13:41 +00:00
"\\begin{algorithmic}",
"\\begin{algorithm}",
"\\end{algorithmic}",
"\\end{algorithm}",
"\\caption{}",
"\\Procedure{}{}",
"\\EndProcedure",
"\\Function{}{}",
"\\EndFunction",
"\\Require",
"\\Ensure",
"\\Input",
"\\Output",
"\\State",
"\\Return",
"\\Print",
"\\For{}",
"\\EndFor",
"\\If{}",
"\\Elif{}",
"\\EndIf",
"\\While{}",
"\\EndWhile",
"\\Repeat",
"\\Until{}",
"\\Comment{}",
2023-03-14 14:13:41 +00:00
"\\{",
"\\}",
"\\$",
"\\&",
"\\#",
"\\%",
"\\_",
"\\gets",
"\\Call{}{}",
"\\And",
"\\Or",
"\\Xor",
"\\Not",
"\\To",
"\\DownTo",
"\\True",
"\\False",
2023-03-14 14:13:41 +00:00
"\\tiny",
"\\scriptsize",
"\\footnotesize",
"\\small",
"\\normalsize",
"\\Large",
"\\Huge",
2023-03-14 14:13:41 +00:00
"\\rmfamily",
"\\sffamily",
"\\ttfamily",
"\\upshape",
"\\itshape",
"\\slshape",
"\\scshape",
"\\bfseries",
"\\mdseries",
"\\lfseries",
"\\textnormal{}",
"\\textrm{}",
"\\textsf{}",
"\\texttt{}",
"\\textup{}",
"\\textit{}",
"\\textsl{}",
"\\textsc{}",
"\\uppercase{}",
"\\lowercase{}",
"\\textbf{}",
"\\textmd{}",
"\\textlf{}",
];
}