Vim Tips Wiki
Advertisement

Autocapitalizing the start of every sentence, a common function in cell phones, is unexpectedly nontrivial. Approaches such as mapping ". a" to ". A" in insert mode, using abbreviate, do not work, produce unexpected delay, or require extra keypresses. The strategy here is to interrupt insert mode on certain key presses, such as ., ?, !, etc and to catch subsequent keypresses with getchar().

The key Vim commands here are:

  • getchar – wait for a single keypress, return the numeric key code
  • startinsert – start insert mode after the interrupt as to not disrupt flow
  • autocmd InsertEnter – trigger capitalization routine when user enters input mode

The basic idea is fairly simple, but some logical manipulations are required to handle the beginnings and the endings of lines because of how exiting from input mode works (cursor sometimes moves back one character). Some further complexity arises from ensuring the input loop isn't triggered multiple times.

Script

The following script can be placed in your vimrc.

 "Inputing '/' cancels capitalizing without delay
function! CapNextKey(prev)
	redraw
	let input = nr2char(getchar())
	let input = (input == '/' ? "\e" : input)
	if input=~'[.?!\r[:blank:]]' "punctuations, return, spaces
		exe 'normal! i' . input . "\<Right>"
		return CapNextKey(input)
	elseif input=="\e"
		return "\<del>"
	elseif a:prev=~'[\r[:blank:]]'
		return toupper(input) . "\<del>"
	else 
		return input . "\<del>"
	endif
endfu
function! InsertEnterCheck()
	let trunc = getline(".")[0:col(".")-2] 
	if col(".")==1
		return CapNextKey("\r")
	elseif trunc=~'[?!.]\s*$\|^\s*$'   "ie, 'text.[t]ext'
		return CapNextKey(trunc[-1:-1])
	else
		return "\<Del>"
	endif
endfu
inoremap <silent> . ._<Left><C-R>=CapNextKey(".")<CR>
inoremap <silent> ? ?_<Left><C-R>=CapNextKey("?")<CR>
inoremap <silent> ! !_<Left><C-R>=CapNextKey("!")<CR>
inoremap <silent> <CR> <CR>_<Left><C-R>=CapNextKey("\r")<CR>
nnoremap <silent> o o_<Left><C-R>=CapNextKey("\r")<CR>
nnoremap <silent> O O_<Left><C-R>=CapNextKey("\r")<CR>
nnoremap <silent> a a_<Left><C-R>=InsertEnterCheck()<CR>
nnoremap <silent> A A_<Left><C-R>=InsertEnterCheck()<CR>
nnoremap <silent> i i_<Left><C-R>=InsertEnterCheck()<CR>
nnoremap <silent> I I_<Left><C-R>=InsertEnterCheck()<CR> 

Comments

Amazing. I have not read the code, but I guess it would always be active? Wouldn't you want a way to turn it on/off? JohnBeckett 01:00, March 4, 2012 (UTC)

Yeah, you're right, it's always active, and a future version should probably include an easy way to unmap and remove the autocommands, although that might increase the complexity even more. I use my vim on my cell phone a lot, and I'm not really sure how common that is and how useful people may find this, but it might be interesting to some as a way to use getchar() to create a "new mode" or a more interactive vim. -- q335r49

Advertisement