开发obsidian插件——删除当前笔记中的图片

本文最后更新于 2024年5月16日。

之前介绍了obsidian插件开发入门
开发obsidian插件入门

以及怎么开发删除所有笔记的外部链接图片
开发obsidian插件——删除所有笔记中的图片
这次改成只删除当前笔记图片的插件。

源码

这次对代码进行修改,只删除当前笔记中的外部链接图片,修改项目中/src/main.ts
的代码,主要增加一个遍历笔记并删除图片链接的函数并调用。
为了避免混淆,这里直接放出修改后的代码:

import {
  App,
  Modal,
  Notice,
  Plugin,
  PluginSettingTab,
  Setting,
} from "obsidian";
interface DeleteImageLinksSettings {
  mySetting: string;
}
const DEFAULT_SETTINGS: DeleteImageLinksSettings = {
  mySetting: "default",
};
export default class DeleteImageLinks extends Plugin {
  settings: DeleteImageLinksSettings;
  async onload() {
    console.log("loading plugin");
    await this.loadSettings();
    this.addRibbonIcon("circle", "delete images", () => {
      // new Notice("This is a notice!");
      this.deleteImageLinks();
    });
    this.addStatusBarItem().setText("Status Bar Text");
    this.addCommand({
      id: "open-sample-modal",
      name: "Open Sample Modal",
      // callback: () => {
      //    console.log('Simple Callback');
      // },
      checkCallback: (checking: boolean) => {
        let leaf = this.app.workspace.activeLeaf;
        if (leaf) {
          if (!checking) {
            new SampleModal(this.app).open();
          }
          return true;
        }
        return false;
      },
    });
    this.addSettingTab(new SampleSettingTab(this.app, this));
    this.registerCodeMirror((cm: CodeMirror.Editor) => {
      console.log("codemirror", cm);
    });
    this.registerDomEvent(document, "click", (evt: MouseEvent) => {
      console.log("click", evt);
    });
    this.registerInterval(
      window.setInterval(() => console.log("setInterval"), 5 * 60 * 1000)
    );
  }
  onunload() {
    console.log("unloading plugin");
  }
  async loadSettings() {
    this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
  }
  async saveSettings() {
    await this.saveData(this.settings);
  }

  async deleteImageLinks() {

      const note = this.app.workspace.getActiveFile();
      const content = this.app.vault.read(note);

      try {
        const resolvedString: string = await content; // 等待 Promise 解析为字符串
        const modifiedString: string = resolvedString.replace(/!\[[^\]]*\]\([^)]*\)/g, ''); // 使用 replace 方法对字符串进行修改
        console.log(modifiedString);
        this.app.vault.modify(note, modifiedString);
      } catch (error) {
        console.error(error);
      }

    // 提示删除成功
    new Notice('All image links have been deleted from your notes.');
  }

}

class SampleModal extends Modal {
  constructor(app: App) {
    super(app);
  }
  onOpen() {
    let { contentEl } = this;
    contentEl.setText("Woah!");
  }
  onClose() {
    let { contentEl } = this;
    contentEl.empty();
  }
}

class SampleSettingTab extends PluginSettingTab {
  plugin: DeleteImageLinks;
  constructor(app: App, plugin: DeleteImageLinks) {
    super(app, plugin);
    this.plugin = plugin;
  }
  display(): void {
    let { containerEl } = this;
    containerEl.empty();
    containerEl.createEl("h2", { text: "Settings for my awesome plugin." });
    new Setting(containerEl)
      .setName("Setting #1")
      .setDesc("It's a secret")
      .addText((text) =>
        text
          .setPlaceholder("Enter your secret")
          .setValue("")
          .onChange(async (value) => {
            console.log("Secret: " + value);
            this.plugin.settings.mySetting = value;
            await this.plugin.saveSettings();
          })
      );
  }
}

打包

运行npm run build打包。

安装插件

打包完成后,把dist文件夹下的文件复制到obsidian插件文件夹即可。
<你的obsidian文件夹></obsidian/plugin>/plugin/<你的插件文件夹>
然后再设置中安装这个插件即可使用。
安装详细教程: obsidian安装插件教程(全面)

获取插件

github

obsidian-delete-image-links

网盘

公众号:weiyounmimi
公众号weiyoun(id:weiyounmimi)后台回复“插件”即可获取。