27

I get a variable's value in vim's script, and how to write it into the file I'm editing now.

e.g.

"=== get date
let TodayDate=system("date")

2 Answers 2

54

You can use :put to put the contents of the variable (or expression) into the current buffer

:put =TodayDate

The help for :h :put

                                                        :pu :put
:[line]pu[t] [x]        Put the text [from register x] after [line] (default
                        current line).  This always works linewise, thus
                        this command can be used to put a yanked block as new
                        lines.
                        The cursor is left on the first non-blank in the last
                        new line.
                        The register can also be '=' followed by an optional
                        expression.  The expression continues until the end of
                        the command.  You need to escape the '|' and '"'
                        characters to prevent them from terminating the
                        command.  Example: 
                                :put ='path' . \",/test\"
                        If there is no expression after '=', Vim uses the
                        previous expression.  You can see it with ":dis =".

For mappings and editing <C-R>= is probably better than :put since it allows you to use the expression register and output the contents at the cursor location. (Take a look at :h <C-R>)

Sign up to request clarification or add additional context in comments.

5 Comments

very great! I had read Learn vi & vim editor but didn't found this! thank you! It works well.
@FDinoff I must've fat-fingered the downvote when voting. I can't change my vote unless you edit your answer. If you edit, I'll change it to upvote. Thanks, by the way!
Any way of putting the text in the cursor's position?
To put vim option values to text, you need to add & before the option. See an related post here.
To be clear, if mapping, do you recommend to save variable (TodayDate) to a register, and afterwards to :put the register. Is that right?
3

How about the following?

execute "normal! i" . TodayDate

This will put you in insert mode and insert the content of TodayDate at the cursor position.

2 Comments

+1. If textwidth not zero (i.e. inf), then next map save-change and finaly reset it. To not having problems if the string (TodayDate) pass the tw char. nnoremap <buffer> <leader>zzz \ : let tw_ztc=&tw \ <bar> :set tw=0<CR><Esc> \ :execute 'normal! o' . str_zzz_01 \ <bar> :execute 'normal! o' . str_zzz_02<CR> \ :set tw=&tw_ztc<CR>
This way is more computer consuming than the accepted, but it holds auto-indentantion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.