Can we make use of syntax highlighting feature to

2019-04-13 09:07发布

问题:

I have a bunch of source files written in different languages, and I would like to strip all comments from the source files.

While writing regex is certainly an option, depending on the input files, I may have to handle cases where the character to denote comment appears inside string literals. There is also the need to maintain a list of regex for different languages.

The syntax highlighting seems to do quite a good job at highlighting the comments, but there doesn't seem to be any command to remove all comments in the Command Palette.

Is there any way to leverage the syntax highlighting feature in SublimeText to remove all comments from source files in different languages?

回答1:

Based on nhahtdh's answer, the following plugin should work for both Sublime Text 2 and 3

import sublime_plugin


class RemoveCommentsCommand(sublime_plugin.TextCommand):

    def run(self, edit):
        comments = self.view.find_by_selector('comment')
        for region in reversed(comments):
            self.view.erase(edit, region)

Create a new file with Python syntax, and paste the code above into it. Save the file in your Packages/User directory (accessible via Preferences -> Browse Packages...) as remove_comments.py. You can now either run the plugin via the console, or bind a key combination to it. To run via the console, just type

view.run_command('remove_comments')

in the console, and all the comments in the current view will be deleted.

To bind a key combination, open Preferences -> Key Bindings-User and add the following (surround it with square brackets [] if the file is empty):

{ "keys": ["ctrl+alt+shift+r"], "command": "remove_comments" }

Save the file, and you can now hit CtrlAltShiftR (or whatever key combination you choose) and all comments in the current file will be deleted.



回答2:

Assumption

  1. We will make use of the syntax highlighting rules in Sublime Text to remove all comments, so the method below works only if the syntax highlighting works correctly for the language of your source file.

    For most languages, the syntax highlighting rules do quite a good job at recognizing the comments. However, it would be best if you take another look at your files to see if there is any anomaly in syntax highlighting.

  2. The current method only works for Sublime Text 2.

Solution

  1. Open the Console via View > Show Console or the key combination Ctrl+`
  2. Copy and paste the following commands line by line:

    e = view.begin_edit()
    len([view.erase(e, r) for r in reversed(view.find_by_selector('comment'))])
    view.end_edit(e)
    

After the last command, the edit will be applied and all comments will be removed.