Typora Plugin 自定义插件开发指南:掌握开放平台的高级用法

【免费下载链接】typora_plugin Typora plugin. feature enhancement tool | Typora 插件,功能增强工具 【免费下载链接】typora_plugin 项目地址: https://gitcode.com/gh_mirrors/ty/typora_plugin

Typora 插件系统为用户提供了强大的自定义插件开发能力,让您能够根据自己的需求扩展 Typora 的功能。无论是简单的文本处理工具,还是复杂的图表生成器,都可以通过自定义插件轻松实现。本文将详细介绍如何利用 Typora 插件的开放平台,创建属于自己的功能增强插件。

为什么需要自定义插件开发?

Typora 作为一款优秀的 Markdown 编辑器,虽然内置了丰富的功能,但每个用户的工作流程和需求都是独特的。自定义插件开发允许您:

  • 个性化工作流程:创建符合自己习惯的快捷键和工具
  • 扩展核心功能:添加 Typora 原生不支持的特性
  • 集成外部工具:将其他服务或工具无缝集成到编辑器中
  • 自动化重复任务:通过脚本减少手动操作时间

Typora 插件系统架构

自定义插件开发基础架构

Typora 的自定义插件系统基于 custom 插件实现,这是一个开放平台,允许用户通过 JavaScript 编写自己的功能模块。核心文件位于 plugin/custom/ 目录:

  • index.js - 自定义插件加载器
  • plugins/ - 用户自定义插件目录
  • README.md - 开发文档

每个自定义插件都是一个继承自 BaseCustomPlugin 的 JavaScript 类,通过声明式配置和代码实现功能。

快速入门:创建你的第一个插件

步骤一:配置插件信息

plugin/global/settings/custom_plugin.user.toml 文件中添加插件配置:

[helloWorld]
name = "你好世界"
enable = true
hide = false
order = 1
hotkey = "ctrl+alt+u"
console_message = "I am in process"
show_message = "this is hello world plugin"

步骤二:编写插件代码

plugin/custom/plugins/ 目录下创建 helloWorld.js 文件:

class helloWorld extends BaseCustomPlugin {
    beforeProcess = async () => {
        // 前置检查,返回 this.utils.stopLoadPluginError 可终止加载
        return
    }

    style = () => "#hello-world { margin: 10px; }"

    html = () => "<div id='hello-world'></div>"

    hint = () => "this is hello world hint"

    hotkey = () => [this.config.hotkey]

    init = () => {
        this.myDiv = document.querySelector("#hello-world")
    }

    process = () => {
        console.log(this.config.console_message)
        console.log("[helloWorldPlugin]: ", this)
    }

    callback = anchorNode => {
        alert(this.config.show_message)
    }
}

module.exports = { plugin: helloWorld }

步骤三:验证插件

重启 Typora 后,您可以在右键菜单中找到 "你好世界" 选项,点击或使用快捷键即可看到效果。

插件命令界面

插件生命周期与核心方法

自定义插件提供了完整的生命周期管理,让您能够在不同阶段执行相应逻辑:

1. beforeProcess()

插件加载前执行,用于检查运行条件,可返回 this.utils.stopLoadPluginError 终止加载。

2. style()

注册 CSS 样式,返回的字符串会自动作为 <style> 标签插入到 DOM 中。

3. html()

注册 DOM 元素,可返回 Element 类型或表示元素的字符串。

4. hint()

定义右键菜单中的提示信息。

5. hotkey()

注册触发插件的快捷键,返回字符串数组。

6. init()

插件初始化,通常在这里获取 DOM 元素、初始化变量。

7. process()

插件主逻辑,在初始化完成后自动运行。

8. callback()

用户点击菜单或使用快捷键时调用的函数。

9. selector()

定义插件可用的光标位置,返回 CSS 选择器。

实战案例:实用的自定义插件示例

案例一:复制标题路径插件

这个插件可以将当前光标所在标题的完整路径复制到剪贴板:

class myFullPathCopy extends BaseCustomPlugin {
    selector = () => '#write > [cid]'
    hint = () => "将当前标题的路径复制到剪切板"
    hotkey = () => [this.config.hotkey]

    callback = anchorNode => {
        const text = this.getFullPath(anchorNode)
        navigator.clipboard.writeText(text)
    }

    getFullPath = (anchorNode) => {
        // 获取标题层级路径的逻辑
        const headers = this.utils.getHeaders(anchorNode)
        const filePath = this.utils.getFilePath() || this.config.untitled_file_name
        return this.utils.Package.Path.join(filePath, ...headers)
    }
}

案例二:思维导图生成器

将文档大纲转换为 Mermaid 格式的思维导图:

class insertMindmap extends BaseCustomPlugin {
    callback = anchorNode => {
        const tree = this.utils.getTocTree()
        const mermaid = this._toGraph(tree)
        this.utils.insertText(null, mermaid)
    }

    _toGraph = tree => {
        // 将大纲树转换为 Mermaid 图格式
        const tokens = this._getTokens(tree, ["graph LR", "\n"])
        return ["```mermaid", "\n ", ...tokens, "```"].join("")
    }
}

