Configuring nvim with Lua and packer for R

A blogpost on how to configure nvim with Lua to work with R.

Neovim
Linux
R
Lua
packer
Author
Published

June 18, 2023

What are we going to do?

In this blogpost, I will guide you through the process of installing Neovim on Ubuntu 22.04, configuring it with Lua, and using Packer as a plugin manager. Our goal is to create an optimized setup that allows for smooth R programming from the terminal.

If you have previously read my blogposts, you might be familiar with the configuration using vim-plug for managing plugins. However, in this blogpost, we will take a different approach by utilizing Lua for our Neovim configuration and Packer for plugin management. Lua provides a more organized and flexible way to configure Neovim, while Packer simplifies the installation and management of plugins.

Let’s get started with the installation and configuration process. If you are familiar with some of the steps, feel free to jump ahead to the specific sections you need.

By the end of this tutorial, you will have a customized Neovim setup that enhances your R programming experience and boosts your productivity.

Our results will be something similar to:

On next blogposts, I will describe how to take this further.

Installation and configuration

So, we need some software for this. Make sure that you have git installed on your workstation and of course, R.

Files structure

We aim to have the following configuration files structure:

In the directory ~/.config/nvim, we should have:

 | - init.lua (Entry point for nvim)
 |
 | - lua/
    | - plugins.lua (For our packer plugins installations)
    | - settings.lua (Our general nvim configuration)
 |
 | - plugin/
    | - plugin_a.lua (Configurations for a determined plugin)
    | - plugin_b.lua (Configurations for a determined plugin)
    | - packer_compiled.lua (File generated automatically by Packer)

This is not mandatory, but is one of the configurations that I find really nice to organize everything being specific on the aim of the instructions.

Installing Neovim

  1. Open your terminal
  2. Run the following command:
sudo apt install neovim

Configuring our nvim with lua

  1. Create the config directory for nvim:
mkdir /home/user_name/.config/nvim

Remember to replace user_name with your actual workstation user name.

Creating nvim directory in .config
  1. Create the init.lua file:
# Create file
nvim init.lua
  1. Add the following requirements:
# Requirements
require('plugins')
require('settings')

Include the requirements in the init.lua file These requirements reference the files that we are about to create: plugins.lua and settings.lua. Both files should be placed in the lua/ directory.

The init.lua file acts as the entry point for loading the settings and plugins. If you make changes to the plugins, such as adding a new one, you can revisit the init.lua file and invoke :PackerSync to synchronize the plugins. However, for now, you don’t need to worry about this step.

Configuring General Settings for Lua

After creating our init.lua file, it’s time to configure the general settings to customize the behavior of the nvim editor according to our preferred style.

To organize these settings effectively, we will utilize the lua/settings.lua file. This file will serve as a central location for all our general settings.

To set up the lua/settings.lua file, follow these steps:

  1. Create the lua/ directory inside the nvim/ directory if it doesn’t already exist:
mkdir lua
  1. Create the settings.lua file within the lua/ directory.
nvim lua/settings.lua

Make sure that the file name matches the one specified in your init.lua file’s requirements.

When doing the step above, probably you will find an error:

Error message when modifyng the settings.lua file

Since we are currently in the process of creating the required files, it’s normal to encounter an error when Neovim tries to locate the non-existent files. However, this is not a cause for concern for now.

Consider adding the following basic configuration options to the settings.lua file:

vim.opt.number = true
vim.opt.relativenumber = true
vim.opt.ignorecase = true
vim.opt.smartcase = true
vim.opt.breakindent = true
vim.opt.tabstop = 4
vim.opt.shiftwidth = 4
vim.opt.colorcolumn = "80"

Settings for nvim in the file settings.lua

These configurations will enable line numbers, relative line numbers, case-insensitive searching, smart case sensitivity, indentation on line breaks, set the tab width to 4 spaces, set the indent width to 4 spaces, and display a color column at column 80.

Feel free to adjust these settings according to your preferences.

Installing packer

To install Packer, a plugin manager for Neovim, follow these steps:

  1. Create the plugins.lua file inside the lua folder
nvim lua/plugins.lua

Again, you will find the same warning as above, but just hit enter.

  1. Copy and paste the following code into the file. This code checks if Packer is already installed and, if not, it installs it automatically when you start Neovim.
 local ensure_packer = function()
  local fn = vim.fn
  local install_path = fn.stdpath('data')..'/site/pack/packer/start/packer.nvim'
  if fn.empty(fn.glob(install_path)) > 0 then
    fn.system({'git', 'clone', '--depth', '1', 'https://github.com/wbthomason/packer.nvim', install_path})
    vim.cmd [[packadd packer.nvim]]
    return true
  end
  return false
