Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save and run at the same time in Vim

Tags:

python

vim

I do a lot of Python quick simulation stuff and I'm constantly saving (:w) and then running (:!!). Is there a way to combine these actions?

Maybe a "save and run" command.

like image 365
Nope Avatar asked Mar 02 '09 01:03

Nope


People also ask

How do I save and exit Vim?

The simplest way to both save and quit out of VI or VIM is with a keyboard shortcut ZZ. Note the capitalization, which means the save and quit command is executed by pressing Escape, then holding the Shift key then pressing Z twice, thus: Press the ESC key, then hold the Shift key then press Z twice.

How do I save a file in Vim editor?

The command to save a file in Vim is :w . To save the file without exiting the editor, switch back to normal mode by pressing Esc , type :w and hit Enter . There is also an update command :up , which writes the buffer to the file only if there are unsaved changes.

How do I save a vim file in Terminal Mac?

To save a file, you must first be in Command mode. Press Esc to enter Command mode, and then type :wq to write and quit the file. The other, quicker option is to use the keyboard shortcut ZZ to write and quit. To the non-vi initiated, write means save, and quit means exit vi.


2 Answers

Okay, the simplest form of what you're looking for is the pipe command. It allows you to run multiple cmdline commands on the same line. In your case, the two commands are write `w` and execute current file `! %:p`. If you have a specific command you run for you current file, the second command becomes, e.g. `!python %:p`. So, the simplest answer to you question becomes:

:w | ! %:p  ^ ^ ^  | | |--Execute current file  | |--Chain two commands  |--Save current file 

One last thing to note is that not all commands can be chained. According to the Vim docs, certain commands accept a pipe as an argument, and thus break the chain...

like image 83
Douglas Mayle Avatar answered Sep 21 '22 22:09

Douglas Mayle


Option 1:

Write a function similar to this and place it in your startup settings:

function myex()    execute ':w'    execute ':!!' endfunction 

You could even map a key combination to it -- look at the documentation.


Option 2 (better):

Look at the documentation for remapping keystrokes - you may be able to accomplish it through a simple key remap. The following works, but has "filename.py" hardcoded. Perhaps you can dig in and figure out how to replace that with the current file?

:map <F2> <Esc>:w<CR>:!filename.py<CR> 

After mapping that, you can just press F2 in command mode.

imap, vmap, etc... are mappings in different modes. The above only applies to command mode. The following should work in insert mode also:

:imap <F2> <Esc>:w<CR>:!filename.py<CR>a 

Section 40.1 of the Vim manual is very helpful.

like image 27
gahooa Avatar answered Sep 21 '22 22:09

gahooa