Create a plugin to run Python Doctest in Vim (1)

Introduction

"Create your first Vim plugin (autopep8) -I tried to fork / clone / update / push an existing repository to practice GitHub" Then. I explained how to customize and use an existing Vim plugin. This time, I will challenge to create a plug-in from scratch. It's a memorandum for myself written by a Vim beginner, so it's a rather confusing description. I hope it helps anyone who wants to create a Vim plugin in the future.

I chose Python Doctest as the subject. I have Python NumPy, SciPy, pandas I often use libraries such as /). In scientific calculations using these libraries, if the coding is incorrect, no error will occur and the incorrect answer will be silently returned. Only the person who made it can judge whether the result is correct or not. It is very important to ensure that your function always returns the correct result. Don't let one mistake spread to the whole and lead to a completely wrong conclusion. Doctest is used positively on a daily basis because it allows you to check the calculation results right next to the function definition. In order to make Doctest easier to use, I decided to create my own plugin.

In the following article

It is assumed that you have built a Vim environment with. If you would like to refer to it, please replace it with your own environment.

Create repository and update Vim config file

Create a new repository on GitHub. The name is vim-greater3. Clone under C: \ Users \ daizu \ Documents \ Vim \ plugin. Then, under the newly created vim-greater3 directory, create two directories, plugin and ʻautoload. In addition, create an empty file with the name greater3.vim` under each of these two directories.

Register this plugin in C: \ Users \ daizu \ vimfiles \ dotfiles \ _vimrc.

_vimrc.vim


NeoBundleLazy 'vim-greater3', {
\   'base': '~/Documents/Vim/plugin',
\   'type': 'nosync',
\   'autoload': {
\       'mappings' : ['<Plug>(greater3)'],
\   }
\}

Next, register the key mapping in C: \ Users \ daizu \ vimfiles \ after \ ftplugin \ python.vim.

ftplugin\python.vim


nmap <buffer> <F10> <Plug>(greater3)

Launch Vim and try : nmap. I can't find the F10 key mapping. Then open a suitable Python file and type : nmap

python


n <F10>    @<Plug>(greater3)

Was found. So far, it seems to be going well. Now, try pressing the F10 key. Nothing happened. I expected to get some kind of error message, but nothing came out.

Let's write a plugin. Write the following content in C: \ Users \ daizu \ Documents \ Vim \ plugin \ vim-greater3 \ plugin \ greater3.vim and save it.

plugin\greater3.vim


if exists('g:loaded_greater3')
  finish
endif

nnoremap <silent> <Plug>(greater3) :<C-U>echo 'greater3'<CR>

let g:loaded_greater3 = 1

In order to reflect the changes you just made immediately, launch another Vim apart from the Vim editing plugin \ greater3.vim (the same applies to the example below). When I open a Python file and press F10, it now shows greater3 on the command line. Running a Python file with QuickRun is also easy:

a.py


print('greater3!!!')

plugin\greater3.vim


nnoremap <silent> <Plug>(greater3) :<C-U>QuickRun<CR>

Finally I will write VimScript.

plugin\greater3.vim


nnoremap <silent> <Plug>(greater3) :<C-U>call greater3#run()<CR>

Press F10 on the Python file to go to the command line

python


E117: Unknown function: greater3#run

It will be displayed. As expected. We will create the actual plug-in. In Vim, if you try to call an undefined function, it will search under the ʻautoloaddirectory. Write the following contents inC: \ Users \ daizu \ Documents \ Vim \ plugin \ vim-greater3 \ autoload \ greater3.vim` and save it.

autoload\greater3.vim


function! greater3#run()
  let l = line('.')
  echo l
endfunction

The line number of the cursor is now displayed with the F10 key.

Let's link VimScript and Python. "Create your first Vim plugin (autopep8) -I tried to fork / clone / update / push an existing repository to practice GitHub" It is a practice of what I learned in. Rewrite ʻautoload \ greater3.vim` to the following contents so that Python can be used in VimScript.

autoload\greater3.vim


function! greater3#run()
  let l = line('.')
py3 << EOF
l = int(vim.eval('l'))
vim.command('echo {}'.format(l))
EOF
endfunction

function! s:init_py_modules()
py3 << EOF
import vim
vim.command('echo "init_py_modules"')
EOF
endfunction

