Save and run at the same time in Vim

前端 未结 12 514
悲哀的现实
悲哀的现实 2021-01-30 03:13

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&qu

相关标签:
12条回答
  • 2021-01-30 03:50
    1. Consider switching to IDLE. F5 does everything.

    2. Consider switching to Komodo IDE. You can define a command so that F5 does everything.

    0 讨论(0)
  • 2021-01-30 03:53

    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...

    0 讨论(0)
  • 2021-01-30 03:54

    Command combination seems to work through the | character, so perhaps something like aliasing :w|!your-command-here to a distinct key combination.

    0 讨论(0)
  • 2021-01-30 03:56

    Try making it inside the Bash.

    In case of a C file called t.c, this is very convenient:

    vi t.c &&  cc t.c -o t && ./t
    

    The and symbols (&&) ensure that one error message breaks the command chain.

    For Python this might be even easier:

    vi t.py && python t.py
    
    0 讨论(0)
  • 2021-01-30 03:57

    This is what I put in my .vimrc file and works like a charm:

    nnoremap <leader>r :w<CR>:!!<CR>
    

    Of course you need to run your shell command once before this, so it knows what command to execute.

    Example:

    :!node ./test.js
    
    0 讨论(0)
  • 2021-01-30 03:58

    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.

    0 讨论(0)
提交回复
热议问题