0

Suppose I have some Python code with a “block comment” (i.e. multiple consecutive comment lines) in the middle of a paragraph:

a = function1()
# Remember: if you pass an even number to function2, your
# computer will explode.
b = function2(7)

If the cursor is on one of these comment lines and I want to use the gq command (for example) on just the comment, but not the surrounding lines, I first need to enter linewise visual mode and select the appropriate lines. This can take several keystrokes if the comment is long and the cursor starts out in the middle of it. It would be easier if there were a text object corresponding to the comment. (If the entire paragraph were a comment, I could just type gqap, for example.)

How can I define a new text object corresponding to the current block comment? I’m defining a block comment as “the longest sequence of consecutive lines that match the regular expression ^\s*#”.

0

I installed the vim-textobj-user and vim-textobj-comment plugins, which provide just the text object I was looking for. If the cursor is on the second or third line in the code sample in the question, I can type gqac to format both lines of the comment without touching either of the surrounding lines of code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.