preservim / vim-textobj-quote

Use ‘curly’ quote characters in Vim
Other
123 stars 6 forks source link

Smart quotes in code comments #8

Open zeorin opened 8 years ago

zeorin commented 8 years ago

I know this plugin is designed primarily for prose, but I wanted smart quotes in comments in my code.

I've managed to do this. Currently it looks like this in my .vimrc:

" Smart quotes toggle {{{4
function! s:ToggleEducate()
    if g:textobj#quote#educate
        silent NoEducate
        silent let g:textobj#quote#educate = 0 " For smart quotes in comments
        echom "Smart quotes off"
    else
        silent Educate
        silent let g:textobj#quote#educate = 1 " For smart quotes in comments
        echom "Smart quotes on"
    endif
endfunction
nnoremap <Leader>' :call <SID>ToggleEducate()<Cr>

" Smart quotes in comments {{{4
function! s:SmartQuotesInComments()
    " Respect the setting above, only do smart quotes in comments
    " If the educate variable is truthy
    if g:textobj#quote#educate
        if synIDattr(synID(line('.'),col('.')-1,1),'name') =~? 'comment'
            exec 'silent Educate'
        else
            exec 'silent NoEducate'
        endif
    endif
endfunction
augroup smartquotes
    autocmd!
    autocmd InsertCharPre * if index(textlikeft, &filetype) < 0 |
        \   call <SID>SmartQuotesInComments()
    \ | endif
    autocmd InsertLeave * if index(textlikeft, &filetype) < 0 |
        \   exec 'silent NoEducate'
    \ | endif
augroup END

I've achieved this by loading the plugin for both text-like and non-text-like file types. For text-like file types, Educate is enabled when loading the plugin.

For non-text-like file types (basically, for source code), the plugin is loaded, but Educate is not enabled. However, the configuration variable is still set to 1 (after plugin init). I figured that the plugin only read it on initialization anyway (i.e. changing it after init doesn't change the plugin's behaviour), so I've reused it for the following purpose:

In non-text-like file types:

The result is that I have smart quotes in my code's comments automatically. I am also able to toggle that off in case I need ASCII quotes in my comments (e.g. when typing a string in VimL, before the closing double quote is entered, Vim thinks we're in a comment—if I couldn't toggle Educate for comments I'd go mad).

I developed and tested this on an Asus Transformer Book (T100TA), which has a wimpy little Atom processor. I didn't notice any performance impact.

I thought this might be of interest to others. Perhaps you'd like to add this functionality to your plugin, or mention this in the docs. ☺

reedes commented 8 years ago

Interesting new feature, thanks.

The blacklisting feature in my pencil plugin uses a similar technique of examining the highlight group to determine if Vim's autoformat should be disabled.

I'll mark this as an enhancement for now as I don't have time to look into it deeper.