Automatically capitalize the first letter of sentence in Vim

Solution 1:

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 <expr> %s search('[.!?]\\_s\\+\\%%#', 'bcnw') ? '%s' : '%s'", char, toupper(char), char)
endfor

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