Vim [compile and] run shortcut

后端 未结 6 700
醉梦人生
醉梦人生 2020-12-12 17:21

Basically what I want is a keyboard shortcut in vim that lets me [compile and] run the currently being edited C, C++ or Python program. In psuedocode:

when a         


        
6条回答
  •  Happy的楠姐
    2020-12-12 18:01

    I wanted to find a shortcut too. But I didn't want to use autocmd for some reason. I used bash script. I was already using a bash script to compile and run my C/C++ codes. So, I thought, why don't I use a bash script and use it in fltplugin file for C and C++. I made two separate bash scripts. One for C and one for C++. Here is the script for C (For C++, it is also similar just change the compiler to clang++/g++, std=c2x to std=c++20 and $filename.c to $filename.cpp),

    filename=$1
    compiler=clang-10
    if [ $2 ]; then
        if [ $2 == "-v" ]; then
            FLAGS="-g -Wall -Wextra -pedantic -std=c2x"
        fi
    else
        FLAGS="-Wall -Wextra -pedantic -std=c2x"
    fi
    
    $compiler $FLAGS $filename.c -o $filename -lm
    
    return_value=$?
    
    if [ $return_value -eq 0]; then
        if [ $2 ]; then
            if [ $2 == "-v" ]; then
                valgrind ./$filename
                rm $filename
            fi
        else
            ./$filename
            echo
            echo "[process exited $return_value]"
            rm $filename
        fi
    fi
    

    Saved it as run. I made it executable for all users,

    $ chmod 777 run
    

    I moved it to my user bin directory.

    $ mv run ~/bin
    

    If you dont have a user bin directory, make on. Go to your home directory, and make a directory named bin.

    $ cd ~
    $ mkdir bin
    

    Then move the run (or whatever name you gave to your script) file to the bin directory.

    $ mv run ~/bin
    

    Let's move on. Then I made a c.vim file in ~/.vim/after/ftplugin directory. And add two new key remaps to the c.vim file.

    nnoremap  :vertical bo term run %:r
    
    # This will run my code with valgrind
    nnoremap  :vertical bo term run %:r -v 
    

    Here are some screen shots,

    Clicking F9 shows me the output screen in a vim buffer,

    Clicking F2 shows me the output using valgrind in a vim buffer

    You can do same for C++, just make a cpp.vim file in ~/.vim/after/ftplugin directory. And make another run file (like run_cpp), save it in your user bin(~/bin) file. Make some custom key bindings, and you are good to go.

提交回复
热议问题