【问题标题】:Sublime plugin for executing a command用于执行命令的 Sublime 插件
【发布时间】:2020-07-03 06:57:42
【问题描述】:

我最近一直在写 markdown 文件,并且每天都在使用很棒的 table of content generator (github-markdown-toc) 工具/脚本,但我希望它能够自动重新生成每次我按下 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])

【问题讨论】:

标签: python sublimetext3 sublime-text-plugin


【解决方案1】:

这是您插件的略微修改版本:

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])

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

【讨论】:

  • 感谢您的建议和代码清理(我很感激),但完整路径我仍然一无所获。
  • 您可以使用if not self.view.match_selector(0, 'text.html.markdown'): return 进一步简化检测,以检测文件何时被降价,无论它具有什么扩展名(如果您使用替代语法,您可能需要交换使用的scope不过)。
  • @OdatNurd 这就是我不去检测范围的原因。我想你可能会争辩说 Markdown 文件可以有其他扩展名,但我决定保留 OP 的内容,只是稍微清理一下。
  • 正如对 OP 的评论(上面)中提到的那样,该插件实际上是我的 this StackOverflow answer。在那个答案中,我提供了代码来检查语法,作为最初请求的文件名检查的更简洁的替代方法。
【解决方案2】:

我想通了,因为 gh-md-toc 是一个 bash 脚本,所以我替换了以下行:

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

与:

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

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

【讨论】:

  • 这将是我的下一个建议。很高兴你让它工作!
猜你喜欢
  • 1970-01-01
  • 2013-11-02
  • 2012-11-02
  • 1970-01-01
  • 1970-01-01
  • 2013-09-06
  • 2011-08-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多