This is a follow up question to Cycle through a list of letters in multiple groups where I asked how to cycle a group of letters. I got a bunch of great tips and this is my follow up question.
This is simply asking for a code review of my attempt at solving this problem
Explanation
My code simply allows the user to hit some key combination (temporarily set to <localleader>ln
and <localleader>lp
) to replace the letter under the cursor with the next letter in the cycle.
Here are some of my thoughts on the current state of my code.
My script flashes the contents of the tr
command upon execution to the statusline. I tried to avoid this by using !
(silent) without much success.
I tried to make sure I do not mess with the user's registers, however, this solution seems unnecessarily verbose. Any suggestions for improvements here are more than welcome.
s\<c-r>=tr(@\",'" . a:letters . "','" . a:replacements . "')\<cr>\<esc>
" executes a command in normal mode, then immediately go to insert mode using s
. Then it switches to invoking an (Ex?) command using <C-r>=
. Is this really the best way to replace the letter under my cursor by invoking tr
over it? It feels as my code jumps between two many modes.
Initially I had some issues with my code, I tried tr(@\"," . a:letters . "," . a:replacements . ")
without much success. I had to add '
around the variables to make it work, why? I thought they already were stored as strings?
Can this code be written cleaner/better? This is the first time I've ever written a function in vimscript. I do not know about any style guides, nor how to lint my code. I choose to do this with vimscript, and I'm not really sure why I did that over lua. Alternative approaches are welcome.
Code
function! TryReplaceLetters(letters, replacements)
let save_cb = &cb
let regText = getreg('"', 1, 1)
try
execute "normal! s\<c-r>=tr(@\",'" . a:letters . "','" . a:replacements . "')\<cr>\<esc>"
finally
let &cb = save_cb
call setreg('"', regText)
endtry
endfunction
let s:lookalikes = "1¹2²3³4⁴5⁵6⁶7⁶8⁸9⁹AẠȦÄÆBḄḂƁßCÇĊƇ©DÐḌḊƊEẸĖ£ÆŒFḞƑGĠƓHḤḢIỊİJȷKḲLḶĿMṂṀⱮNṆṄÑƝOȮØŒPṖƤQỌRṚṘ®SṢṠTṬṪƬUỤƲVṾWẈẆXẊYỴẎ¥ZẒŻaạȧæbḅḃþcċç¢dḍḋɗeẹæœfḟƒgḥḣiị¡jkƙlḷŀmṃṁnñoọȯøœpṗÞrṛṙɼsṣṡ$tṭṫƭvʋwẇxẋyżz"
let s:lookcycles = "¹1²2³3⁴4⁵5⁶6⁶7⁸8⁹9ÆAẠȦÄßBḄḂƁ©CÇĊƇƊDÐḌḊŒEẸĖ£ÆƑFḞƓGĠḢHḤİIỊȷJḲKĿLḶⱮMṂṀƝNṆṄÑŒOȮØƤPṖỌQ®RṚṘṠSṢƬTṬṪƲUỤṾVẆWẈẊX¥YỴẎŻZẒæaạȧþbḅḃ¢cċçɗdḍḋœeẹæƒfḟgḣḥ¡iịjƙkŀlḷṁmṃñnœoọȯøÞpṗɼrṛṙ$sṣṡƭtṭṫʋvẇwẋxżyz"
function! JellyLookaLikes()
" Cycles through similar looking symbols, clockwise
return TryReplaceLetters(s:lookalikes, s:lookcycles)
endfunction
function! JellyLookaLikesPrev()
" Cycles through similar looking symbols, counter-clockwise
return TryReplaceLetters(s:lookcycles, s:lookalikes)
endfunction
nnoremap <silent> <localleader>ln :call JellyLookaLikes()<cr><esc>
nnoremap <silent> <localleader>lp :call JellyLookaLikesPrev()<cr><esc>