When using Python scripts, you need to learn the appropriate knowledge. VIM has a wide range of Python script applications. The current implementation principle is very simple. Execute the VIM function JPython () in VIM, and then the function is responsible for calling python (of course, the common version of python needs to be put into the environment variable ).
The called command is "python-c...", that is, directly execute the following string, which contains the complete execution script. In the script, first open a file and use fp. readlines () read all rows and put them in a list (g_text). Then execfile () is used to call the Script Name passed in by JPython () and the global variable g: JPYTHON_PATH. In this way, you can directly use the g_text variable without worrying about file IO and path issues in the Python script. After python outputs the content using print or sys. stdout, the original content is replaced by VIM. The Code is as follows.
- Function! JPython (py_fname)
- Let w: fname = g: JPYTHON_PATH. '/'. a: py_fname
- Echo bufname (".")
- Let w: cmd = 'fp = open (r "'. bufname (". ").'", "rb ");'
- Let w: cmd. = 'G _ text = fp. readlines ();'
- Let w: cmd. = 'fp. close (); del fp ;'
- Let w: cmd. = 'execfile ("'. w: fname .'");'
- Exec '%! Python-c "'. escape (w: cmd ,"'\"").'"'
- "^ M will be generated after the output is found and replaced
- If has ('windows ')
- Try
- Exec '% s/\ r // G'
- Catch
- Endtry
- Endif
- Endfunction
- Let g: JPYTHON_PATH = "D:/scripts/vim"
Copy the function to vimrc and configure g: PYTHON_PATH to the specified position.
This is just a simple implementation of the idea. There may be a better way to operate in the actual environment, and there should be a better way to achieve interaction between VIM and Python. Some may ask why VIM scripts are not directly used. The main reason is that I only implement this simple function for VIM scripts. I believe there are not many people studying VIM scripts to use VIM, not to mention complex applications. python is relatively popular and widely used. It is relatively skilled in writing and modifying.
If you have any good ideas or suggestions, please leave a message for me. You are also welcome to propose a better solution.