Skip to content

Instantly share code, notes, and snippets.

@leoluyi
Forked from tgirke/_Nvim-R-Tmux.md
Created January 10, 2019 13:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leoluyi/2aeb4795c99de487b568178a31f7b635 to your computer and use it in GitHub Desktop.
Save leoluyi/2aeb4795c99de487b568178a31f7b635 to your computer and use it in GitHub Desktop.
Nvim-R-Tmux: An Integrated Working Environment for R

Nvim-R-Tmux: Neovim-based IDE for R


Table of Content

  1. Overview
  2. Installation
    1. Neovim
    2. Tmux
    3. R package colorout
    4. Nvim-R plugin
    5. Nerdtree
    6. Color Scheme
    7. Setup in user accounts of UCR's HPCC
  3. Usage and configuration
  4. Config files

1. Overview

This page gives an overview of the installation and usage of the new Nvim-R plugin from Jakson Alves de Aquino, the developer of the original vim-R plugin. The new plugin now also supports the new extension of Vim called Neovim. The main advantages of Neovim compared to Vim are its better performance and its built-in terminal emulator facilitating the communication among Neovim and interactive programming environments such as R. Since the Vim and Neovim environments are managed independently, one can run them in parallel on the same system without interfering with each other. The Nvim-R project page can be found here and its main manual is here. The usage section below introduces how to use the plugin with or without Tmux.

2 Installation

2.1 Install Neovim for your OS

Neovim Version >= 0.1.7 is required for Nvim-R. For the installation, follow the instructions here. A sample config file for controlling Neovim, called init.vim, is given below. This or a similar init.vim file should be downloaded and saved to a user's home under ~/.config/nvim/init.vim.

2.2 Install Tmux

The usage of Tmux with Nvim-R is highly recommended on Linux or OS X systems but not absolutely necessary. Supported Tmux versions are >=2.0. To upgrade Tmux to a more recent version, one can follow the instructions here. To install it from source, consult this page. If you get on Ubuntu 16.04 a locale-gen en_US.UTF-8 error, then the last step here fixes it. A sample config file for controlling Tmux, called .tmux.conf, is given below. This or a similar .tmux.conf file should be downloaded and saved to a user's home under ~/.tmux.conf.

2.3 Install R package colorout

The R package colorout is available on GitHub here. If it is not yet installed in an R environment, one can install it from within R via the devtools package as follows:

devtools::install_github("jalvesaq/colorout")

2.4 Install Nvim-R plugin for Neovim

Download the latest *.vmb from here. Then open the downloaded file with nvim (neovim), and then run from nvim's command mode the following commands:

:packadd vimball
:so %
# press space bar a few times until install is complete!

2.5 Install Nerdtree (optional)

Download the Nerdtree vim plugin from here. Then extract to ~/.config/nvim with:

unzip NERD_tree.zip -d ~/.config/nvim

2.6 Color Scheme (optional)

Jakson Alves de Aquino has developed the southernlights color scheme that works well with Nvim-R. To enable it, users want to save the file southernlights.vim from this repos to ~/.config/nvim/colors/ and add the recommended bash configurations to your .bashrc as described here.

2.7 Setup in user accounts of UCR's HPCC

Neovim and Tmux are already installed systemwide on the HPCC, but need to be loaded from the module system (step 1). What remains to be installed in each user's account are the plugins and configuration files (steps 2-5).

  1. Add to your .bashrc the following lines
if [ -n "$MODULESHOME" ]; then
    module load neovim
    module load tmux/2.2
fi
  1. Install Nvim-R plugin for Neovim as instructed here
  2. Save this init.vim sample file to ~/.config/nvim/init.vim
  3. Install Nerdtree plugin as instructed here
  4. Install southernlights color scheme as instructed here
  5. Now log out of the system and in again. After this start tmux and then open a .R or .Rmd file with nvim command. Next open a connected R session with the key combination \rf and then follow the usage instructions given here.

