0

I been writing markdown files lately, and have been using the awesome table of content generator (github-markdown-toc) tool/script on a daily basis, but I'd like it to be regenerated automatically each time I press Ctrl+s, right before saving the md file in my sublime3 environment.

What I have done till now was to generate it from the shell manually, using:

gh-md-toc --insert my_file.md

So I wrote a simple plugin, but for some reason I can't see the result I wanted. I see my print but the toc is not generated. Does anybody has any suggestions? what's wrong?

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])
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
JammingThebBits
  • 732
  • 11
  • 31
  • The plugin you wrote?! That's the plugin I wrote and posted in response to the StackOverflow [Auto-run a command on saving in Sublime Text](https://stackoverflow.com/a/60249097/2102457) question. At best that's very bad netiquette JammingThebBits. – mattst Jul 28 '20 at 11:35

2 Answers2

0

Here's a slightly modified version of your plugin:

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

I changed a couple things, along with the name of the class. First, I simplified your test for determining if the current file is a Markdown document (fewer operations means less room for error). Second, you should include the full path to the gh-md-toc command, as it's possible subprocess.Popen can't find it on the default path.

MattDMo
  • 100,794
  • 21
  • 241
  • 231
  • Thank you for the suggestion and the code cleanup (I appreciate it), but with the full path I still got nothing. – JammingThebBits Jul 03 '20 at 21:20
  • 1
    You can simplify the detect even further with `if not self.view.match_selector(0, 'text.html.markdown'): return` to detect when the file is markdown, regardless of the extension it has (if you use an alternate syntax you may need to swap the `scope` used though). – OdatNurd Jul 03 '20 at 23:31
  • @OdatNurd that's why I didn't go for detecting scope. I suppose you could argue that Markdown files can have other extensions, but I decided to stay with what the OP had, just clean it up a bit. – MattDMo Jul 05 '20 at 21:12
  • As mentioned in a comment (above) in response to the OP, the plugin was actually mine from [this StackOverflow answer](https://stackoverflow.com/a/60249097/2102457). In that answer I offered code to check the syntax as a more concise alternative to the filename check originally requested. – mattst Jul 28 '20 at 11:43
0

I figured out, since gh-md-toc is a bash script, I replaced the following line:

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

with:

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

So now it works well, on each save.

JammingThebBits
  • 732
  • 11
  • 31