思维导图效果

高级功能:插件系统工具类

Typora 插件系统提供了丰富的工具类,位于 plugin/global/core/utils/ 目录:

1. 事件中心 (Event Hub)

const { eventHub } = this.utils
eventHub.addEventListener(eventHub.eventType.fileEdited, this.refreshContent)

2. 样式模板 (Style Templater)

await this.utils.styleTemplater.register(this.fixedName, { 
    rowCount: 3, 
    colCount: 3, 
    this: this 
})

3. 国际化支持 (i18n)

hint = () => this.i18n.t("plugin.hint.message")

4. 文件操作工具

const filePath = this.utils.getFilePath()
const content = await this.utils.readFile(filePath)

插件配置与用户设置

自定义插件支持灵活的配置系统,通过 TOML 文件管理:

配置文件位置

  • plugin/global/settings/custom_plugin.default.toml - 默认配置
  • plugin/global/settings/custom_plugin.user.toml - 用户配置

配置示例

[myPlugin]
name = "我的插件"
enable = true
hide = false
order = 10
hotkey = "ctrl+shift+p"
custom_option = "自定义值"
number_option = 42
array_option = ["item1", "item2"]

插件配置界面

插件开发最佳实践

1. 错误处理

try {
    // 插件逻辑
} catch (error) {
    console.error(`插件 ${this.fixedName} 执行错误:`, error)
    this.utils.notification.error("插件执行失败")
}

2. 性能优化

// 使用防抖处理频繁触发的事件
this.utils.eventHub.addEventListener(
    eventHub.eventType.fileEdited, 
    this.utils.debounce(this.refreshContent, 300)
)

3. 内存管理

afterProcess = () => {
    // 清理资源,防止内存泄漏
    this.eventListeners.forEach(listener => 
        listener.target.removeEventListener(listener.type, listener.handler)
    )
}

4. 用户界面设计

html = () => `
    <div class="plugin-modal">
        <div class="plugin-header">${this.pluginName}</div>
        <div class="plugin-content">
            <!-- 界面内容 -->
        </div>
        <div class="plugin-footer">
            <button class="plugin-btn plugin-btn-primary">确认</button>
            <button class="plugin-btn">取消</button>
        </div>
    </div>
`

调试与测试技巧

1. 控制台调试

process = () => {
    console.log("插件配置:", this.config)
    console.log("工具类:", this.utils)
    console.log("DOM元素:", document.querySelector("#my-plugin"))
}

2. 快捷键测试

确保快捷键配置正确,可通过 Ctrl+Shift+I 打开开发者工具查看控制台输出。

3. 样式调试

使用浏览器开发者工具检查插件注入的样式和元素。

插件调试界面

扩展功能:集成第三方库

自定义插件可以轻松集成第三方 JavaScript 库:

1. 图表库集成

html = () => `
    <div id="chart-container"></div>
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
`

process = () => {
    const chart = echarts.init(document.getElementById('chart-container'))
    chart.setOption({
        title: { text: '示例图表' },
        series: [{ type: 'bar', data: [5, 20, 36, 10, 10, 20] }]
    })
}

2. 绘图工具集成

callback = anchorNode => {
    const drawIOConfig = {
        url: "https://app.diagrams.net/",
        container: this.utils.createModal("drawio-modal"),
        width: "800px",
        height: "600px"
    }
    this.utils.embedDrawIO(drawIOConfig)
}

图表插件效果

社区资源与进阶学习

官方文档

  • 插件开发指南:plugin/custom/README.md
  • 工具类文档:plugin/global/core/utils/
  • 示例插件:plugin/custom/plugins/ 目录下的各种实现

学习资源

  • 查看现有插件源码,学习最佳实践
  • 参考 toc.jsquickButton.js 等复杂插件的实现
  • 阅读 plugin.js 了解插件加载机制

社区支持

  • 在项目 Issues 中提问
  • 查看其他开发者的插件实现
  • 参与插件功能讨论和改进

总结

Typora 的自定义插件开发平台为高级用户提供了无限的可能性。通过掌握插件生命周期、工具类和配置系统,您可以创建出功能强大、用户体验优秀的插件。无论是简单的文本处理工具,还是复杂的图表生成器,都可以通过这个开放平台实现。

记住,好的插件应该:

  1. 功能明确:解决特定问题
  2. 配置灵活:提供合理的默认值,支持自定义
  3. 用户体验友好:清晰的提示和错误处理
  4. 性能优化:避免影响编辑器性能
  5. 易于维护:清晰的代码结构和注释

现在就开始您的 Typora 插件开发之旅吧!从简单的 "Hello World" 开始,逐步构建符合您工作流程的强大工具。

绘图插件效果

【免费下载链接】typora_plugin Typora plugin. feature enhancement tool | Typora 插件,功能增强工具 【免费下载链接】typora_plugin 项目地址: https://gitcode.com/gh_mirrors/ty/typora_plugin

Logo

欢迎加入 MCP 技术社区!与志同道合者携手前行,一同解锁 MCP 技术的无限可能!

更多推荐