2026/06/05

Vim / 커서 위치 단어를 설정한 단어로 상호 전환



대소문자 전환키 "~"처럼 커서가 위치한 단어를 리스트에서 설정한 단어로 상호 전환하는 vimscript 함수.
t키로 리더 맵핑한 후 HA자동화 편집등에 가끔 사용중.

function! ToggleWord()
    let word = expand('<cword>')
    let lower = tolower(word)
    let groups = [
    \ ['true', 'false'],
    \ ['yes', 'no'],
    \ ['on', 'off'],
    \ ['1', '0'],
    \ ['enable', 'disable'],
    \ ['enabled', 'disabled'],
    \ ['above', 'below'],
    \ ['from', 'to'],
    \ ['left', 'right'],
    \ ['and', 'or'],
    \ ['min', 'max'],
    \]
    for group in groups
        let idx = index(group, lower)
        if idx >= 0
            let next = group[(idx + 1) % len(group)]
            if word ==# toupper(word)
                let next = toupper(next)
            elseif word[0] ==# toupper(word[0])
                let next = toupper(next[0]) . next[1:]
            endif
            execute "normal! ciw" . next
            normal! `[
            return
        endif
    endfor
endfunction

nnoremap <leader>t :call ToggleWord()<CR>