call s:init_py_modules()

Open the Python file and press F10

python


init_py_modules
1

It will be displayed. 1 is because the current cursor is at the beginning of the buffer. You can see that you can access Vim from within Python with the vim.eval and vim.command functions of the Python vim module. It seems that you can do various things with this function. Now, try pressing the F10 key again. Then,

python


1

have become. The s: init_py_modules function is executed only when ʻautoload \ greater3.vim is loaded, so ʻinit_py_modules is not displayed with the second F10 key. This is as expected. What surprised me was that I could access the vim module on the second run without any problems, even though I didn't import the vim module inside the greater3 # run function. In other words, the first F10 key import of the vim module remains valid, in other words, the Python session continues. This has given me hope in creating a Doctest plugin.

The reason for this is that the following file is executed by QuickRun. This is a typical export in a Python program that performs scientific and technological calculations.

a.py


import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

It will take some time from the time you set : QuickRun to the end of execution. It takes about the same amount of time after the second time. This is because the library is imported each time it is executed. Now, let's try the plug-in. Rewrite ʻautoload \ greater3.vim` to the following content.

autoload\greater3.vim


function! greater3#run()
py3 << EOF
vim.command('echo {:.6f}'.format(np.pi))
EOF
endfunction

function! s:init_py_modules()
py3 << EOF
import vim
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
vim.command('echo "init_py_modules"')
EOF
endfunction

call s:init_py_modules()

The first run takes about the same time as QuickRun, but the second and subsequent runs return instant results. great. I don't want to wait for the library import to finish every time I do a Doctest.

Summary

I am trying to create a Vim plugin for the purpose of comfortably performing Python Doctest with Vim. Before getting into the main subject, it's getting longer, so I'll stop here. I will summarize this article.

Next time, I will create a Python module that performs Doctest.

Recommended Posts

Create a plugin to run Python Doctest in Vim (2)
Create a plugin to run Python Doctest in Vim (1)
Write a vim plugin in Python
Write a simple Vim Plugin in Python 3
Create a Vim + Python test environment in 1 minute
I want to create a window in Python
How to create a JSON file in Python
Create a Wox plugin (Python)
Create a shortcut to run a Python file in VScode on your terminal
Create a function in Python
Create a dictionary in Python
A memorandum to run a python script in a bat file
Create a plugin that allows you to search Sublime Text 3 tabs in Python
Create a DI Container in Python
Create a binary file in Python
Create a Kubernetes Operator in Python
5 Ways to Create a Python Chatbot
Run a simple algorithm in Python
Create a random string in Python
Create a tool to check scraping rules (robots.txt) in Python
Create a simple GUI app in Python
Create a JSON object mapper in Python
How to create a heatmap with an arbitrary domain in Python
Run the Python interpreter in a script
How to get a stacktrace in python
[GPS] Create a kml file in Python
How to run a Maya Python script
I made a plugin to generate Markdown table from csv in Vim
[Python] [Word] [python-docx] Try to create a template of a word sentence in Python using python-docx
What is the fastest way to create a reverse dictionary in python?
[Python] List Comprehension Various ways to create a list
Edit Excel from Python to create a PivotTable
Create a GIF file using Pillow in Python
Try to calculate a statistical problem in Python
How to create a Python virtual environment (venv)
How to clear tuples in a list (Python)
To execute a Python enumerate function in JavaScript
How to embed a variable in a python string
Type Python scripts to run in QGIS Processing
Create a standard normal distribution graph in Python
Create a virtual environment with conda in Python
A clever way to time processing in Python
Steps to develop a web application in Python
Steps to create a Twitter bot with python
To add a module to python put in Julialang
Create a simple momentum investment model in Python
How to notify a Discord channel in Python
Split files when writing vim plugin in python
I want to create a plug-in type implementation
Create a new page in confluence with Python
A Vim plugin that automatically formats Python styles
Create a datetime object from a string in Python (Python 3.3)
How to run Leap Motion in non-Apple Python
Create a package containing global commands in Python
[Python] How to draw a histogram in Matplotlib
How to create a Rest Api in Django
Create a MIDI file in Python using pretty_midi
Create a loop antenna pattern in Python in KiCad
[Docker] Create a jupyterLab (python) environment in 3 minutes!
Create a Python module
Create SpatiaLite in Python