Skip to content

Commit

Permalink
support [FR] custom js code to modify selectedText #77
Browse files Browse the repository at this point in the history
  • Loading branch information
Benature committed Mar 7, 2024
1 parent 4917681 commit 70536c9
Show file tree
Hide file tree
Showing 4 changed files with 113 additions and 6 deletions.
15 changes: 14 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,20 @@
# Changelog

## 2.6.0
🧱 [Todo Project](https://github.com/Benature/obsidian-text-format/projects/1)

## 🏗️ developed
> to be updated in the next version
- [feature] custom replacement
- [updated] callout format: auto select whole paragraph
- [feature] math mode:
- rename: Detect and convert characters to math mode (LaTeX)
- two characters (sub case): e.g. `a0` -> `$a_0$`
- [ ] More ignore case should be considered. For now: `/is|or|as|to|am|an|at|by|do|go|ha|he|hi|ho|if|in|it|my|no|of|on|so|up|us|we/g`
- simple calculation: e.g. `ab+cd` -> `$a_b+c_d$`
- sup case for `*`: e.g. `a*` -> `$a^*$`

## 2.6.0
- [feature] Convert wikiLinks to plain markdown links in selection ([#40](https://github.com/Benature/obsidian-text-format/issues/40))
- [feature] remove trailing spaces ([#61](https://github.com/Benature/obsidian-text-format/issues/61))
- [updated] decodeURI
Expand Down
24 changes: 20 additions & 4 deletions main.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Editor, MarkdownView, Plugin, Notice, debounce } from "obsidian";
import { removeWikiLink, removeUrlLink, url2WikiLink, convertWikiLinkToMarkdown } from "src/link";
import { FormatSettings, DEFAULT_SETTINGS, TextFormatSettingTab } from "src/setting";
import { array2markdown, table2bullet, capitalizeWord, capitalizeSentence, removeAllSpaces, zoteroNote, textWrapper, replaceLigature, ankiSelection, sortTodo, requestAPI, headingLevel, slugify, snakify, extraDoubleSpaces, toTitleCase } from "src/format";
import { array2markdown, table2bullet, capitalizeWord, capitalizeSentence, removeAllSpaces, zoteroNote, textWrapper, replaceLigature, ankiSelection, sortTodo, requestAPI, headingLevel, slugify, snakify, extraDoubleSpaces, toTitleCase, customReplace } from "src/format";

function getLang() {
let lang = window.localStorage.getItem('language');
Expand Down Expand Up @@ -297,6 +297,7 @@ export default class TextFormat extends Plugin {

this.debounceUpdateCommandWrapper();
this.debounceUpdateCommandRequest();
this.debounceUpdateCommandCustomReplace();
this.addCommand({
id: "decodeURI",
name: { en: "Decode URL", zh: "解码 URL", "zh-TW": "解碼 URL" }[lang],
Expand Down Expand Up @@ -351,6 +352,18 @@ export default class TextFormat extends Plugin {
});
});
}
debounceUpdateCommandCustomReplace() {
const lang = getLang();
this.settings.customReplaceList.forEach((customReplace, index) => {
this.addCommand({
id: `custom-replace-${index}`,
name: { "en": "Custom Replace", "zh": "自定义替换", "zh-TW": "自定義取代" }[lang] + " - " + customReplace.name,
editorCallback: (editor: Editor, view: MarkdownView) => {
this.textFormat(editor, view, "custom-replace", customReplace);
},
});
});
}

textFormat(editor: Editor, view: MarkdownView, cmd: string, args: any = ""): void {
var selectedText: string, replacedText;
Expand Down Expand Up @@ -593,17 +606,17 @@ export default class TextFormat extends Plugin {
replacedText = selectedText
// single character
.replace(
RegExp(pre + String.raw`([(͠]?[a-zA-Z])` + suf, "g"),
RegExp(pre + String.raw`([a-zA-Z])` + suf, "g"),
(t, t1) => {
// console.log(t1, t1.length, t1[0]) //2
// t1 = t1.replace(//g, String.raw`\tilde `);
return `$${t1}$`;
})
// double character
.replace(
RegExp(pre + String.raw`([a-z])([a-zA-Z0-9])` + suf, "g"),
(t, t1, t2) => {
if (/is|or|as|to/g.test(t)) { return t; }
// ignore cases
if (/is|or|as|to|am|an|at|by|do|go|ha|he|hi|ho|if|in|it|my|no|of|on|so|up|us|we/g.test(t)) { return t; }
return `$${t1}_${t2}$`;
})
.replace(
Expand Down Expand Up @@ -679,6 +692,9 @@ export default class TextFormat extends Plugin {
return;
})
return;
case "custom-replace":
replacedText = customReplace(selectedText, args);
break;
case "callout":
const wholeContent = editor.getValue();
let type = this.settings.calloutType;
Expand Down
9 changes: 8 additions & 1 deletion src/format.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Editor, MarkdownView, EditorPosition, App, requestUrl, TFile, Notice } from "obsidian";
import { FormatSettings } from "src/setting";
import { FormatSettings, customReplaceSetting } from "src/setting";
import { compile as compileTemplate, TemplateDelegate as Template } from 'handlebars';

import { off } from "process";
Expand Down Expand Up @@ -584,4 +584,11 @@ export function extraDoubleSpaces(editor: Editor, view: MarkdownView): void {
}
);
editor.setValue(content);
}

export function customReplace(text: string, s: customReplaceSetting): string {
s.data.forEach(data => {
text = text.replace(new RegExp(JSON.parse(`"${data.search}"`), "g"), JSON.parse(`"${data.replace}"`))
})
return text;
}
71 changes: 71 additions & 0 deletions src/setting.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,16 @@ export interface WikiLinkFormatGroup {
both: string;
}

export interface customReplaceSettingPair {
search: string;
replace: string;
}

export interface customReplaceSetting {
name: string;
data: Array<customReplaceSettingPair>;
}

export interface FormatSettings {
MergeParagraph_Newlines: boolean;
MergeParagraph_Spaces: boolean;
Expand All @@ -36,6 +46,7 @@ export interface FormatSettings {
BulletPoints: string;
WrapperList: Array<WrapperSetting>;
RequestList: Array<APIRequestSetting>;
customReplaceList: Array<customReplaceSetting>;
ToggleSequence: string;
RemoveWikiURL2: boolean;
WikiLinkFormat: WikiLinkFormatGroup;
Expand All @@ -56,6 +67,7 @@ export const DEFAULT_SETTINGS: FormatSettings = {
BulletPoints: "•–§",
WrapperList: [{ name: "underline", prefix: "<u>", suffix: "</u>" }],
RequestList: [],
customReplaceList: [],
ToggleSequence: "titleCase\nlowerCase\nupperCase",
RemoveWikiURL2: false,
WikiLinkFormat: { headingOnly: "{title} (> {heading})", aliasOnly: "{alias} ({title})", both: "{alias} ({title} > {heading})" },
Expand Down Expand Up @@ -392,6 +404,65 @@ export class TextFormatSettingTab extends PluginSettingTab {
});
});

containerEl.createEl("h3", { text: "Custom replacement" });
new Setting(containerEl)
.setName("Add custom replacement")
.setDesc("The plugin will replace the `search` string with the `replace` string in the selection. RegExp is supported.")
.addButton((button: ButtonComponent) => {
button.setTooltip("Add new replacement")
.setButtonText("+")
.setCta().onClick(async () => {
this.plugin.settings.customReplaceList.push({
name: "",
data: [{
search: "",
replace: "",
}]
});
await this.plugin.saveSettings();
this.display();
});
})
this.plugin.settings.customReplaceList.forEach((replaceSetting, index) => {
const s = new Setting(this.containerEl)
.addText((cb) => {
cb.setPlaceholder("Command name")
.setValue(replaceSetting.name)
.onChange(async (newValue) => {
this.plugin.settings.customReplaceList[index].name = newValue;
await this.plugin.saveSettings();
this.plugin.debounceUpdateCommandCustomReplace();
});
})
.addText((cb) => {
cb.setPlaceholder("Search")
.setValue(replaceSetting.data[0].search)
.onChange(async (newValue) => {
this.plugin.settings.customReplaceList[index].data[0].search = newValue;
await this.plugin.saveSettings();
this.plugin.debounceUpdateCommandCustomReplace();
});
})
.addText((cb) => {
cb.setPlaceholder("Replace")
.setValue(replaceSetting.data[0].replace)
.onChange(async (newValue) => {
this.plugin.settings.customReplaceList[index].data[0].replace = newValue;
await this.plugin.saveSettings();
this.plugin.debounceUpdateCommandCustomReplace();
});
})
.addExtraButton((cb) => {
cb.setIcon("cross")
.setTooltip("Delete")
.onClick(async () => {
this.plugin.settings.customReplaceList.splice(index, 1);
await this.plugin.saveSettings();
this.display();
});
});
});


containerEl.createEl("h3", { text: "Zotero pdf note format" });
new Setting(containerEl)
Expand Down

0 comments on commit 70536c9

Please sign in to comment.