1

Here is a situation: I want to manage my working environment on multiple projects separately, and all of them should have its own session (Session.vim) to save and restore.

So I would like to launch each project via nvim -S SESSION_FILE. And in order to save and quit easily, I define the following:

nnoremap <leader>q :mksession! ~/.config/nvim/session.vim<cr>:wqa<cr>

However, I want to set the SESSION_FILE to some variable in the vimrc at the launch time automatically, and then quit via <leader>q whatever the current project is, by replacing the ~/.config/nvim/session.vim to the variable I read via the command-line argument. However, I'm not sure how I can extract the command-line argument that is executed on Terminal.

So how can I read the command-line argument from the launch and set it in the vimrc while the vim is working, and then when it quits, it automatically save the session file that is specific to the current project?

1

If you're willing to roll your own argument parsing by abusing file names, then vim has the functions argc and argv that mimic the API of main in C.

argc returns the number of arguments (besides the 0th one, the name under which vim was invoked).

argv() returns the arguments as an array of strings.

argv(n) returns the nth element of the array of strings.

For instance

$ vim a b c d

within vim, if you run the following commands

:echo argc()

See also :help arglist. 4

:echo argv()
['a', 'b', 'c', 'd']

:echo argv(0)
a

:echo argv(27)
<empty string>

Note that you cannot use this to implement options beginning with - because those are handled before vimscript gets a chance to see the arguments. But you can pick another convention like key=value

1

Vim version 8.1.2233 adds the read-only variable v:argv, which can be used to parse the command line arguments given to Vim.

0

There might be an easier way than checking the command line arguments. Depending on the value of sessionoptions you can save vim variables in your session.vim file with :mks so you just need to set your variable in the running session (instead of the vimrc file) and it will be restored together with the session:

let g:MySessionFile = '~/.config/nvim/session_foo.vim'

Then you can define the mapping in your vimrc like this:

nnoremap <leader>q :exe "mksession! " . g:MySessionFile <BAR> wqall<CR>

EDIT: If you want to save your session file every time you quit and do not want to learn your new mapping you can set up a VimLeave autocmd to save the session file when the variable from above exists. Something like this (untested):

au VimLeave * 
  \ if exists('g:MySessionFile') |
  \   exe "mksession! " . g:MySessionFile |
  \ endif

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.