The story of running python and displaying the results without closing vim

Thing you want to do

  1. Run python without closing vim
  2. Display the execution result in a new buffer

What was made

--Execution by pressing <F5> only for python files --The execution result is displayed in a new buffer --If executed multiple times, it will be added. --The file with the cursor is executed when multiple python files are open

vimpy.gif

place

This content was written in vimrc. vimrc is

 :edit $MYVIMRC

You can open it with. If you have not changed the settings

:vnew $HOME/_vimrc

You can also open it here. You can check the settings with : version.

vimrc help: h vimrc

Recommended: All Vim configuration files should be in the $ HOME / .vim / directory ( $ HOME / vimfiles / on MS-Windows). This will make it easier to copy the configuration file to another system.

You can check $ HOME with: echo $ HOME. If you want to create vimrc under $ HOME / vimfiles, the name is vimrc, but under $ HOME. If you put it, it will be named _vimrc.

What i did

Naive way

:!python %

The Ex command :! Hoge will execute cmd hoge, assigning it to <F5>.

autocmd BufRead,BufNewFile *.py inoremap <F5> <Esc>:w<CR>:! python %<CR>
autocmd BufRead,BufNewFile *.py nnoremap <F5> :w<CR>:! python %<CR>

Now you can run the open file by pressing <F5>.

problem

The execution result disappears by pressing ʻENTER`.

How to open a new buffer

I've set it to open a new buffer to solve the above problem, except if it's already open, it will multiply every time I press <F5>, so I need to separate cases to solve this. Because it became long, I made a function called Pyexe (). At this time, since the :! Hoge used earlier is only executed, usesystem (hoge)that can obtain the output as a character string.

"Define function
function Pyexe()
"Preparing to return after inputting the result to the output buffer
    "Get the current position of the cursor
    :let pos=getpos(".")
    "Get the id of the current window
    :let cwinid=win_getid()
    "Get the filename of the buffer in the current window
    :let fileName=expand('%')
"Buffer settings for output
    "Decide the file name to display
    :let outFileName="~pyOut"
"Preparing to check if the output window is already open
    "Get the buffer number if a buffer for output exists.If it does not exist-1.
    :let bnr=bufnr(outFileName)
    "Get the window id of the buffer for output(List format).Empty list if it does not exist.
    :let wids=win_findbuf(bnr)
"If there is a buffer for output, change the window id to outWindid.Make if it doesn't exist.
    if bnr == -1 || len(wids)==0
    "If it does not exist
        "Allow the output buffer to be closed at the same time when the python file is closed
        :autocmd QuitPre <buffer> exe(':bwipeout!') g:bnr
        "Split the window to create a buffer for output
        :exe 'vertical rightbelow new' outFileName
        "Set the buffer type to nofile as the user does not write
        :set buftype=nofile
        "Set to exit by simply pressing q in normal mode.
        "<buffer>The option should be applied only to the output buffer created this time..
        :nmap <buffer> q <C-u>:bwipeout!<CR>
        "Adjust window size
        :vertical resize 70
        "Get the buffer buffer number for output
        :let bnr=bufnr(outFileName)
    else
    "If there
        "Fetch the output buffer window id from the list
        :let outWinid=wids[0]
        "Move to the output buffer window
      :call win_gotoid(outWinid)
    endif
"output
    "Move to the end of the output buffer
    :call setpos(bnr,"$")
    "Call cmd to run python
    :let @r=system('python '.fileName)
    "Put to the output buffer
    :put r
    "Re-depiction
    :redraw!
"Return to start position
    "Go to python file window
    :call win_gotoid(cwinid)
    "Move the cursor to the start position
    :call setpos(".",pos)
endfunction

After that, assign this to <F5> only for python.

"Only for python files<F5>Make it possible to execute by pressing a key
autocmd BufRead,BufNewFile *.py inoremap <F5> <Esc>:w<CR>:call Pyexe()<CR>
autocmd BufRead,BufNewFile *.py nnoremap <F5> :w<CR>:call Pyexe() <CR>

Recommended Posts

The story of running python and displaying the results without closing vim
The story of Python without increment and decrement operators.
The story of Python and the story of NaN
The process of installing Atom and getting Python running
The story of making Python an exe
The story of manipulating python global variables
The basics of running NoxPlayer in Python
The story of trying deep3d and losing
The story of blackjack A processing (python)
The story of low learning costs for Python
Summary of the differences between PHP and Python
The answer of "1/2" is different between python2 and 3
Specifying the range of ruby and python arrays
Compare the speed of Python append and map
Image processing? The story of starting Python for
The story of reading HSPICE data in Python
About the * (asterisk) argument of python (and itertools.starmap)
A discussion of the strengths and weaknesses of Python
Python --Explanation and usage summary of the top 24 packages
the zen of Python
Visualize the range of interpolation and extrapolation with python
The story of FileNotFound in Python open () mode ='w'
The story of sys.path.append ()
Referencing and changing the upper bound of Python recursion
I checked out the versions of Blender and Python
The story of automatic language conversion of TypeScript / JavaScript / Python
The story of implementing the popular Facebook Messenger Bot with python
Visualize the results of decision trees performed with Python scikit-learn
The story of how the Python bottle worked on Sakura Internet
[python] plot the values ​​before and after the conversion of yeojohnson conversion
The story of displaying images with OpenCV or PIL (only)
The story of rubyist struggling with python :: Dict data with pycall
The process of making Python code object-oriented and improving it
The websocket of toio (nodejs) and python / websocket do not connect.
I want to know the features of Python and pip
[Tips] Problems and solutions in the development of python + kivy
[Python] Tensorflow 2.0 did not support Python 3.8, so the story of downgrading Python
Play with the password mechanism of GitHub Webhook and Python
The story of building Zabbix 4.4
Towards the retirement of Python2
[Apache] The story of prefork
About the ease of Python
Reuse the results of clustering
About the features of Python
Source installation and installation of Python
The Power of Pandas: Python
The story of returning to the front line for the first time in 5 years and refactoring Python Django
I compared the speed of Hash with Topaz, Ruby and Python
The story that the version of python 3.7.7 was not adapted to Heroku
Note: Get the first and last items of Python OrderedDict non-destructively
Python: Update pyenv without thinking and solve the "where is Python?" Phenomenon
March 14th is Pi Day. The story of calculating pi with python
A story that struggled to handle the Python package of PocketSphinx
[Introduction to Python] I compared the naming conventions of C # and Python.
[Python] How to get the first and last days of the month
[Python] I thoroughly explained the theory and implementation of logistic regression
The story of making a standard driver for db with python.
[Python] I thoroughly explained the theory and implementation of decision trees
Get and set the value of the dropdown menu using Python and Selenium
[Python + heroku] From the state without Python to displaying something on heroku (Part 1)
Convert the result of python optparse to dict and utilize it