4

I'd like to define a vim command with the following functionality.

60<F7>= insert = at the end of the line until the line become 60 characters long.

<F7>* insert * until the line becomes as long as the value of colorcolumn.

The preexisting text on the line should be separated from the inserted characters by a space.

1 Answer 1

4

Well, doing this in vimscript is not that hard. For example, the following command will do what you describe to the line your cursor is on:

:exec 'norm '.(&cc - strlen(getline('.'))).'A='

The way this works is it determines the length of the current line and subtracts that from the current value of 'colorcolumn'. This evaluates to a string, and is executed as if you had typed it. For example, on a line with 10 characters, and with 'colorcolumn' set to 80 this is equivalent to typing:

70A=

You can also be more specific about which line to do this to. For example, to do this to line 3:

:exec 'norm '.(&cc - strlen(getline(3))).'A='

Or the line that mark a is on:

:exec 'norm '.(&cc - strlen(getline("'a"))).'A='

To wrap this up in a convenient mapping, I would recommend this:

function! Append(c)
  exec 'norm '.(&cc - strlen(getline('.'))).'A'.nr2char(a:c)
endfunction

nnoremap <expr> m ':call Append('.getchar().")\<CR>"
4
  • By automatically I simply meant that I was looking for a command that can be mapped, so your answer is perfect. One question though. How could I map this to something that can be prepended with a length and appended with a character I want? So, for example, I'd like to type 60<F7>* for the current line to extend to column 60 by appending a bunch of *s?
    – SU3
    Dec 5, 2016 at 1:00
  • @SU3 I know how to do that! I'll edit my answer some more, but you should put those details into your main post. That would have been useful to know at first
    – DJMcMayhem
    Dec 5, 2016 at 1:02
  • Sure. I just couldn't formulate it properly at first.
    – SU3
    Dec 5, 2016 at 1:04
  • Might be worth mentioning that this works on visual ranges too. Nov 9, 2021 at 2:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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