Git Product home page Git Product logo

r.nvim's Introduction

Selene linter check

R.nvim

This is the development code of R.nvim which improves Neovim's support to edit R scripts.

Installation

If you use a plugin manager, follow its instructions on how to install plugins from GitHub. Users of lazy.nvim who opted for defaults.lazy=true have to configure R.nvim with lazy=false. Examples of configuration for lazy.nvim (see also cmp-r):

Minimal configuration:

  {
    "R-nvim/R.nvim",
    lazy = false
  },
  {
    "nvim-treesitter/nvim-treesitter",
    run = ":TSUpdate",
    config = function ()
      require("nvim-treesitter.configs").setup({
        ensure_installed = { "markdown", "markdown_inline", "r", "rnoweb" },
      })
    end
  },
  "R-nvim/cmp-r",
  {
    "hrsh7th/nvim-cmp",
    config = function()
      require("cmp").setup({ sources = {{ name = "cmp_r" }}})
      require("cmp_r").setup({ })
    end,
  },

More complex configuration (for R.nvim only):

    {
        "R-nvim/R.nvim",
        config = function ()
            -- Create a table with the options to be passed to setup()
            local opts = {
                R_args = {"--quiet", "--no-save"},
                hook = {
                    on_filetype = function ()
                        -- This function will be called at the FileType event
                        -- of files supported by R.nvim. This is an
                        -- opportunity to create mappings local to buffers.
                        vim.api.nvim_buf_set_keymap(0, "n", "<Enter>", "<Plug>RDSendLine", {})
                        vim.api.nvim_buf_set_keymap(0, "v", "<Enter>", "<Plug>RSendSelection", {})
                    end
                },
                min_editor_width = 72,
                rconsole_width = 78,
                disable_cmds = {
                        "RClearConsole",
                        "RCustomStart",
                        "RSPlot",
                        "RSaveClose",
                    },
                }
                -- Check if the environment variable "R_AUTO_START" exists.
                -- If using fish shell, you could put in your config.fish:
                -- alias r "R_AUTO_START=true nvim"
                if vim.env.R_AUTO_START == "true" then
                    opts.auto_start = 1
                    opts.objbr_auto_start = true
                end
                require("r").setup(opts)
            end,
        lazy = false
    },

The complete list of options is in the documentation. See also the Wiki.

Usage

Please read the plugin's documentation for instructions on usage. See also the output of :RMapsDesc.

Transitioning from Nvim-R

Changes

During the conversion of VimScript to Lua, we decided to end support for features that were useful in the past but no longer sufficiently valuable to be worth the effort of conversion. We removed support for Rrst (it seems that not many people use it anymore), debugging code (a debug adapter would be better), legacy omni-completion (auto completion with nvim-cmp is better), and highlighting functions from .GlobalEnv (difficult to make compatible with tree-sitter + LSP highlighting).

We changed the default key binding to insert the assignment operator (<-) from an underscore (which was familiar to Emacs-ESS users) to Alt+- which is more convenient (but does not work on Vim). See the option assignment_keymap.

We replaced the options R_source and after_R_start with some more specific hooks and we can insert other hooks for Lua functions at other parts of the code under user request.

We added a keybinding for the pipe operator (|>). This defaults to <LocalLeader>, and is configurable with the option pipe_keymap.

We added awareness of .Rproj files (the project-level configuration files used by RStudio). This may, for example, change whether pipe_keymap inserts |> or %>% for a particular project. See the option rproj_prioritise for a full list of the behaviours which may be affected by .Rproj files, or to change whether they should affect things at all.

We removed the "echo" parameters from the functions that send code to R Console. Users can still set the value of source_args to define the arguments that will be passed to base::source() and include the argument echo=TRUE. Now, there is a new option to define how many lines can be sent directly to the R Console without saving the code in a temporary file to be sourced (max_lines_to_paste).

The options for displaying R documentation (nvimpager) are now: "split_h", "split_v", "tab", "float" (not implemented yet), and "no".

The options openpdf and openhtml were renamed as open_pdf and open_html, they now are strings and there with a minor change in how they behave.

The option nvim_wd was renamed as setwd and it now is a string and its default value is "no".

The option notmuxconf was renamed as config_tmux to avoid the negation of the negation notmuxconf=false or the even more awkward confirmation of the negation notmuxconf=true. The default value of config_tmux is true.

New features

There are two new commands:

  • :RMapsDesc displays the list of key bindings followed by short descriptions.

  • :RConfigShow displays the list of configuration options and their current values.

There is one new command to send the above-piped chain of commands. Its default key binding is <LocalLeader>sc.

There is a new option: auto_quit.

If you have colorout installed, and if you are not loading it in your ~/.Rprofile, it should be the development version. Reason: R.nvim calls the function colorout::isColorOut() which unduly enables the colorizing of output in the released version of colorout. This bug was fixed in this commit.

There are two new commands available to separate a file path into its different components.

The first command, sp, will take the file path under the cursor and break it down into its components, then surround it with the paste() function.

The second command, sh, will also break down the file path under the cursor into its components, but instead surround it with the here() function.

It's important to note that both functions require the nvim-treesitter plugin to be installed.

For example, if you have the following file path under the cursor:

read.csv("/home/user/Documents/file.csv")

Running the sp command will transform it into:

read.csv(paste("/home", "user", "Documents", "file.csv", sep = "/"))

Screenshots and videos

None yet. Tell us if you published a video presenting R.nvim features.

The communication between Neovim and R

The diagram below shows how the communication between Neovim and R works. Neovim-R communication

The black arrows represent all commands that you trigger in the editor and that you can see being pasted into R Console. There are three different ways of sending the commands to R Console:

  • When running R in a Neovim built-in terminal, the function chansend() is used to send code to R Console.

  • When running R in an external terminal emulator, Tmux is used to send commands to R Console.

  • On the Windows operating system, if using the Rgui.exe as "external terminal", Nvim-R can send a message to R (nvimcom) which forwards the command to R Console.

