Sending input to a screen window from vim - vim

I have a vim function set up where I can highlight a line of text and execute in clojure. Here's the function:
function! Clojure_execline()
let cl = (getline(line(".")))
// ...
exec 'clojure -e "' . cl . '"'
endfunction
The problem with this is that it's slow to start and because it spawns a new clojure session every time I run it, I can't call a function I ran previously. Ideally, I'd like for a hidden repl to be running where I could send input from vim and retrieve the output from as well. I learned about gnu screen and thought it could help me, but I don't know how to send input from one screen window to another.
To clarify my problem, take this line of clojure:
(defn add2 [x y] (+ x y))
I'd like to be able to highlight this line in vim and execute in a running repl. I want to be able to call the line below and have it execute in the same repl:
(add2 4 5)
Afterwards, I'd like to be able to get the output of the function.
So, basically, my question is, how do I send input from one screen window to another?

Jake McCrary's suggestion is a good one. There are also a couple other scripts available, probably based on same idea:
VimClojure, which says it does "repl in a vim buffer"
and
slimv, specifically supports Clojure
and
Gorilla, I think VimClojure, above, is based on Gorilla
I don't know whether VimClojure actually does what you want, sending result back from Screen to buffer in Vim. One way to do that, I think, would be to finagle something using Vim's client-server functionality, possible with the --remote-send flag. See:
:h client-server
:h --remote-send

I don't have an exact answer, but it might be worth taking a look at slime.vim and seeing if anything can be learned from it.
blog post about it
script at vim.org

Found what I was looking for. You can execute this from a terminal to send a string directly to the stdin of a screen window:
$ screen -X stuff "ls -l\015" # \015 sends a carrige return.

You might also be interested in Conque http://code.google.com/p/conque/
I use it for Scala

Related

Using vimscript to run test scripts by utilizing normal vim commands

