Achievement Unlocked: Wrote my first SublimeText2 plugin.

Specifically this one converts the currently selected text from Asciidoc syntax to DocBook.

It actually uses the Ruby port of Asciidoc, Asciidoctor, instead of the “offical” Python tool. It probably would have made sense to use the Python tool (and it’s library) given that the SublimeText plugin system is Python-based. But I’m a Ruby guy and I didn’t want to get into details of Python packages or anything when I already had Asciidoctor installed and had successfully used it previously.

  1. Install Asciidoctor

    Installing Asciidoctor is pretty easy, assuming that you already have Ruby and RubyGems installed.

    [localhost]$ sudo gem install asciidoctor
    
  2. Create plugin .py file

    On the SublimeText2 menu go to Tools and select New Plugin. Delete all the template code and paste in the code below.

    import sublime, sublime_plugin
    import subprocess
    
    class AsciidoctoringCommand(sublime_plugin.TextCommand):
       def run(self, edit):
          for region in self.view.sel():
             if not region.empty():
                # Get the selected text
                s = self.view.substr(region)
    
                p1 = subprocess.Popen(["echo", s], stdout=subprocess.PIPE)
                p2 = subprocess.Popen(["asciidoctor -s -b docbook45 -"], shell=True, stdin=p1.stdout, stdout=subprocess.PIPE)
    
                p1.stdout.close()  # Allow p1 to receive a SIGPIPE if p2 exits.
                output = p2.communicate()[0]
    
                self.view.replace(edit, region, output)
    

    The save it. It should default to the correct directory, Sublime Text 2/Packages/User. The filename doesn’t matter but it does need to have the .py extension.

    Once the file is saved you can run it immediately by opening the console ( ctrl- ` ) and running the following command:

    view.run_command("asciidoctoring")
    

    And of course it only does anything if you have text selected in your editor view.

  3. Add right-click menu item

    The final touch is to put an entry on the right-click menu so you can quickly access it. To do this, add the following line to the Sublime Text 2/Packages/Default/Context.sublime-menu file.

    { "command": "asciidoctoring", "caption":"Convert ASCIIDOC > Docbook45" }
    

Now you can select a block of text, right-click and select Convert ASCIIDOC > Docbook45 and the text will be replaced with the Docbook version of it.

I like it. It saves me a lot of time.