用于执行命令的 Sublime 插件

Sublime plugin for executing a command

我最近一直在写 markdown 文件,并且一直在使用很棒的 table 的内容生成器 (github-markdown-toc) tool/script每天,但我希望每次按下 Ctrl+s 时自动重新生成它,就在我的 sublime3 中保存 md 文件之前环境。

到目前为止我所做的是从 shell 手动生成它,使用:

gh-md-toc --insert my_file.md

于是我写了一个简单的插件,但是不知为何看不到我想要的结果。 我看到了我的印刷品,但未生成目录。 有人有什么建议吗?怎么了?

import sublime, sublime_plugin
import subprocess

class AutoRunTOCOnSave(sublime_plugin.EventListener):
    """ A class to listen for events triggered by ST. """

    def on_post_save_async(self, view):
        """
        This is called after a view has been saved. It runs in a separate thread
        and does not block the application.
        """

        file_path = view.file_name()

        if not file_path:
            return
        NOT_FOUND = -1
        pos_dot = file_path.rfind(".")
        if pos_dot == NOT_FOUND:
            return
        file_extension = file_path[pos_dot:]
        if file_extension.lower() == ".md": #
            print("Markdown TOC was invoked: handling with *.md file")
            subprocess.Popen(["gh-md-toc", "--insert ",  file_path])

这是你的插件的一个稍微修改的版本:

import sublime
import sublime_plugin

import subprocess


class AutoRunTOCOnSaveListener(sublime_plugin.EventListener):
    """ A class to listen for events triggered by ST. """

    def on_post_save_async(self, view):
        """
        This is called after a view has been saved. It runs in a separate thread
        and does not block the application.
        """

        file_path = view.file_name()
        if not file_path:
            return
        
        if file_path.split(".")[-1].lower() == "md":
            print("Markdown TOC was invoked: handling with *.md file")
            subprocess.Popen(["/full/path/to/gh-md-toc", "--insert ",  file_path])

我更改了一些内容,以及 class 的名称。首先,我简化了用于确定当前文件是否为 Markdown 文档的测试(更少的操作意味着更少的错误空间)。其次,您应该包含 gh-md-toc 命令的完整路径,因为 subprocess.Popen 可能无法在默认路径中找到它。

我发现,由于 gh-md-toc 是一个 bash 脚本,我替换了以下行:

subprocess.Popen(["gh-md-toc", "--insert ",  file_path])

与:

subprocess.check_call("gh-md-toc --insert %s" % file_path, shell=True)

所以现在它在每次保存时都运行良好。