I started using VIM as my editor around six months back and I enjoy it very much. However, there are a few work related scripts that I'd like to implement to make my life easier. If there is anyone who can help me I would be grateful.
This is my question. I have some tests written in python and I wrote a key mapping to run those tests using vim terminal. It works perfectly. However, now I want to use VimScript and some vim functions to make it look better. I'm a beginner in VimScript and therefore, I'm not sure whether this is doable.
My folder structure looks like,
.
├── my_test.py
└── test
└── testRunner.py
1 directory, 2 files
My test code looks something like,
my_test.py:
#!/bin/python
class MyTest1:
def Run():
# Test body
class MyTest2:
def Run():
# Test body
test/testRunner.py:
#!/bin/python
print "Running the test"
My current key-mapping in .vimrc looks like:
nnoremap <leader>t mZ/class<CR>Nwyiw:noh<CR>:terminal<CR>cd test<CR>python testRunner.py <C-W>"0<CR><C-W><C-W>'Z
What this does is,
Find the test name (the test that I'm currently editing)
Copy the name and run that test name in a vim-terminal
What I want it to be something which looks like:
nnoremap <leader>t :call RunThisTest()<CR>
function! RunThisTest()
RememberEditContext()
FindAndCopyTestName()
RunTestInTestDirectory()
ReturnToEditContext()
endfunction
Can someone help me in developing these functions?
Thank you in advance!
One option is to use the :normal! command directly, which allows you to run a sequence of keystrokes directly as you'd have used them in a mapping.
But it turns out we can do better, much better, so let's get to it!
Searching and Matching
You can use the search() function to look for the class you're in. You can pass it flags, such as bcnW, to have it search backwards, possibly match at the cursor position, do not move the cursor and do not wrap around the file. Putting it all together:
let line = search('^class \w', 'bcnW')
This will return a line number if there was a positive match, or 0 if there wasn't one. If there was a match, we can use getline() to get its contents and then matchlist() to capture the name of the class.
let [_, classname; _] = matchlist(getline(line), '^class \(\w\+\)')
As you can see, using Vimscript we were able to get the classname without moving the cursor and without touching the search register. So we didn't need to set any marks and we won't need to worry about recovering the current position and view!
Running a command
Now it's time to run a command on the terminal. We can simplify the process by passing it a command directly. (Note that there's a difference here, in that the terminal will run just that command, it won't leave the shell around after finished. Depending on your use case, you might prefer to do something more akin to what you're doing now.)
We can run the command in a terminal with:
:terminal ++shell cd test && python testRunner.py MyTest1
But, of course, we need to actually pass it the class name we got, not a fixed value here. We can use the :execute command for this purpose. It takes a string and runs it as a Vimscript command. We can use this to assemble the string dynamically.
execute "terminal ++shell cd test && python testRunner.py ".shellescape(classname)
Finally, to go back to the original window, we can use the :wincmd command, more specifically wincmd p.
Putting it together
The resulting function is:
function! RunThisTest() abort
let line = search('^class \w', 'bcnW')
if line == 0
echoerr "Not inside a test class!"
return
endif
let [_, classname; _] = matchlist(getline(line), '^class \(\w\+\)')
execute "terminal ++shell cd test && python testRunner.py ".shellescape(classname)
wincmd p
endfunction
nnoremap <silent> <leader>t :call RunThisTest()<CR>
There's definitely room for improvement, but this should get you started!
Saving and restoring context
We didn't go into saving and restoring context, since this case actually didn't need any of that!
If you were to develop functions that use commands that affect global context, you can use Vimscript to save and restore it.
For example, if you're going to search, you can save the #/ register and restore it after the search:
let saved_search = #/
/class
let #/ = saved_search
If you're going to yank into a register, you can save and restore it too. For example, #" for the default register. You should also save the register type, which records whether the contents were taken in a character-wise, linewise or blockwise context.
let saved_register = getreg('"')
let saved_regtype = getregtype('"')
normal! y3W
let words = getreg('"')
call setreg('"', saved_register, saved_regtype)
You can also save the current view, which includes the position your cursor is in, but also the other parameters of the window, such as what the first displayed line and column are, such that you can fully restore that context. See the winsaveview() and winrestview() functions for details on that.
Managing Terminals
There are functions to control the terminal that go way beyond what :terminal can do.
For instance, the much richer term_start() allows running a command as a list and passing options such as 'cwd' to run the command on a different directory.
So we could simplify our test execution with:
call term_start(['python', 'testRunner.py', classname], {'cwd': 'test'})
There's also term_sendkeys() which you can use to send keystrokes to the terminal. For example, if you prefer to start a shell and call the Python script through the shell:
let termbuf = term_start(&shell, {'cwd': 'test'})
call term_sendkeys(termbuf, "python testRunner.py ".shellescape(classname)."\r")
You can also use term_getline(termbuf, '.') to get the contents of the line where the cursor currently is. For instance, you could use that to detect whether the terminal is on a shell prompt (line ending in $ and whitespace) or still on an execution of a test runner.
Finally, you can even have the command running inside the terminal call Vim commands! Through special escape sequences, it can call exported functions or ask Vim to open files for editing. See :help terminal-api for details.
Learning More
This is all very neat... But how can I learn more?
My first strong recommendation would be to read the excellent "Learn Vimscript the Hard Way", by Steve Losh. It covers the basics of the language, how to interface with the editor (mappings, auto-commands, indentation expressions, filetypes) and basics of how to put together Vim plug-ins. It also covers common pitfalls of Vimscript and best practices for writing reliable code. That's a must if you want to get serious about scripting Vim.
Second suggestion is read the excellent documentation that's available through :help! Few applications are as well documented as Vim is, so knowing your way around the help system can really help a lot.
Third is using StackExchange. In particular, the Vi & Vim SE which is dedicated to the subject. Not only you'll find great answers there and you'll be able to ask great questions, you will also have the opportunity of seeing great questions, wonder how to solve them and possibly take a stab at writing an answer. (Personally, since I started using the Vi & Vim SE, my Vim-foo has greatly improved, to the point I can consider myself almost an expert.) I strongly recommend that.
Finally, practice. It typically takes a few attempts to get something really right. But the fact that the environment is fairly dynamic and flexible allows for experimentation. You can type and experiment with the commands in the editor itself, so it's usually quick to test your code and get it right as you're writing it.

How to execute a terminal program and perform an action when it closes in vimscript

