Skip to content

Instantly share code, notes, and snippets.

@bfredl
Forked from tarruda/nvim-terminal-edit.py
Last active March 1, 2024 01:02
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save bfredl/e5b05193304a3340e29e998662ffff76 to your computer and use it in GitHub Desktop.
Save bfredl/e5b05193304a3340e29e998662ffff76 to your computer and use it in GitHub Desktop.
Edit file in host Neovim instance from a :terminal buffer
#!/usr/bin/env python
"""Edit a file in the host nvim instance."""
from __future__ import print_function
import os
import sys
from neovim import attach
args = sys.argv[1:]
if not args:
print("Usage: {} <filename> ...".format(sys.argv[0]))
sys.exit(1)
addr = os.environ.get("NVIM_LISTEN_ADDRESS", None)
if not addr:
os.execvp('nvim', args)
nvim = attach("socket", path=addr)
def _setup():
nvim.input('<c-\\><c-n>') # exit terminal mode
chid = nvim.channel_id
nvim.command('augroup EDIT')
nvim.command('au BufEnter <buffer> call rpcnotify({0}, "n")'.format(chid))
nvim.command('au BufEnter <buffer> startinsert'.format(chid))
nvim.command('augroup END')
nvim.vars['files_to_edit'] = args
for x in args:
nvim.command('exe "drop ".remove(g:files_to_edit, 0)')
def _exit(*args):
nvim.vars['files_to_edit'] = None
nvim.command('augroup EDIT')
nvim.command('au!')
nvim.command('augroup END')
nvim.stop_loop()
nvim.run_loop(_exit, _exit, _setup)
@abaldwin88
Copy link

Works great! Thank you!

@tbelaire
Copy link

Doesn't adjust the working directory.

But thanks.

@tbelaire
Copy link

args = [os.path.abspath(f) for f in args]

Fixes it

@mknz
Copy link

mknz commented Jan 21, 2017

Thanks, this is what I've been looking for!

However, os.execvp ignores first argument.
Below is a fix to open files correctly when there is no nvim running.

if not addr:
    os.execvp('nvim', [''] + args)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment