Linux – Tmux ranger integration: opening text files in new panes

linuxnanotmuxvim

Here we have some amazing tools: tmux, ranger, vim… Would be amazing to configure ranger to open the files (when text editable) in a tmux newpane? Is that easy and how it is done?

Best Answer

I did some research and find it is not too hard.

To open the current selected file in ranger in a new pane (to the right) in an ad-hoc manner, you can first go to ranger's command line (by pressing :) and then type shell tmux splitw -h 'vim %f' following by the <Enter> key.

To achieve this with some key binding, you can set it in a configuration file of ranger. For ranger 1.6+, key bindings are specified in rc.conf. So in ~/.config/ranger/rc.conf, use something like this:

map ef eval if 'TMUX' in os.environ.keys(): fm.execute_console("shell tmux splitw -h 'vim " + fm.thisfile.basename + "'")

While with ranger 1.4 you need a file ~/.config/ranger/keys.py with the following contents:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Customized key bindings.

from ranger.api.keys import *

map = keymanager.get_context('browser')
@map("ef")
def edit_file_in_new_tmux_pane(arg):
    command = "shell tmux splitw -h 'vim " + arg.fm.env.cf.basename + "'"
    if 'TMUX' in os.environ.keys(): arg.fm.execute_console(command)

With the above setting when you press ef in the ranger's browser, it will open a new tmux pane with vim editing the selected file.

The code is simply for demo, and it might need to involve with more safeguarding, such as checking for file type, etc.

Credit goes to ranger's help manual and $(pythonpkginstalldir)/ranger/defaults/rc.conf ($(pythonpkginstalldir)/ranger/defaults/keys.py for ranger 1.4). They are really helpful.