The R package nvimcom includes the application rnvimserver which is never used by R itself but is run as a Neovim's job. That is, the communication between the rnvimserver and Neovim is through the rnvimserver standard input and output (green arrows). The rnvimserver application runs a TCP server. When nvimcom is loaded, it immediately starts a TCP client that connects to rnvimserver (red arrows).

Some commands that you trigger are not pasted into R Console and do not output anything in the R Console; their results are seen in the editor itself. These are the commands to do auto completion (of names of objects and function arguments), start and manipulate the Object Browser (\ro, \r= and \r-), call R help (\rh or :Rhelp), insert the output of an R command (:Rinsert), and format selected text (:Rformat).

When new objects are created or new libraries are loaded, nvimcom sends messages that tell the editor to update the Object Browser, update the syntax highlight to include newly loaded libraries and open the PDF output after knitting an Rnoweb file, and compiling the LaTeX result. Most of the information is transmitted through the TCP connection to the rnvimserver, but temporary files are used in a few cases.

See also:

r.nvim's People

Contributors

akthe-at avatar ben10164 avatar cswingle avatar hongyuanjia avatar j-w-e avatar jalvesaq avatar liubianshi avatar mikemc avatar pmassicotte avatar she3o avatar smb5 avatar wklimowicz avatar wurli avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

r.nvim's Issues

:RSend command is broken

Trying to execute an :Rsend command produces the following error

Error  03:43:24 PM msg_show.lua_error   RSend help() Error executing Lua callback: /home/frank/.local/share/nvim/lazy/R.nvim/lua/r/term.lua:25: attempt to concatenate local 'command' (a table value)
stack traceback:
	/home/frank/.local/share/nvim/lazy/R.nvim/lua/r/term.lua:25: in function 'cmd'
	/home/frank/.local/share/nvim/lazy/R.nvim/lua/r/config.lua:733: in function </home/frank/.local/share/nvim/lazy/R.nvim/lua/r/config.lua:733>

nvimcom sends a string that is invalid for Lua

When we do <LocalLeader>rf over the word function, nvimcom sends a string that is invalid for Lua: it contains a backslash before a parenthesis. The simple workaround would be to escape the backslash before sending the help text to R.nvim. However, the more appropriate fix is to escape all strings sent to R.nvim in a standard way. There is a function for this (nvim.fix.string() at R.nvim/nvimcom/R/bol.R), but it was developed to escape strings for VimScript, not for Lua, and, before trying to further adjust it to Lua, I would like to know what are @she3o ideas on the C-Lua interface:

  • Is the plan to convert the whole C code to Lua or to turn rnvimserver into a C library for our Lua code?

  • What would be the advantages over the current approach of running rnvimserver as a Neovim job?

Currently, if rnvimserver crashes, R.nvim stops working, but Neovim doesn't crash. As far as I know, if rnvimserver were a C library, a fatal error in its code would crash Neovim. This would be a disadvantage of rnvimserver as a C library. Another disadvantage would be the dependency on Lua headers for compilation, but this is easily solved by including the Lua headers in the R.nvim directory.

If we converted the whole C code to Lua, this would result in a loss of performance because in C we have total control of memory management and direct access to string arrays.

In summary:

C application: better at processing data, but slower transferring information to R.nvim.

Lua only: slower at processing data, but no need to transfer data.

C library: better at processing data and fast transferring data.

From the above comparison, considering that there are no reports of the nvimrserver crashing, the most advantageous approach for R.nvim seems to be the conversion of rnvimserver into a C library for our Lua code. However, considering that the current approach of running rnvimserver as a job is already pretty fast, it might be better to leave it as is and simply fix the nvim.fix.string() function.

Add support for executing SQL chunks

Hi!

I have been digging through the documentation in order to understand how to use R.nvim to execute SQL chunks, without success. Is this something you already support or would consider adding support for (I might have missed something here).

My motivation is that I love expressing the initial data transformation in the form of SQL chunks, which are then post-processed in the tidyverse ecosystem before being plotted in ggplot. It looks something like this:

```{r}
library(DBI)
db = dbConnect(RSQLite::SQLite(), dbname = "sql.sqlite")
```

```{sql, output.var="trials", connection=db}
SELECT * FROM trials
```

