Sublime Forum

How to start a comment at the end of line

#1

Hi ,
Sometimes, I might want to add a comment at the end of an existing code line . For example in the following screenshot I want to add a comment where the cursor is . Is there a shortcut that I can employ to achieve my intended desire ?

CloudApp

1 Like

#2

Sublime Text provides 2 key bindings for comments

ctrl+/ line comments
ctrl+shift+/ block comments

The latter one might be your choice.

0 Likes

#3

ctrl+L comments the entire line, not starts a comment at the end of the line , same is the case with the other one.

0 Likes

#4

I suppose it goes without saying that in your example above the keyboard shortcut for adding a comment at the cursor position is just to press #. :wink:

I’m not aware of a built in command for doing this, but you could create a macro and bind it to a key to do something like this. For example:

[
    {
        "command": "move_to",
        "args": {
            "to": "hardeol",
            "extend": false
        }
    },
    {
        "command": "insert",
        "args": {
            "characters": "#"
        }
    }
]

If you want this to work for more than one sort of file then you’d likely need a plugin to do this more efficiently, since the characters for commenting differ based on file type.

1 Like

#5

That is true , but suppose I am the beginning of the line (or in the middle of the line) pressing # comments the line from then onwards, not what I am intending to do.[quote=“OdatNurd, post:4, topic:38456”]
If you want this to work for more than one sort of file then you’d likely need a plugin to do this more efficiently, since the characters for commenting differ based on file type.
[/quote]

This gives me an idea, though I will need some help please - I can use the chain of command plugin to achieve this , can’t I ? I believe the first command remains the same, but I am not sure about the second one.

Thanks

0 Likes

#6

This may depend on the syntax. I tried with C, which worked, but you are right. It adds the /**/ at the eol, but not an // which would make more sense.

0 Likes

#7

Yeah, I was trying this with

  1. Javascript
  2. Python
  3. LUA

and it does not work appropriately with them.

0 Likes

#8

Indeed you could use Chain of Command in place of a macro. If you want this for multiple languages you would need multiple key bindings, one for each language. You’d use the same key for each binding but use a context that makes it available only in the appropriate file type.

To be more streamlined a fairly simple plugin can get access to the same metadata that the built in commands use to know how to comment a file, so that only a single key binding on a single command would be needed.

0 Likes

#9

I am wondering if there is a plugin that already does that? I havent done any Sublime Plugin development.

0 Likes

#10

I’m not sure personally; possibly there is a package that does something like that.

An example of a plugin that does this is the following. It implements a command named comment_at_end that jumps to the end of the line and then inserts either a line comment or a block comment, depending on the syntax (some things, such as XML and CSS, don’t define line comments by default.

import sublime
import sublime_plugin

from Default.comment import build_comment_data


class CommentAtEndCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        # Jump to the end of the line
        self.view.run_command("move_to", {"extend": False, "to": "hardeol"})

        # Get comment data; the returned tuple contains two elements: a list of
        # line comment strings and a list of block comment strings.
        data = build_comment_data(self.view, self.view.sel()[0].begin())
        print(data)

        # Prefer line comments to block comments where possible.
        if data[0]:
            snip = " {0}$0".format(data[0][0][0])
        elif data[1]:
            snip = " {0} $0 {1}".format(data[1][0][0], data[1][0][1])
        else:
            sublime.status_message("No comment type defined for this syntax")
            return

        self.view.run_command("insert_snippet", {"contents": snip})
1 Like

#11

Thanks @OdatNurd, Much appreciated .
I have copied over the code and saved it under - packages\user folder. How can I now run it ?

sorry for being so dumb …

Thanks

0 Likes

#12

Create a key binding to the comment_at_end command, for example:

    { "keys": ["ctrl+alt+/"], "command": "comment_at_end"},
1 Like

#13

@OdatNurd - Thank you Sir. It worked like a charm.

With Regards
Gagan

0 Likes

#14

it may be cleaner to just do a

view.run_command('insert_snippet', { 'contents': '$TM_COMMENT_START$1${TM_COMMENT_END:}' })

rather than get the comment data manually etc.

1 Like

#15

Well, that’s embarrassing… :blush: This might be a good public service notice on why you shouldn’t do Sublime stuff while also playing with Lego, it’s very distracting.

Indeed a shorter version might be something like the following, which could also be a macro.

class CommentAtEndCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        self.view.run_command("move_to", {"extend": False, "to": "hardeol"})
        self.view.run_command('insert_snippet', { 'contents': ' $TM_COMMENT_START$0$TM_COMMENT_END' })

That said, I think the reason I originally thought of extracting the comment strings from the meta info is because the comment characters defined in the metadata don’t necessarily have consistent spacing in them, which may or may not be undesirable.

For example, the comment strings for multi line comments in XML contain white space, but the ones for C don’t, so your comment gets all bunched up and requires some manual tweaking in some cases. The output of the function from Default gives you trimmed and untrimmed versions to make that easier (although I forgot to actually do that above).

Along similar lines, it might be handy as a plugin to trim the trailing white space on the line in question before moving to the end to ensure that the comment ends up where you expected.

1 Like

#16

one could also use the snippet regex substitution feature to ensure one ends up with the desired whitespace :wink:

0 Likes

#17

OdatNurd’s version would then easy be implemented via Chain of Commands, too.

	// Insert comment at the end of the line
	{
		"keys": ["ctrl+alt+/"],
		"command": "chain",
		"args": {
			"commands": [
				[ "move_to", {"extend": false, "to": "hardeol"}],
				[ "insert_snippet", {"contents": " $TM_COMMENT_START$0$TM_COMMENT_END"}],
			]
		}
	},
1 Like

#18

Where is the difference? :smile:

1 Like