Monday 22 July 2019

Automatically capitalize the first letter of sentence in Vim


When writing in MS Word, or in Open Office, the first letter of each sentence is capitalized automatically by the editor, without needing to press the Shift key. This makes typing much easier.


Is there a script, mode or something that will cause Vim to likewise capitalize the first letter of all sentences automatically, as you type?



Answer



This can be done with :help :map-expr mappings for all lowercase characters that check for a preceding end of a sentence. If there's a sentence-ending character before the cursor, it returns the uppercase character, else the typed lowercase character.


You can force a lowercase character after a sentence-ending character by pressing Shift while typing the character. I.e., in effect case is "toggled" for the first letter.


I use a loop to build the individual mappings:


for char in split('abcdefghijklmnopqrstuvwxyz', '\zs')
exe printf("inoremap %s search('[.!?]\\_s\\+\\%%#', 'bcnw') ? '%s' : '%s'", char, toupper(char), char)
endfor

for char in split('ABCDEFGHIJKLMNOPQRSTUVWXYZ', '\zs')
exe printf("inoremap %s search('[.!?]\\_s\\+\\%%#', 'bcnW') ? '%s' : '%s'", char, tolower(char), char)
endfor

No comments:

Post a Comment

How can I VLOOKUP in multiple Excel documents?

I am trying to VLOOKUP reference data with around 400 seperate Excel files. Is it possible to do this in a quick way rather than doing it m...