I'd like to write a Vim command that does the following:
Make a new split.
Launch a terminal program.
Wait for the program to stop and close the split.
Read the output produced in the second step into the original buffer.
This seems like a very common work flow, but I'm having trouble getting it to work.
The problem is in steps 3 and 4. As a test I defined:
function MyExitFunction(a,b,c)
close
read blah
endfunction
Then did:
:new | call termopen('fzf>blah',{on_exit:MyExitFunction}
which does start the terminal and close the split after the program is done. The read command, however, seems to do nothing. Perhaps it reads the input into a wrong split?
What should I do to get the actual program output into my current buffer?
Note, fzf is not the actual program I'm running, but it works a bit like it.
If you have a command that cleanly outputs to stdout, then you simply need :read !<command>.
If you want interactivity, i.e. reading from stdin first, then you should probably run it inside a terminal with :vs | te and then yank the output over. Vim doesn't have a clean and easy way to interop with interactive scripts, so this is probably as good as it's gonna get.

Prevent gVim from returning control to command line (when called from Stata)

When I call gVim from Stata with shell (or equivalently with !) Stata doesn't wait for the command to finish and continues on with the .do file. I usually specify a short sleep and everything works great (discussed on the Stata mailing list here).
But sometimes the gVim call is lengthy and the length is unknown a priori. For example. I use gVim's argdo to remove headers from a folder of text files.
!gvim -c "argdo 1,3d | update" *sheet*.txt
Is there any way that I can force gVim to not return control to Stata? Or are my best options to complete this step outside the .do file or with a pause/lengthy sleep? Thanks!
Oh, I'm on Win 8 (64 bit) with gVim 7.3.
I think you would need to make this call a Stata command or the equivalent thereof.
That is, try running this separately from a do-file editor window or as wrapped up in a separate do-file.
I realise that is not an attractive solution, but in principle it seems the only one.
(sleep solutions I dislike as fudges, but I guess no one likes them on principle.)

Vim: map GNU Screen command

Apologies if this has been asked before, but I feel overwhelmed with the Vim docs and I can't seem to figure this out.
I want to map the F5 key in Vim to accomplish the following actions:
Yank text from the visual selection in Vim.
Execute the yanked portion of the text in another GNU Screen session named ipython.
The second portion could be achieved by issuing the following command line argument (via :!), if only I was able to find a way to paste the register content between the double quotes of that line (but I can't figure out how):
map <F5> :!screen -x ipython -X stuff "[REGISTER 0 CONTENT]"<CR><CR>
Any help would be much appreciated!
For the second part, you can use
:execute "!screen -x ipython -X stuff " . shellescape(#0)
Here I copy my previous answer:
Maybe one of these two plugins is what you need:
slime is screen-based.
tslime is a tmux-based version of slime.
Given the nature of your question - I encourage you to take a look at vim-ipython. Using this plugin, you can send lines or whole files for IPython to execute, and also get back object introspection and word completions in Vim, like what you get with: object?<enter> and object.<tab> in IPython.
If you follow that github link, there are a few screencasts demonstrating what you can do with it. It requires IPython 0.11 or later, though, with ZeroMQ enabled.

Run bash command on Vim and copy result to clipboard

How can I create a Vim command and copy it's results to clipboard?
I want to convert Markdown to HTML and copy the result to the clipboard. So far I got:
nmap md :%!/bin/markdown/Markdown.pl --html4tags
But this will substitute my opened file on Vim to the result of Markdown.
You didn't say which system you're using, but generally saving it in the +
register should work. You can call system():
:let #+=system("markdown --html4tags", join(getline(1,line("$")), "\n"))
The system() function takes the second parameter (optional) as input to the
command, and here I'm using a chain of other functions to retrieve the contents
of the current buffer. Not sure, but there should be a better way to do it (if
someone knows, please let me know).
Alternatively, you can pass markdown your file name as input directly:
:let #+=system("markdown --html4tags " . shellescape(expand("%:p")))
But keep in mind that you'll need to write the file before calling this.
Two important notes:
I didn't type your full path to markdown. Use it.
I didn't use maps here, the final result would be something like:
nnoremap md :let #+=system(...)
get the xsel package
and pipe stdout to xsel --clipboard
For instance:
cat /etc/passwd | xsel --clipboard
Is that what you're looking for?
Filling in a missing piece (2+ years late). With the clarification that the user was on a Mac and since the asker's "why doesn't it work for me?" question was not answered.
To redirect the output of a command to the system clipboard from within MacVim (GUI version) you need to set the '*' to be the "clipboard register" you need to change the clipboard setting to 'unnamed':
set clipboard 'unnamed' # 'cb' can be substituted for 'clipboard'
Then sidyll's answer should work except specify the '*' register and not the '+' register:
:let #*=system(...)
The clipboard feature is likely not compiled into the "terminal version" of MacVim and when it is available option setting is different from 'unnamed'. To see more details regarding what works where and how, see the documentation in MacVim using the Vim help command:
:help 'clipboard' (include the single quotes since it's a set option!)
(I'll skip the command mapping issue since it always takes me several tries and I still have to look it up; finding the help for the mapping commands should be easier than finding it for the * register.)

Resources