Toggle semicolon (or other character) at the end of a line

Adding (or removing) a semicolon to the end of a line is a common operation. However, type A; commands A; change the current cursor position, which is not always ideal.

Is there an easy way to match a command (e.g. ;; ) to switch if a semicolon appears at the end of a line?

I am currently using this command in my vimrc to add:

 map ;; A;<Esc> 
+4
source share
2 answers

Something like this will work

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

In this case, the substitute command is used and it is checked whether the last character is a semicolon, and if it deletes it. If he does not attach it to the character that was matched. This uses \= in the replacement part to execute the vim expression.

If you don't match an arbitrary character, you can wrap it in a function and pass in the character you want to match.

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

and then the display would have to switch the semicolon.

 nnoremap ;; :call ToggleEndChar(';')<CR> 
+3
source

I don't think I have ever had to delete a semicolon in EOL, but to add a semicolon I had

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

Defines a context label, adds a semicolon, and returns back.

+3
source

Source: https://habr.com/ru/post/1496265/


All Articles