end

local packer_bootstrap = ensure_packer()

Packer code snippet for installation

With these code snippets in place, whenever you start Neovim, it will automatically check if Packer is installed. If it’s not found, it will be cloned from the official repository and set up for use.

Don’t close the file yet! We are going to add a couple of things more in the next section.

Installing plugins

Now you can proceed with adding the desired plugins to the lua/plugins.lua file. Here we are going to add a couple, with special attention to Nvim-R.

  1. Open the lua/plugins.lua file in your preferred text editor.

  2. Inside the require(‘packer’).startup(function() block, you can add the plugins you want to install. For example, let’s add two plugins: gruvbox for a colorscheme and Nvim-R for R integration. Modify your lua/plugins.lua file as follows:

return require('packer').startup(function()
        -- packer can manage itself
        use 'wbthomason/packer.nvim'

        -- colorscheme
        use 'gruvbox-community/gruvbox'
        
        -- nvim-r
        use 'jalvesaq/Nvim-R'

end)
  1. Save the changes to your lua/plugins.lua file.

After adding the plugins, you can go back to your init.lua file and check if everything is correct. To install and update all the plugins, run the following command inside Neovim:

:PackerSync

This will trigger the installation and updating of your plugins.

Once the process is complete, you can quit Neovim by running :q in the Packer window and :q in the init.lua file.

Now, your plugins should be successfully installed and ready to use in Neovim.

Configure settings for Nvim-R

At this point you should have the following structure:

File structure for our settings

For this, we need to create a file with the name of the plugin. We are going to configure a couple of settings for our nvim-r plugin.

  1. Navigate to the plugin/ folder in your Neovim configuration directory.
  2. Create a new file called nvimr.lua inside the plugin/ folder.
  3. Open the nvimr.lua file and add the following configurations:
-- To use spacebar for running code
vim.cmd([[
  let g:markdown_fenced_languages = ['r', 'python']
  let g:rmd_fenced_languages = ['r', 'python']

  if has("gui_running")
      inoremap <C-Space> <C-x><C-o>
  else
      inoremap <Nul> <C-x><C-o>
  endif
  vmap <Space> <Plug>RDSendSelection
  nmap <Space> <Plug>RDSendLine
]])


-- R filetypes
vim.cmd([[
autocmd BufNewFile,BufRead *.Rmd set ft=rmd
autocmd BufNewFile,BufRead *.rmd set ft=rmd
autocmd BufNewFile,BufRead *.qmd set ft=rmd
]])

The above configurations will:

  • Set the fenced code block languages to ‘r’ and ‘python’ for R Markdown and quarto files.
  • Enable the space bar as a shortcut for running lines of code.
  • Set the key mapping <Space> for visual mode to send the selected lines to the R terminal.
  • Set the key mapping <Space> for normal mode to send the current line to the R terminal.
  • Set the filetypes to rmd for .Rmd, .rmd, and .qmd files.

Save the changes to the nvimr.lua file.

With these settings in place, Nvim-R will be configured to enhance your workflow with .rmd and .qmd files, providing a convenient way to run R code within Neovim.

Testing

Now that we have everything installed, let’s test if we can work with R from our terminal using Neovim.

  1. Create a test .rmd file on your desktop. You can use the following command:
nvim test.rmd
  1. In the test.rmd file, let’s start with a simple function. Add a similar function:

Creating a test.rmd file
  1. To open the R console, press \rf:

Opening R console with nvim-r
  1. Place your cursor in any line inside the chunk of the code and press the spacebar to send the line to the R console:

Running the R code!

With all these steps, you just tested the integration of R with nvim. You can now continue to explore and utilize the features provided by Nvim-R to enhance your R coding experience within Neovim.

Workflow

Now that we hace everything setup, is time to work with R from nvim. Check this other tutorial with some of the most common and useful key bindings.

Reuse

Citation

BibTeX citation:
@online{a. hernandez mora2023,
  author = {A. Hernandez Mora, Ronny},
  title = {Configuring Nvim with {Lua} and Packer for {R}},
  date = {2023-06-18},
  url = {https://profound-caramel-d8abb6.netlify.app/posts/2023-06-17-nvim_lua_packer},
  langid = {en}
}
For attribution, please cite this work as:
A. Hernandez Mora, Ronny. 2023. “Configuring Nvim with Lua and Packer for R.” June 18, 2023. https://profound-caramel-d8abb6.netlify.app/posts/2023-06-17-nvim_lua_packer.