Nick
Nick

Reputation: 2911

Make VIM function return text without indent

I guess this question could be taken in two ways...

  1. (Generic) - is there a way to specify settings 'local' to a function (setlocal changes seem to persist after the function call)...

  2. (Specific) - I have a function which gets called from an imap mapping (which takes a user input to pass into the function. The function works perfectly if I run set paste or set noai | set nosi either just before running my shortcut, or added into the function itself. The problem is, whichever way I do it, those setting changes persist after my function call.

Essentially, my workflow is:

  1. In insert mode, type //// at which point I get prompted for input text, which I enter and press enter.
  2. The function is called with my input. I need the function to disable indenting, return my string and then re-enable the previous settings. The string would just be a PHP-block comment like this:

    /**
     * Blah {INPUT TEXT}
     */
    

Any suggestions appreciated. My script currently looks like this:

function CommentInjector(txt)
  return "\/**" ."\<CR>"
  \    . " * foo " . a:txt . " bar " . "\<CR>"
  \    . " */"
endfunction
imap <silent> //// <C-R>=CommentInjector(input("Enter some text:"))<CR>

UPDATE

Managed to figure it out at least how to dump a comment in... Would appreciate knowing how to get/restore settings though...

function! CommentInjector(txt)
  set paste

  exe "normal! i/**\<CR>"
  \          . " * fooo " . a:txt . " bar\<CR>"
  \          . " */\<Esc>"

  set nopaste
endfunction

map <C-C><C-C><C-C> :call CommentInjector(input("Enter some text:"))<CR>

Using this you can just pres Ctrl+C 3 time, enter text when prompted and you get a nice comment written in. It assumes you had "set paste" disabled before running though...

Upvotes: 1

Views: 189

Answers (1)

Randy Morris
Randy Morris

Reputation: 40927

Since you've posted an update and are really just looking at how to save/restore settings, I'll give a general solution.

  • At the start of your function save the initial value of the setting: let save_paste = &paste
  • Make any changes to paste that you'd like to make
  • Restore it at the end: let &paste = save_paste

An example of this can be found in the documentation with :help use-cpo-save where they talk about saving and restoring the value of cpoptions.

Upvotes: 1

Related Questions