简体   繁体   中英

Vim: Function to make <CR> exit insert mode unless at end of line

How do make <CR> exit insert mode when the cursor (*) is inside a line? Like:

" pressing <CR> should exit insert mode (in either case)
Lorem *ipsum dolor
Lorem ipsum dol*or

But also make <CR> insert a newline when cursor is at EOL?

" pressing <CR> when cursor @ EOL
Lorem ipsum dolor*
Fusce leo quam

" results in
Lorem ipsum dolor
*
Fusce leo quam

What does the function look like to make both of these simultaneously possible?

Rationale: When maintaining a document I find I do small strokes (ie goto word, change it, exit). To me, these strokes are actions I want to 'enter' (like sending a message in a chat window). So having <CR> exit insert allows me to keep this mental model when maintaining. On the other hand, <CR> is clearly useful when composing. Fortunately, there's enough context to make both simultaneously possible - I just don't have the vimscript skills yet. This will teach me some :)

You can achieve mappings that depend on some condition with an expression mapping; see :help :map-expression . We can check for the cursor at the end of the line via the col() function, like this:

:inoremap <expr> <CR> col('.') == col('$') ? '<CR>' : '<Esc>'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM