Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle semicolon (or other character) at end of line

Tags:

vim

Appending (or removing) a semicolon to the end of the line is a common operation. Yet commands like A; modify the current cursor position, which is not always ideal.

Is there a straightforward way to map a command (e.g. ;;) to toggle whether a semicolon appears at the end of a line?

I'm currently using this command in my vimrc to append:

map ;; A;<Esc>
like image 835
codementum Avatar asked Aug 10 '13 00:08

codementum


2 Answers

Something like this would work

nnoremap ;; :s/\v(.)$/\=submatch(1)==';' ? '' : submatch(1).';'<CR>

This uses a substitute command and checks to see if the last character is a semicolon and if it is it removes it. If it isn't append it to the character that was matched. This uses a \= in the replacement part to execute a vim expression.

If you wan't to match any arbitrary character you could wrap it in a function and pass in the character you wanted to match.

function! ToggleEndChar(charToMatch)
    s/\v(.)$/\=submatch(1)==a:charToMatch ? '' : submatch(1).a:charToMatch
endfunction

and then the mapping would be to toggle the semicolon.

nnoremap ;; :call ToggleEndChar(';')<CR>
like image 70
FDinoff Avatar answered Sep 23 '22 05:09

FDinoff


I don't think I've ever needed to remove a semicolon at the EOL but for adding a semicolon, I have

nnoremap ,; m`A;<Esc>``

Which sets a context mark, appends the semicolon and jumps back.

like image 22
romainl Avatar answered Sep 23 '22 05:09

romainl