```{r}
trials %>% as_tibble() %>% ggplot(...) + ...

Thanks in advance!

  • Jakob

PS: Thanks for the great plugin! I used Nvim-R extensively during 2018 and 2019, and I'm happy to return to this ecosystem seeing that things have been keeping up to date with Neovim's migration to lua-based plugins ๐Ÿ™‡

Is `after_R_start()` broken in `hook`?

When I attempt to set this in any way I get an error:

Client 1 quit with exit code 1 and signal 0

The rest of the package works fine after this, but nothing I put in after_R_start() gets run. This happens with even the basic configuration example from the docs:

hook = {
    after_config = function() vim.notify("R.nvim is configured") end,
    after_R_start = function() vim.notify("R was launched") end,
    after_ob_open = nil,
},

set up assign map to mimic ESS behaviour

In ESS, _ converts to <- (the assignment operator) while using _ in quick succession (i.e. __) switches it back to _. This is a throwback to the old days (before R 1.6) when _ was allowed as an assignment operator. Is it possible to get this behaviour with nvim-R?

[FR] Create a config to turn on autoreplacement of magrittr pipe with native pipe

This is a feature request.

I'm in the process of migrating all my pipe usage from the magrittr %>% pipe to the R native |> pipe. But old habits truly die hard and I find my self mixing the two pipes all the time in my script. As a result, I have to do global replacement often. I'm wondering if it's possible to enable some kind of auto-replacement of %>% to |> in real time when typing. There can be a setting which turns on and off this behavior.

Congrats on the new launch and thanks for all the hard work over many years!

`vim.system()` api did not exist in Neovim current release (v0.9.5)

Thank you all for your efforts! Currently, I failed to use R.nvim on the current Neovim release. (v0.9.5). vim.system() Lua API was added in PR neovim/neovim#23827, which was before when Neovim v0.9.5 was released. However, somehow, it was not included in the current Neovim release. Since vim.system() was a wrapper around vim.loop.spawn(), maybe we can use the latter directly? Or at least note that R.nvim only works for the development version of Neovim.

Error detected while processing BufReadPost Autocommands for "*":
Error executing lua callback: ...coop/apps/neovim/current/share/nvim/runtime/filetype.lua:24: Error executing lua: ...coop/apps/neovim/current/share/nvim/runt
ime/filetype.lua:25: BufReadPost Autocommands for "*"..FileType Autocommands for "*"..function <SNR>1_LoadFTPlugin[19]..script C:\Users\hongyuanjia\AppData\Lo
cal\nvim-data\lazy\tmp-R-nvim\ftplugin\r_rnvim.lua: Vim(runtime):E5113: Error while calling lua chunk: ...AppData/Local/nvim-data/lazy/tmp-R-nvim/lua/r/config
.lua:543: attempt to call field 'system' (a nil value)
stack traceback:
        ...AppData/Local/nvim-data/lazy/tmp-R-nvim/lua/r/config.lua:543: in function 'get_rip'
        ...AppData/Local/nvim-data/lazy/tmp-R-nvim/lua/r/config.lua:553: in function 'windows_config'
        ...AppData/Local/nvim-data/lazy/tmp-R-nvim/lua/r/config.lua:698: in function 'global_setup'
        ...AppData/Local/nvim-data/lazy/tmp-R-nvim/lua/r/config.lua:799: in function 'real_setup'
        ...ata/Local/nvim-data/lazy/tmp-R-nvim/ftplugin/r_rnvim.lua:12: in main chunk
        [C]: in function 'nvim_cmd'
        ...coop/apps/neovim/current/share/nvim/runtime/filetype.lua:25: in function <...coop/apps/neovim/current/share/nvim/runtime/filetype.lua:24>
        [C]: in function 'nvim_buf_call'
        ...coop/apps/neovim/current/share/nvim/runtime/filetype.lua:24: in function <...coop/apps/neovim/current/share/nvim/runtime/filetype.lua:10>
stack traceback:
        [C]: in function 'nvim_cmd'
        ...coop/apps/neovim/current/share/nvim/runtime/filetype.lua:25: in function <...coop/apps/neovim/current/share/nvim/runtime/filetype.lua:24>
        [C]: in function 'nvim_buf_call'
        ...coop/apps/neovim/current/share/nvim/runtime/filetype.lua:24: in function <...coop/apps/neovim/current/share/nvim/runtime/filetype.lua:10>
stack traceback:
        [C]: in function 'nvim_buf_call'
        ...coop/apps/neovim/current/share/nvim/runtime/filetype.lua:24: in function <...coop/apps/neovim/current/share/nvim/runtime/filetype.lua:10>
Press ENTER or type command to continue

Neovim version:

:version
NVIM v0.9.5
Build type: RelWithDebInfo
LuaJIT 2.1.1703942320
Compilation: C:/Program Files (x86)/Microsoft Visual Studio/2019/Enterprise/VC/Tools/MSVC/14.29.30133/bin/Hostx64/x64/cl.exe /MD /Zi /O2 /Ob1  -W3 -wd4311 -wd
4146 -DUNIT_TESTING -D_CRT_SECURE_NO_WARNINGS -D_CRT_NONSTDC_NO_DEPRECATE -D_WIN32_WINNT=0x0602 -DMSWIN -DINCLUDE_GENERATED_DECLARATIONS -ID:/a/neovim/neovim/
.deps/usr/include/luajit-2.1 -ID:/a/neovim/neovim/.deps/usr/include -ID:/a/neovim/neovim/.deps/usr/include -ID:/a/neovim/neovim/build/src/nvim/auto -ID:/a/neo
vim/neovim/build/include -ID:/a/neovim/neovim/build/cmake.config -ID:/a/neovim/neovim/src -ID:/a/neovim/neovim/.deps/usr/include -ID:/a/neovim/neovim/.deps/us
r/include -ID:/a/neovim/neovim/.deps/usr/include -ID:/a/neovim/neovim/.deps/usr/include -ID:/a/neovim/neovim/.deps/usr/include -ID:/a/neovim/neovim/.deps/usr/
include -ID:/a/neovim/neovim/.deps/usr/include

   system vimrc file: "$VIM\sysinit.vim"
  fall-back for $VIM: "C:/Program Files (x86)/nvim/share/nvim"

Run :checkhealth for more info

lots of error out on assigned function call and entering arguments into functions as nvim info (notification)

Error obtained from calling an assigned function.
Error executing vim.schedule lua callback: /.local/share/nvim/lazy/cmp-r/lua/cmp_r/init.lua:208: attempt to call upvalue 'send_to_nvimcom' (a nil value)
stack traceback:
.local/share/nvim/lazy/cmp-r/lua/cmp_r/init.lua:208: in function 'resolve'
...mtrek/.local/share/nvim/lazy/nvim-cmp/lua/cmp/source.lua:384: in function 'resolve'
./.local/share/nvim/lazy/nvim-cmp/lua/cmp/entry.lua:495: in function 'resolve'
/.local/share/nvim/lazy/nvim-cmp/lua/cmp/view.lua:287: in function 'fn'
.../.local/share/nvim/lazy/nvim-cmp/lua/cmp/utils/async.lua:71: in function <.../.local/share/nvim/lazy/nvim-cmp/lua/cmp/utils/async.lua:69>

Error obtained on entering arguments to an assigned function
Error detected while processing TextChangedI Autocommands for "*":

The functions work as they ought to, but the frequent error output can be a sort of "distraction", is there a way in which it can be muted?

Better `auto_start` option?

Currently, auto_start options are 0, 1, and 2, but users will only know what these numbers mean if they remember what is in the documentation. So would it be better to change the option type from number to string? If yes, what about "no", "on startup", and "always" as valid values?

Latest commits breaks Windows Build of Nvimcom

OS: Windows 10
commit: a5f8666
branch: main

Problem seems to be with this commit here

Attempts to fix: change setenv to getenv, doesn't work if you keep the arguments as is...fails with warning about too many arguments. If you you remove the extra arguments besides the environment variable string, the build works.
But that fix doesn't make sense based on a quick google search of setenv and the arguments you provided in the above commit.

Going to paste in my error message.

* preparing 'nvimcom':
* checking DESCRIPTION meta-information ...
 OK
* cleaning src
* checking for LF line-endings in source and make files and shell scripts
* checking for empty or unneeded directories
* building 'nvimcom_0.9.35.tar.gz'
gcc  -I"C:/Users/ARK010/AppData/Local/Programs/R/R-4.3.1/include" -DNDEBUG     -I"C:/rtools43/x86_64-w64-mingw32.static.posix/include"  -D`C:/Users/ARK010/AppData/Local/Programs/R/R-4.3.1/bin/R --slave -e 'cat(Sy
s.info()[[1]])'` -DLWS_NO_FORK  -DWIN32   -O2 -Wall  -mfpmath=sse -msse2 -mstackrealign  -c common.c -o common.o
gcc  -I"C:/Users/ARK010/AppData/Local/Programs/R/R-4.3.1/include" -DNDEBUG     -I"C:/rtools43/x86_64-w64-mingw32.static.posix/include"  -D`C:/Users/ARK010/AppData/Local/Programs/R/R-4.3.1/bin/R --slave -e 'cat(Sy
s.info()[[1]])'` -DLWS_NO_FORK  -DWIN32   -O2 -Wall  -mfpmath=sse -msse2 -mstackrealign  -c nvimcom.c -o nvimcom.o
gcc  -I"C:/Users/ARK010/AppData/Local/Programs/R/R-4.3.1/include" -DNDEBUG     -I"C:/rtools43/x86_64-w64-mingw32.static.posix/include"  -D`C:/Users/ARK010/AppData/Local/Programs/R/R-4.3.1/bin/R --slave -e 'cat(Sy
s.info()[[1]])'` -DLWS_NO_FORK  -DWIN32   -O2 -Wall  -mfpmath=sse -msse2 -mstackrealign  -c rd2md.c -o rd2md.o
gcc -shared -s -static-libgcc -o nvimcom.dll tmp.def common.o nvimcom.o rd2md.o -lWs2_32 -LC:/rtools43/x86_64-w64-mingw32.static.posix/lib/x64 -LC:/rtools43/x86_64-w64-mingw32.static.posix/lib -LC:/Users/ARK010/A
ppData/Local/Programs/R/R-4.3.1/bin/x64 -lR
(cd apps; make -f Makefile.win)
make[1]: Entering directory '/c/Users/ARK010/AppData/Local/Temp/RtmpyagKBD/R.INSTALL1ea02f8e5b26/nvimcom/src/apps'gcc -mwindows -std=gnu99 -O3 -Wall -DWIN32 -m64 complete.c data_structures.c logging.c rnvimserver
.c obbr.c rgui.c tcp.c utilities.c ../common.c -o rnvimserver.exe -lWs2_32
make[1]: Leaving directory '/c/Users/ARK010/AppData/Local/Temp/RtmpyagKBD/R.INSTALL1ea02f8e5b26/nvimcom/src/apps'

Why build nvimcom: nvimcom version mismatch
Time:
  windows setup: 0.2154036
  before_rns.R: 18.1124079
  global setup: 0.2318926
before_rns.R stderr:
.build_packages() exit status 0
* installing to library 'C:/Users/ARK010/AppData/Local/Programs/R/R-4.3.1/library'
* installing *source* package 'nvimcom' ...
** using staged installation
** libs
using C compiler: 'gcc.exe (GCC) 12.3.0'
rnvimserver.c: In function 'stdin_loop':rnvimserver.c:158:17: warning: implicit declaration of function 'setenv'; did you mean 'getenv'? [-Wimplicit-function-declaration]  158 |                 setenv("CMPR_DOC_W
IDTH", msg, 1);      |                 ^~~~~~      |                 getenv
C:\rtools43\x86_64-w64-mingw32.static.posix\bin/ld.exe: C:\Users\ARK010\AppData\Local\Temp\
cczb0t3b.o:rnvimserver.c:(.text+0x400): undefined reference to `
sete
nv'
collect2.exe: error: ld returned 1 exit status
make[1]: *** [Makefile.win:17: rnvimserver.exe] Error 1
make: *** [Makevars.win:11: nvimapps] Error 2
ERROR: compilation failed for package 'nvimcom'
* removing 'C:/Users/ARK010/AppData/Local/Programs/R/R-4.3.1/library/nvimcom'
* restoring previous 'C:/Users/ARK010/AppData/Local/Programs/R/R-4.3.1/library/nvimcom'
Error in do_exit(status = status) : .install_packages() exit status 1
* removing 'C:/Users/ARK010/AppData/Local/Programs/R/R-4.3.1/library/nvimcom'
Error in do_exit(status = status) : .install_packages() exit status 1
Execution halted

Can not get R running with NvChad/Windows 11 configuration

I installed the plugin to work with NvChad, but when I open an R file, it reads:

Could not find R path in Windows Registry. If you have already installed R, please, set the value of 'R_path'.
R_app executable not found: 'Rterm.exe'

When I went on to try to start R program (\rf), the R window opened for less than half a second, and then instantly closed. The following message appeared in the status bar:

[Server] "Neovim" window not found
"R" exited with status 1

So I thought if the nvimcom package is correctly installed, so I ran :RDebugInfo, the following reading appears: (I have no idea how to copy these messages I'm noob) Does this mean the package has been installed?

RDebugInfo

I tried to add R_path in the system PATH and init.lua, but the error messages remain.

Then I tried to edit R_path in config.lua; this time, the R_path and Rterm.exe messages disappeared, but it still said "Neovim" window not found. I tried \aa and \l, but it only returned a message Did you start R?. I would highly appreciate some help.

Additional info: I'm using Windows 11, and the neovim is run in CMD. I also tried Powershell, but that did not work either.

Cannot get active window info

I get the following error (please ignore the headlines.nvim error, still figuring that one out) whenever I open a Quarto document. Never happens with R scripts. As far as I can see, it doesn't impact functionality.

Cannot get active window info on your system.
Please, do a pull request fixing the problem.
See: R.nvim/lua/r/utils.lua

Would still like to know what the problem is and how I can fix it.

grim-06-03-2024-06-26-47

Status line indicator

Not an issue; just sharing my status line configuration, which includes an R-Nvim indicator. We can improve it and add the code as a suggestion for configuration to the Wiki...

    {
        "nvim-lualine/lualine.nvim",
        config = function()
            local function macro_recording()
                local reg = vim.fn.reg_recording()
                if reg == "" then
                    return ""
                end
                return "[" .. reg .. "]"
            end

            local rstt =
            {
                { "-", "#aaaaaa" }, -- 1: ftplugin/* sourced, but nclientserver not started yet.
                { "S", "#757755" }, -- 2: nclientserver started, but not ready yet.
                { "S", "#117711" }, -- 3: nclientserver is ready.
                { "S", "#ff8833" }, -- 4: nclientserver started the TCP server
                { "S", "#3388ff" }, -- 5: TCP server is ready
                { "R", "#ff8833" }, -- 6: R started, but nvimcom was not loaded yet.
                { "R", "#3388ff" }, -- 7: nvimcom is loaded.
            }

            local rstatus = function ()
                if not vim.g.R_Nvim_status or vim.g.R_Nvim_status == 0 then
                    -- No R file type (R, Quarto, Rmd, Rhelp) opened yet
                    return ""
                end
                return rstt[vim.g.R_Nvim_status][1]
            end

            local rsttcolor = function ()
                if not vim.g.R_Nvim_status or vim.g.R_Nvim_status == 0 then
                    -- No R file type (R, Quarto, Rmd, Rhelp) opened yet
                    return { fg = "#000000" }
                end
                return { fg = rstt[vim.g.R_Nvim_status][2] }
            end

            local selectionCount = function ()
                local m = vim.fn.mode()
                if m == "v" or m == "V" then
                    local c = vim.fn.wordcount()
                    return tostring(c.visual_words) .. " Words, " .. tostring(c.visual_chars) .. " Chars"
                end
                return ""
            end

            require("lualine").setup({
                options = {
                    section_separators = "",
                    component_separators = "",
                    globalstatus = true,
                },
                sections = {
                    lualine_a = { "mode", macro_recording },
                    lualine_b = { {'FugitiveHead', icon = '๎‚ '}, "diagnostics" },
                    lualine_c = { "filename", "searchcount",  },
                    lualine_x = { selectionCount },
                    lualine_y = { {rstatus, color = rsttcolor }},
                    lualine_z = { "progress", "location" },
                },
                -- extensions = { "nvim-tree" },
            })
        end,
    },

Escaping single quotes when sending to R console

When sending code to the R console (on tmux), all single quotes appear to be escaped and come back with error. There is no problem when there are no single quotes, or when there are double quotes.

For example:
library(tidyr) runs fine,
library("tidyr") runs fine,
library('tidyr') leads to

> library('\\''tidyr'\\'')
Error: unexpected string constant in "library('\\''tidyr'"

sending function to the R console

I dont know if sending function to the R console has been implemented, I am having difficulty in sending functions to the R console, it is always returning error, and the functions do not work. I have tried all the new key combinations none of which is working for now, unless I want to source the whole file, which I have no plan of doing for now, as I have to test the functions make sure they are working.

Remove support for debugging R functions?

This is a feature that I don't use, and it certainly would be better to have a nvim-dap-r. These are reasons to remove the current support for debugging functions. But I don't know if anyone is going to develop the nvim-dap-r and this is a reason to convert the current VimScript code to Lua.

@she3o ? @PMassicotte ? What do you think?

Unable to use \d or \l to run lines of code that have been newly added to a .R file.

When opening an R file and starting R.nvim, I can run all lines of code in my file using \d or \l with no issues.

When I add new lines to my code, \d and \l stop working. However, I can still run lines using \ss.

Using \d or \l causes the following error:

E5108: Error executing lua ~/.vim/plugged/R.nvim/lua/r/send.lua:95: attempt to index local 'n' (a nil value)                                                                                                              
stack traceback:
      ~/.vim/plugged/R.nvim/lua/r/send.lua:95: in function 'is_root'
      ~/.vim/plugged/R.nvim/lua/r/send.lua:99: in function 'get_code_to_send'
      ~/.vim/plugged/R.nvim/lua/r/send.lua:566: in function 'line'
      [string ":lua"]:1: in main chunk

I need to save the file and restart neovim to get \d and \l to work again.

No suggestion through nvim-cmp

I will like to know if suggestions through nvim-cmp-r has been implemented? suggestions of variables, functions and others are not been shown for now, cmpstatus shows that nvim-cmp-r is active in r documents

Names of commands are inconsistent

All our commands start with the upper case letter "R", but some have the second letter in upper case while others have it in lower case:

RBuildTags
RConfigShow
RDebugInfo
RFormat
RInsert
RKill
RMapsDesc
RSend
RSourceDir

and

Rhelp
Rstop

So, maybe the latter two should be RHelp and RStop, although RHelp seems strange to me because the R command is help(), with a lowercase "H".

Unrecognized option "editing_mode"

I get the following error message if I set editing_mode = "vi" as an option

Warn 06:17:26 PM notify.warn R.nvim Unrecognized option 'editing_mode'.

Lazy.nvim config

return {
  "R-nvim/R.nvim",
  lazy = false,
  opts = {
    editing_mode = "vi",
  },
}

inputrc

set editing-mode vi
set show-mode-in-prompt on
set vi-cmd-mode-string \1\e[2 q\2(c)
set vi-ins-mode-string \1\e[5 q\2(i)

$if R
    set bell-style none
$else
    set bell-style audible
$endif

R, hooks; scripts, nvimcom

I'm thinking about renaming some directories and moving some files from one directory to another:

Move nvimcom to the root of R.nvim, so, we have to type less when accessing it.

Rename R as scripts as common in many other plugins.

Move hooks/pre_comit to scripts.

Delete hooks.

What do you think, @PMassicotte and @she3o? Any objections or better ideas?

What should change in R.nvim when compared with Nvim-R?

This is the best moment to introduce changes in R.nvim that will break some habits of Nvim-R users.

We have already:

  • Removed support for Rrst, debugging code, legacy omni-completion, and highlighting functions from .GlobalEnv.

  • Changed how RAssign() works.

  • Replaced options R_source and after_R_start with hook.

  • Remove the "echo" argument from functions sending code to R.

  • Simplify how Rhelp windows are open.

We still could:

  • Decrease the number of maps created by default. The options disable_cmds, hook.after_config, and user_maps_only already makes maps creation flexible enough.

Did I forget to mention something? Any other ideas?

Paste vs bracketed paste vs source; echo vs silent.

In the past, when sending multiple lines to RConsole, if the total number of bytes was over 4 Kb, the text was incompletely pasted by Tmux (required to run R in an external terminal on Unix). To test if the problem persists, I converted a PDF book to txt and then converted each line into a cat():

%s/\(.*\)/cat("\1\\n")/

The result was a file with 500 Kb.

There was no problem sending all the lines concatenated with "\n" directly to R if it was running in Neovim's built-in terminal. Also, there was no problem sending the code to Tmux.

However, a bracketed paste didn't work with Neovim's built-in terminal or Tmux.

Considering these results we may consider that we no longer need to source multiple lines if running R on a local Linux system. However, it is prudent to keep the option to source code at least in some circumstances, for example, when running R in a remote machine. We also have to keep the bracketed paste option for Python code in Quarto documents.

Although it's possible, I can't see any usefulness of pasting hundreds of lines on the R Console since the code will scroll up and be out of sight anyway. So, I'm trying to figure out what should be the default behavior. Perhaps: Paste the code directly if the number of lines is below max_lines_to_paste; otherwise, source it.

Another problem is the number of key bindings created by default: four for each source operation, combining "echo" and "movement". I think we can get rid at least of the "echo" option because echo=TRUE can be added to source_args.

@PMassicotte , @she3o, any suggestions?

Replacement for cmp-nvim-r

R-Nvim will rely on cmp-r for auto-completion, but we can use the branch rnvim of `cmp-nvim-r' while we don't create the R-Nvim organization.

R.nvim won't use user tmux configuration

When the R console is started using an external terminal (external_term = true), when using notmuxconf = true, tmux does not start with the user tmux configuration (in ~/.tmux.conf). This used to work no problem in Nvim-R when R_notmuxconf = 1.

Completion gets worse after turning on R console

Hi, I am not sure if this is an expected behavior, or a bug, or a wrong config on my side, but I am observing the following behavior:

When I open an .R file, the completion works according to what is in the file, so for example, if the file contains library(ggplot2) I will be offered all ggplot variables for the completion, but then I run R using <leader>rf completion no longer works for ggplot, it works only for base R things and it works for ggplot again only after I run the code in the R console. Sorry for a convoluted explanation, I hope it is understandable anyway.

Is RAction still supported?

Back in nvim-R, I used RAction extensively to map simple keystrokes to custom functions (e.g. colnames(), show_query(), etc). It seems that RAction is not supported in R.nvim?

Support for {renv} projects

NB, this issue has previously been discussed at jalvesaq/Nvim-R/issues/445.

Problem description

When a project uses {renv}, {nvimcom} is not available, meaning a good deal of R.nvim breaks. The reason for this is that in {renv} projects the .libPaths() are reset, meaning R can no longer find {nvimcom}, which will have been installed by R.nvim into the libpath where most other package installations also live.

Current workaround

The workaround people seem to have been using is to:

  • Create a new libpath directory somewhere, e.g. called nvimcomlib
  • Create a symlink within this libpath that points to the existing nvimcom installation
  • Set the RENV_CONFIG_EXTERNAL_LIBRARIES environmental variable to point to this new libpath, which tells {renv} it can also look for package installations here

There are a few issues with this workaround:

  • You need to go through these steps each time you update R
  • Symlinks may be hard to create, e.g. on Windows without admin privileges
  • It requires some esoteric knowledge, both about {renv} and R.nvim

Suggested approach for seamless {renv} support

  • When R.nvim is installed, instead of dropping {nvimcom} into the user's default libpath directory, keep this package in its own dedicated directory somewhere else
  • Then, let R know that it can also look for package installations in this alternative location, e.g. by setting the R_LIBS environmental variable before R starts up
  • At the same time, set the RENV_CONFIG_EXTERNAL_LIBRARIES environmental variable to the same value, thereby making {nvimcom} available in {renv} projects

I'm not that familiar with with what happens when R.nvim is installed, so I don't know how realistic/well informed this approach is. However, {renv} is pretty widely used - a quick GitHub search reveals 9.1k repos with a renv.lock file - so in my humble opinion, it's worth seriously considering adding official support.

Tasks to do before inaugurating R.nvim

Here are some tasks that I foresee:

  • Send Lua table instead of Vim list, Vim dictionary, or white space separated list of words to job.stdout, and use lua cmd instead of call v:lua.. Done on data sent to cmp-r which is the only one that requires high speed.

  • Create the R.nvim organization with the repository cmp-r. Done.

  • Do grep -R '\\|' lua/ and fix patterns that don't work.

  • Use vim.regex or vim.fn.matchlist() to fix code that uses patterns \k or \w

  • Fix all most FIXME. OK, the remaining might be fixed later.

  • Add "desc" field to maps.

  • Temporarily force rnvimserver to send strings broken in pieces to fully test job.stdout(). Simpler than that: I did <LocalLeader>o over a character vector with 10000 lines with R running in a remote machine. The data arrived in three parts, and the function worked properly.

  • Test everything.

  • Visit open issues in Nvim-R requesting new features and invite people to try tmp-R-Nvim for a week.. Done.

  • One week later:

    • Add the repository R.nvim to the organization.

    • Close issues in Nvim-R that are too old, aren't reproducible, or won't be fixed, and invite people to switch to R.nvim (where there is a chance of the bug being fixed). Already done.

`reprex` not working (file not found)

Trying to run this, I get an error:

reprex::reprex({
  plot(1)
}, std_out_err = TRUE)
Error in abs_path(input) : 
  The file 'super-sable_reprex.R' does not exist.
In addition: Warning message:
In normalizePath(x, winslash = winslash, mustWork = must_work) :
  path[1]="super-sable_reprex.R": No such file or directory

This works fine in radian outside nvim. My guess it has to do with relative path, but I can not find why at this time.

Randomly got an error message in the R console: `Error in exists(mname) : first argument has length > 1`

I randomly got an error message in the R console: Error in exists(mname) : first argument has length > 1. After searching the codebase, I found this error was caused by nvim.getmethod() function. Changing exists(mname) to any(exists(mname)) should do the trick. But I am not familiar with nvimcom codebase and am not sure that mname should already be a single vector in the first place, and there are other places causing it to be a vector of length > 1.

R.nvim/nvimcom/R/misc.R

Lines 426 to 431 in 7c870c8

nvim.getmethod <- function(fname, objclass) {
mname <- paste0(fname, ".", objclass)
if (exists(mname) && is.function(get(mname)))
return(mname)
return(fname)
}

Could not find R path in Windows Registry

On Windows 10, as of this morning with the new updates over the last 12 hours I am not able to build/install nvimcom. During the installation process I get an error that says Could find R path in Windows Registry. If you already installed R, please, set the value of 'R_path'.

I am wondering if I missed somewhere that the config options from before need to be altered for the new R-nvim, specifically items like (vim.g.R_path='')

config jk in insert mode to send code

Hi in Nvim-R I had this

vim.cmd("imap jk <Esc>:call SendLineToR('stay')<CR><Down><Home>i")

but in r-nvim I don't find SendLineToR functions. Any idea?

Remove support for Evince, Okular and Qpdfview

I can't see any reason to keep support for Evince, Okular, and qpdfview. They are better than Zathura for annotation, filling forms, etc. But we only need to display the newly generated PDF quickly, and Zathura excels in this task.

So, I propose to delete the files evince.lua, okular.lua, and qpdfview.lua. It will still be possible to use them as "generic" pdf viewers, but without the SyncTeX support.

@PMassicotte ? @she3o ?

Change default indentation style?

One of the most important changes for me when setting up R.nvim was to change the default indentation style:

vim.g.r_indent_align_args = 0

This changes the indentation behaviour from this:

paste(
      ... # <- carriage return aligns cursor with `(` from prev line

To this:

paste(
  ... # <- carriage return adds a single layer of indentation

People of course have different opinions about which style is better, so in my view it would be best to:

  • Make this setting easy to configure (done)
  • Make the documentation for this setting easier to find - I'm not sure I would have been able to track it down without finding a relevant issue from Nvim-R.
  • Provide a default which agrees with an industry standard. The Tidyverse style guide is by far the most popular style guide for R, and this advises the latter style:
# Good
do_something_very_complicated(
  something = "that",
  requires = many,
  arguments = "some of which may be long"
)

# Bad
do_something_very_complicated("that", requires, many, arguments,
                              "some of which may be long"
                              )

(From The tidyverse style guide, on Syntax/Long lines)

I'm enjoying this plugin so much - thank you for creating it and generously making it available to the world!

`assign_map` should be disabled differently

Well done on the refactoring!

Either the documentation or implementation on assign_map is incorrect. Setting

assign_map = ""

Leads to an error on opening an R file. I don't know enough lua to edit the implementation, but I got it to work by doing:

assign_map = "<Nop>"

This might not be 100% correct. The documentation in question:

R.nvim/doc/R.nvim.txt

Lines 945 to 948 in 79db76a

To completely disable this feature, put in your config:
>lua
assign_map = ""
<

Error Message
Error detected while processing BufReadPost Autocommands for "*":                                                                
Error executing lua callback: /usr/share/nvim/runtime/filetype.lua:30: Error executing lua: /usr/share/nvim/runtime/filetype.lua:
31: BufReadPost Autocommands for "*"..FileType Autocommands for "*"..function <SNR>1_LoadFTPlugin[20]..script /home/wojtek/.local
/share/nvim/lazy/R.nvim/ftplugin/r_rnvim.lua: Vim(runtime):E5113: Error while calling lua chunk: /home/wojtek/.local/share/nvim/l
azy/R.nvim/lua/r/maps.lua:197: Invalid (empty) LHS                                                                               
stack traceback:                                                                                                                 
        [C]: in function 'nvim_buf_set_keymap'                                                                                   
        /home/wojtek/.local/share/nvim/lazy/R.nvim/lua/r/maps.lua:197: in function 'edit'                                        
        /home/wojtek/.local/share/nvim/lazy/R.nvim/lua/r/maps.lua:291: in function 'create'                                      
        ...ojtek/.local/share/nvim/lazy/R.nvim/ftplugin/r_rnvim.lua:61: in main chunk                                            
        [C]: in function 'nvim_cmd'                                                                                              
        /usr/share/nvim/runtime/filetype.lua:31: in function </usr/share/nvim/runtime/filetype.lua:30>                           
        [C]: in function 'nvim_buf_call'                                                                                         
        /usr/share/nvim/runtime/filetype.lua:30: in function </usr/share/nvim/runtime/filetype.lua:10>                           
stack traceback:                                                                                                                 
        [C]: in function 'nvim_cmd'                                                                                              
        /usr/share/nvim/runtime/filetype.lua:31: in function </usr/share/nvim/runtime/filetype.lua:30>                           
        [C]: in function 'nvim_buf_call'                                                                                         
        /usr/share/nvim/runtime/filetype.lua:30: in function </usr/share/nvim/runtime/filetype.lua:10>                           
stack traceback:                                                                                                                 
        [C]: in function 'nvim_buf_call'                                                                                         
        /usr/share/nvim/runtime/filetype.lua:30: in function </usr/share/nvim/runtime/filetype.lua:10>       

Organization and project names

I started this repository as tmp-R-Nvim, but @she3o used R.nvim in the CONTRIBUTING.md document. So, we have at least two options. R-Nvim (closer to Nvim-R) and R.nvim (resembling the names of many other Neovim plugins). Since we are refactoring Nvim-R, I think there is no reason to choose a name similar to the old one, and R.nvim is easier to type...

Error, segfaualt and exit

Seems the new update broke something, the error output is given below

*** caught segfault ***
address (nil), cause 'memory not mapped'

Traceback:
1: fun(libname, pkgname)
2: doTryCatch(return(expr), name, parentenv, hand
ler)
3: tryCatchOne(expr, names, parentenv, handlers[[
1L]])
4: tryCatchList(expr, classes, parentenv, handler
s)
5: tryCatch(fun(libname, pkgname), error = identi
ty)
6: runHook(".onAttach", ns, dirname(nspath), nsna
me)
7: attachNamespace(ns, pos = pos, deps, exclude,
include.only)
8: doTryCatch(return(expr), name, parentenv, hand
ler)
9: tryCatchOne(expr, names, parentenv, handlers[[
1L]])
10: tryCatchList(expr, classes, parentenv, handler
s)
11: tryCatch({ attr(package, "LibPath") <- whic
h.lib.loc ns <- loadNamespace(package, lib.loc)
env <- attachNamespace(ns, pos = pos, deps, ex
clude, include.only)}, error = function(e) { P
<- if (!is.null(cc <- conditionCall(e))) p
aste(" in", deparse(cc)[1L]) else "" msg <-
gettextf("package or namespace load failed for %s%
s:\n %s", sQuote(package), P, conditionMes
sage(e)) if (logical.return && !quietly)
message(paste("Error:", msg), domain = NA) el
se stop(msg, call. = FALSE, domain = NA)})
12: library(package, lib.loc = lib.loc, character.
only = TRUE, logical.return = TRUE, warn.confl
icts = warn.conflicts, quietly = quietly, mask.ok
= mask.ok, exclude = exclude, include.only = i
nclude.only, attach.required = attach.required)
13: doTryCatch(return(expr), name, parentenv, hand
ler)
14: tryCatchOne(expr, names, parentenv, handlers[[
1L]])
15: tryCatchList(expr, classes, parentenv, handler
s)
16: tryCatch(library(package, lib.loc = lib.loc, c
haracter.only = TRUE, logical.return = TRUE, w
arn.conflicts = warn.conflicts, quietly = quietly,
mask.ok = mask.ok, exclude = exclude, include
.only = include.only, attach.required = attach
.required), error = function(e) e)
17: require(pkg, quietly = TRUE, warn.conflicts =
FALSE, character.only = TRUE)
18: .First.sys()

Possible actions:
1: abort (with core dump, if enabled)
2: normal R exit
3: exit R without saving workspace
4: exit R saving workspace

some issues and questions mainly csv_app after testing it

Congratulations on the new plugin refactoring! and thank you for the hard work.
After testing it, I'd like to highlight a few points:

  1. It's noticeably faster than the old one, especially when opening plots and sending commands.
  2. Opening and closing the console is much snappier, which is a big improvement.
    Overall, there are many enhancements.

However, I noticed a few things:

  • The autoformatting when saving is really good, but I need to keep assignments as = instead of <- because I work with Python a lot, and I want to keep things consistent, so is there a way?
  • The rbrowser (<localleader>ro) doesn't refresh when I open it until I perform some assignment (like if I was working and open it, it shows nothing until I do some assignment).
  • The csv_app feature doesn't seem to work anymore. I had it set as vim.g.csv_app = "terminal: vd", but now it doesn't work. I tried adding
opts = {
csv_app = "terminal: vd"
}

\rv output in the echo area:
Screenshot 2024-02-19 at 3 39 23 PM

to the plugin config, but it complained about it. So, I'm not sure how this will work, even though I saw it in the source code.

  • Finally, as more of an aesthetic suggestion, in the rbrowser, to save some more space on the left, there's no need for the signcolumn or foldcolumn options, and I was going to make a pr to add these 2 options, but then I decided to know if those was intentional.

Overall, great job on the plugin!

Thank you

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.