Search code examples
commentssublimetext2sublimetext3sublime-text-plugin

Sublime Text Plugin - How can I get the comment block type of the current syntax


I'm writing a plugin for Sublime Text and I would like to get the characters to use to add a comment with the current syntax of the document.

e.g.

  • Python -> #
  • PHP -> //
  • C -> //
  • C++ -> //
  • .ini -> ;
  • ...

Of course, I could use

view.run_command('toggle_comment', {'block': True})

But I DON'T want to just add a comment, I want to know the characters that I should use...

Any ideas?

I had a look in this documentation, but I didn't find anything


Solution

  • You can use view.meta_info('shellVariables', 0) to get an array of the shellVariables that are defined for the current document's syntax.

    (The second argument, where I specified 0, represents the position (a.k.a point in official terminology) in the view to interrogate, which can be useful for views containing embedded syntaxes i.e. PHP/HTML/JS)


    Examples:

    On a Python file it returns:

    [{'name': 'TM_COMMENT_START', 'value': '# '}, {'name': 'TM_LINE_TERMINATOR', 'value': ':'}]
    

    On an XML file it returns:

    [{'name': 'TM_COMMENT_END', 'value': ' -->'}, {'name': 'TM_COMMENT_START', 'value': '<!-- '}]
    

    On a JavaScript file:

    [{'name': 'TM_COMMENT_END_2', 'value': '*/'}, {'name': 'TM_COMMENT_START', 'value': '// '}, {'name': 'TM_COMMENT_START_2', 'value': '/*'}]
    

    As you can see, the relevant dictionary item in the array has a name of TM_COMMENT_START, and for block comments, there will also be a TM_COMMENT_END. Syntaxes like JavaScript that support single line comments and block comments can also have the same names with an _2 suffix.


    Therefore, your code to get the characters to begin a comment could look like:

    comment_characters = [var['value'] for var in view.meta_info('shellVariables', 0) if var['name'] == 'TM_COMMENT_START'][0]