问题
In MATLAB, we can write to the editor the following
%% -- a example cell --
plot(rand(3));
%% -- another cell
A=rand(2^10);
t=linspace(-pi,pi,2^10);
compass(fft(A*sin(t))
and we can just hit Ctrl+Enter to run the cell being clicked by the mouse pointer.
Now I know in Vim, I can do
:'<,>'w !matlab
to run a visually selected block of code.
But how do I implement the MATLAB-like cell mode in Vim/gVim?
For example some python code
import os
import subprocess
import random
## 1st cell
ps =["python", "-h"]
out = subprocess.Popen(ps).communicate()[0]
print out
## 2nd cell
# import random -sould not be needed if we concatenate the import section and the cell
print random.randint(1,100)
Can anyone offer some ideas?
回答1:
Not sure exactly what you're asking, but if what you want is to process a cell block upon double-clicking in the block with a mouse, then you can map mouse-double-click (the <2-LeftMouse>
mapping) to call a function:
nnoremap <buffer> <2-LeftMouse> :call ProcessMouseDoubleClick()<CR>
ProcessMouseDoubleClick() would be a function that (1) visually selects the "cell" area and (2) issues '<,>'w !matlab
to have matlab run the selected code.
When calling ProcessMouseDoubleClick the Vim cursor will be located at whatever point you clicked in the document. Other than that, there's nothing specific to the mouse. So you could also map any key to same function, e.g., a mnemonic command for 'evaluate cell':
map <buffer> <Leader>ec :call ProcessMouseDoubleClick()<CR>
So, there's not really any reason to have function name referencing mouse at all, you might want to call it something like EvaluateMatlabCell()
.
回答2:
Here's my option for matlab, but it can be easily adapted for python. It switches from vim to a Matlab window and then you paste with the mouse or the keyboard shortcut. I described it in details there: Vim and matlab GUI - Emulate matlab Run (<F5>) with Vim
The following, ensures you are in the right directory before running the cell, and also goes back to Vim after evaluating the cell (if you have correctly configured the external editor in matlab. I use:gvim --servername MAT --remote-tab-silent).
function! MatRunCellAdvanced()
execute "!echo \"cd(\'".expand("%:p:h")."\')\">/tmp/buff"
:?%%?;/%%/w>> /tmp/buff
execute "!echo \"edit ".expand("%:f")."\">>/tmp/buff"
!cat /tmp/buff|xclip -selection c
!cat /tmp/buff|xclip
!wmctrl -a MATLAB
endfunction
map ,n :call MatRunCellAdvanced() <cr><cr>
来源:https://stackoverflow.com/questions/5093306/how-to-implement-matlab-like-cell-mode-in-vim