How can I toggle XML line comment in Sublime Text 3

十年热恋 提交于 2019-12-04 19:46:46

In general, Sublime can be configured to know the difference between a line and block comment and act accordingly. However as far as I can tell, this can't be done for XML because it needs to wrap the content with comment characters.

More specifically, the configuration options for comments specify either a TM_COMMENT_START for a pure line comment or TM_COMMENT_START and TM_COMMENT_END for a block comment. If both are present, the toggle command selects the correct one based on content and context.

For XML, it uses a pair due to how comments in XML works, which means that only block comments are possible. However, when you invoke the command with no selection, it assumes that the selection wraps the entire line. If you have a selection, that's what gets wrapped.

One way around this problem is to split your selection into lines before you toggle the comment. You can do that via Selection > Split into Lines from the menu (this will also show you what your key binding is for this command).

It is possible to group these commands into a macro so that you don't have to take multiple steps on your own.

Such a macro could look like the following (saved in your User package as XML_Line_Comment.sublime-macro):

[
    {
        "command": "split_selection_into_lines"
    },
    {
        "command": "toggle_comment",
        "args": {"block": false}
    },
    {
        "command": "single_selection"
    },
    {
        "command": "move_to",
        "args": {"extend": false, "to": "bol" }
    }
]

This would split the selection, toggle the comment, and then return to a single selection (and jump to the start of the line). You can modify this as appropriate (e.g. if you don't want to revert to single selection afterwards).

You can run this macro from the menu bar (Tools > Macros > User > XML_Line_Comment), but a better way might be to set up a key binding. An example of that would be:

{
    "keys": ["ctrl+/"],
    "command": "run_macro_file",
    "args": { "file": "res://Packages/User/XML_Line_Comment.sublime-macro" },
    "context": [
        { "key": "selection_empty", "operator": "equal", "operand": false},
        { "key": "selector", "operator": "equal", "operand": "text.xml"},
    ]
},

This will cause the key that normally toggles comments to run your macro for the specific case of there being a selection while you're in an XML file.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!