2

I am trying to make a little function that aims to extract a method from a piece of php code. The function works fine. Is not optipized but "done is better than perfect" and the purpose here is not perfectio but just, ... keep expandtab settings right.

enter image description here

And here the incriminated code.

fun! ExtractMethod() range
    let g:selection = s:get_visual_selection()
    exec ":set paste"
    exec ":normal! Gko\<esc>o\<esc>Spublic function xxxxxxx()\<esc>=="
    exec ":normal! o\t{\<esc>"
    exec ":normal! o" . g:selection . "\<esc>"
    exec ":normal! o\t}\<esc>%k2w"
endfun
function! s:get_visual_selection()
    let [lnum1, col1] = getpos("'<")[1:2]
    let [lnum2, col2] = getpos("'>")[1:2]
    let lines = getline(lnum1, lnum2)
    let lines[-1] = lines[-1][: col2 - 2]
    let lines[0] = lines[0][col1 - 1:]
    return join(lines, "\n")
endfunction
vnoremap <Leader>r :call ExtractMethod()<cr>
5

From :h paste:

When the 'paste' option is switched on (also when it was already on):
        - mapping in Insert mode and Command-line mode is disabled
        - abbreviations are disabled
        - 'autoindent' is reset
        - 'expandtab' is reset
        - 'formatoptions' is used like it is empty
        - 'revins' is reset
        - 'ruler' is reset
        - 'showmatch' is reset
        - 'smartindent' is reset
        - 'smarttab' is reset
        - 'softtabstop' is set to 0
        - 'textwidth' is set to 0
        - 'wrapmargin' is set to 0
These options keep their value, but their effect is disabled:
        - 'cindent'
        - 'indentexpr'
        - 'lisp'
...
When the 'paste' option is reset the mentioned options are restored to
the value before the moment 'paste' was switched from off to on.

So, reset paste at the end of your function:

fun! ExtractMethod() range
    let g:selection = s:get_visual_selection()
    set paste
    exec ":normal! Gko\<esc>o\<esc>Spublic function xxxxxxx()\<esc>=="
    exec ":normal! o\t{\<esc>"
    exec ":normal! o" . g:selection . "\<esc>"
    exec ":normal! o\t}\<esc>%k2w"
    set nopaste
endfun
  • Might be worth including the bit form a couple of lines further down about the options being reset when 'paste' is switched off so the fix (set nopaste at the end) is more obvious. – Rich May 18 '17 at 9:04
  • @Rich done. Growing too lazy these days – muru May 18 '17 at 9:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.