3. Usage and configuration

The usage of Neovim is almost identical to Vim. Two important differences are:

  1. The command for opening Neovim is nvim instead of vim.
  2. Plugins are usually stored under ~/.config/nvim/ and the counter part of the .vimrc config file is init.vim located at ~/.config/nvim/init.vim.

3.1 Run R in built-in terminal emulator

Open a *.R or *.Rmd file with nvim and intialize a connected R session with \rf. This command can be remapped to other key combinations, e.g. uncommenting lines 10-12 in init.vim will remap it to the F2 key. Note, the resulting split window among Nvim and R behaves like a split viewport in nvim or vim meaning the usage of Ctrl-w w followed by i and Esc is important for navigation.

Important keybindings for nvim (vim):

  • \rf: opens vim-connected R session
  • spacebar: sends code from vim to R; here remapped in init.vim from default \l
  • :split or :vsplit: splits viewport (similar to pane split in tmux)
  • gz: maximizes size of viewport in normal mode (similar to Tmux's Ctrl-a z zoom utility)
  • Ctrl-w w: jumps cursor to R viewport and back; toggle between insert (i) and command (Esc) mode is required for navigation and controlling the environment.
  • Ctrl-w r: swaps viewports
  • Ctrl-w =: resizes splits to equal size
  • Ctrl-w 5< or 5>: resizes splits to left or right by 5 steps; change number as needed
  • Ctrl-w H or Ctrl-w K: toggles between horizontal/vertical splits
  • Ctrl-spacebar: omni completion for R objects/functions when nvim is in insert mode. Note, this has been remapped in init.vim from difficult to type default Ctrl-x Ctrl-o.
  • :h nvim-R: opens nvim-R's user manual; navigation works the same as for any Vim/Nvim help document
  • :Rhelp fct_name: opens help for a function from nvim's command mode with text completion support
  • Ctrl-s and Ctrl-x: freezes/unfreezes vim (some systems)

3.2 Run R in Tmux Pane

To run R in a separate Tmux pane, include the following two lines in your init.vim:

- `let R_in_buffer=0`
- `let R_tmux_split=1`

Open a *.R or *.Rmd file with nvim and start R with \rf. Similarly as above, the \rf command can be remapped to other key combinations, e.g. uncommenting three lines containing F2 in init.vim will remap it to the F2 key. To navigate among the Nvim and R panes, the key combination Ctrl-w-o is important.

Important keybindings for Tmux panes:

  • Ctrl-a o: jumps cursor to next pane e.g. from Nvim to R console pane
  • Ctrl-a Ctrl-o: swaps panes
  • Ctrl-z z: maximizes (zooms into) active pane

Note, closing R in this setup will also close the corresponding Tmux pane. This is different from the behavior of the older vim-R plugin where the R pane stayed open and returned a shell after quitting R. This behavior can be useful to open a different R version or ssh into remote systems while maintaining the connected Nvim pane from where code can still be sent to the original pane. To achieve a similar behavior with the new Nvim-R plugin, one can use the following workaround:

  1. Switch cursor scope to R esssion (with Ctrl-a o) and then execute from R pane system("tmux set remain-on-exit on")
  2. Quit R with q(). This gives a dead pane that can be reactivated by starting a shell in it with the commands Ctrl-a and :respawn-pane bash

4. Config files

The following config files (or similar custom versions) should be saved to the following locations in a user's home directory:

  • File init.vim for Neovim: ~/.config/nvim/init.vim
  • File tmux.conf for Tmux: ~/.tmux.conf
""""""""""""""""""""""
"""Nvim config file"""
""""""""""""""""""""""
" Save this file to ~/.config/nvim/init.vim
" Fixes weird character problem in some devel versions neovim under tmux sesssion. This might go away in future.
set guicursor=
" Uses color scheme southernlights from Jakson Alves de Aquino here: https://github.com/jalvesaq/southernlights
" To enable it, save file southernlights.vim to ~/.config/nvim/colors/
colorscheme southernlights
" Preferred default settings
set nowrap
" start R with F2 key
" map <F2> <Plug>RStart
" imap <F2> <Plug>RStart
" vmap <F2> <Plug>RStart
" R version can be specified like this:
" let vimrplugin_r_path = "/opt/R/3.1.2-release/bin/R"
" Send selection or line to R with space bar, respectively.
vmap <Space> <Plug>RDSendSelection
nmap <Space> <Plug>RDSendLine
" Shortcut for R's assignment operator: 0 turns it off; 1 assigns underscore; 2 assigns two underscores
let R_assign = 2
" Ensures usage of your own ~/.tmux.conf file
let R_notmuxconf = 1
" Shows function arguments in a separate viewport during omni completion with Ctrl-x Ctrl-o:w
let R_show_args = 1
" Use Ctrl-Space to do omnicompletion
inoremap <C-Space> <C-x><C-o>
" Remove white background of status line at bottom of nvim viewport (default is 2)
set laststatus=1
"let R_in_buffer = 0
"let R_tmux_split = 1
"let R_applescript = 0
"let R_tmux_close = 0
" The following provides a zoom functionality, similar to Tmux's Ctrl-a z, by pressing 'gz' in normal mode.
function ZoomWindow()
let cpos = getpos(".")
tabnew %
redraw
call cursor(cpos[1], cpos[2])
normal! zz
endfunction
nmap gz :call ZoomWindow()<CR>
"""""""""""""""""""""
"""NERDTree Plugin"""
"""""""""""""""""""""
" Installation
" - Download NERDTree plugin from here
" http://www.vim.org/scripts/script.php?script_id=1658
" - unzip nerdtree.zip -d ~/.vim
"
" Usage
" - '?' opens quick help
" - 'zz' opens and 'q' closes NERDTree ('zz 'requires setting below)
" - 't' opens file in new tab
" - 'T' opens file in new tab silently
" - 'gt' and 'gT' switch between tabs
" - 'm' opens menu mode for creating/deleting files, 'Ctrl-c' to exit out of this mode
"
" Settings
" Opens NERDTree with custom shortcut, here 'zz'
let mapleader = "z"
nmap <leader>z :NERDTreeToggle<cr>
" Instruct NERDTree to always opens in the current folder
"set autochdir
"let NERDTreeChDirMode=2
"nnoremap <leader>n :NERDTree .<CR>
" Optional to show special NERDTree browser characters properly (e.g. on remote linux system)
let g:NERDTreeDirArrows=0
" Show bookmarks by default
let NERDTreeShowBookmarks=1
"""""""""""""""""""""""
#####################################################
## ~/.tmux.conf - tmux terminal multiplexer config ##
#####################################################
## Save this file to ~/.tmux.conf
# fix for problem that vim sometimes doesn't open in old tmux session
# set -g default-terminal "screen-256color"
# set prefix key to ctrl+a until I have time to adapt
unbind C-b
set -g prefix C-a
# send the prefix to client inside window (ala nested sessions)
bind-key a send-prefix
# toggle last window like screen
bind-key C-a last-window
# confirm before killing a window or the server
bind-key k confirm kill-window
bind-key K confirm kill-server
# toggle statusbar
bind-key b set-option status
# ctrl+left/right cycles thru windows
bind-key -n C-right next
bind-key -n C-left prev
# open a man page in new window
bind / command-prompt "split-window 'exec man %%'"
# quick view of processes
bind '~' split-window "exec htop"
# scrollback buffer n lines
set -g history-limit 5000
# listen for activity on all windows
set -g bell-action any
# on-screen time for display-panes in ms
set -g display-panes-time 2000
# start window indexing at one instead of zero
set -g base-index 1
# enable wm window titles
set -g set-titles on
# wm window title string (uses statusbar variables)
set -g set-titles-string "tmux.#I.#W"
# ThG: set vi mode
set-window-option -g mode-keys vi
# ThG: force a reload of the .tmux.conf file with Ctrl-a r
unbind r
bind r source-file ~/.tmux.conf
# ThG: session initialization
# Start new session with .tmux-conf settings with: tmux attach
# Kill session entirely from a tmux session with: C-a: kill-session
new -n bash
neww -n mutt 'cd ~/; bash'
neww -n git 'cd ~/GoogleDrive/Applications/github/; bash'
neww -n Rwork 'cd ~/Dropbox/Software/; bash'
neww -n Rscript 'cd ~/Manuscripts/planning/; bash'
neww -n latex 'cd ~/Manuscripts/planning/; bash'
neww -n bibtex 'cd ~/Manuscripts/BibTeX/; bash'
neww -n tasks 'cd ~/Tasks/; bash'
select-window -t 2
# Maximizing and restoring panes
unbind +
bind + new-window -d -n tmp \; swap-pane -s tmp.0 \; select-window -t tmp
unbind -
bind - last-window \; swap-pane -s tmp.0 \; kill-window -t tmp
# Status bar 1 tab-based--------------------------------------------------------------
# set -g display-time 3000
#
# # default statusbar colors
# set -g status-fg black # ThG original was: white
# set -g status-bg white
# set -g status-attr default
#
# # default window title colors
# set-window-option -g window-status-fg black
# set-window-option -g window-status-bg white
# set-window-option -g window-status-attr dim
#
# # active window title colors
# set-window-option -g window-status-current-fg white
# set-window-option -g window-status-current-bg black
# set-window-option -g window-status-current-attr dim
#
# # command/message line colors
# set -g message-fg white
# set -g message-bg black
# set -g message-attr bright
#
# # center align the window list
# set -g status-justify left # centre
#
# # show some useful stats but only when tmux is started
# # outside of Xorg, otherwise dwm statusbar shows these already
# # set -g status-right "" # ThG: conflicts with time display
# set -g status-left ""
# if '[ -z "$DISPLAY" ]' 'set -g status-left "[#[fg=green] #H #[default]]"'
# if '[ -z "$DISPLAY" ]' 'set -g status-right "[ #[fg=magenta]#(cat /proc/loadavg | cut -d \" \" -f 1,2,3)#[default] ][ #[fg=cyan,bright]%a %Y-%m-%d %H:%M #[default]]"'
# if '[ -z "$DISPLAY" ]' 'set -g status-right-length 50'
# Status bar 2 non-tab-based cyan color--------------------------------------------------------------
set -g display-time 3000
# default statusbar colors
set -g status-fg cyan # ThG original was: white
set -g status-bg default
set -g status-attr default
# default window title colors
set-window-option -g window-status-fg cyan
set-window-option -g window-status-bg default
set-window-option -g window-status-attr dim
# active window title colors
set-window-option -g window-status-current-fg white
set-window-option -g window-status-current-bg default
set-window-option -g window-status-current-attr bright
# command/message line colors
set -g message-fg white
set -g message-bg black
set -g message-attr bright
# center align the window list
set -g status-justify centre # left
# show some useful stats but only when tmux is started
# outside of Xorg, otherwise dwm statusbar shows these already
# set -g status-right "" # ThG: conflicts with time display
set -g status-left ""
if '[ -z "$DISPLAY" ]' 'set -g status-left "[#[fg=green] #H #[default]]"'
if '[ -z "$DISPLAY" ]' 'set -g status-right "[ #[fg=magenta]#(cat /proc/loadavg | cut -d \" \" -f 1,2,3)#[default] ][ #[fg=cyan,bright]%a %Y-%m-%d %H:%M #[default]]"'
if '[ -z "$DISPLAY" ]' 'set -g status-right-length 50'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment