sheikh_anton
sheikh_anton

Reputation: 3452

Different command based on if next line is empty

I'm trying to auto-add ; , or whatever is needed in the end of expression by a keystroke, and go to another line.

Basicly it'll be something like inoremap <leader>; <C-o>A;, but i want a little improvement. If next line is empty (or doesn't exist) i want it to do <C-o>A;<cr>, and if it isn't empty just <C-o>A;<Down>. In other words i need an idiomatic way to check if next line exist and if it's empty. Thanks.

Upvotes: 2

Views: 278

Answers (1)

romainl
romainl

Reputation: 196496

Answer to the actual question:

inoremap <expr> <leader>; getline(line(".")+1) =~ "^$" ? "\<C-o>A;\<CR>" : "\<C-o>A;\<Down>"

"Expression" mappings allow you to execute different macros depending on the result of one or more expressions. Here, we check if the line below is empty within a straightforward ternary operator.

Reference:

:help <expr>
:help getline()
:help line()
:help =~

Original answer to the original question:

inoremap <leader>; <C-o>A;^M

^M is a literal <C-m> (synonym of <CR>) that you obtain by pressing <C-v> then <CR>.

Upvotes: 5

Related Questions