1

I am writing a little hack for vim session that will save and load sessions more conveniently - I am aiming for more project-style sessions.

When you are in directory my-proj and call vim, it should automatically open the session associated with the current directory. (This is 'almost' working so far - the problem is with getting the current directory). Saving the 'project' (i.e. a session) can be done with SaveSession

I have done this so far:

let g:session_autosave = 'yes'
let g:session_autoload = 'yes'
let g:session_default_name = getcwd()

The minor problem is, if I call vim ~/x.txt, getcwd() will not return ~/x.txt. It will return the current directory in bash (which could be almost anything). How can I get the directory that vim was called on in the command line (i.e. ~ in this case)? And if vim was opened with just vim then it should get the current working directory.

  • Just a hint, but maybe :h autochdir will help you. – grodzik Feb 2 '17 at 8:31
  • I don't think this is what I am looking for. I have nerdtree, so opening a file that is nested within the 'project' will cause the path to be incorrect – Dylanthepiguy Feb 2 '17 at 19:55
4

If you want to get the directory of the first file in :argv (the filename arguments when vim was opened): let g:session_default_name = fnamemodify(argv()[0], ':p:h'). This will fail if vim was opened with no arguments.

To fallback on getcwd() where there were no arguments:

" Returns the directory of the first file in `argv` or `cwd` if it's empty
function FindSessionDirectory() abort
  if len(argv()) > 0
    return fnamemodify(argv()[0], ':p:h')
  endif
  return getcwd()
endfunction!
let g:session_default_name = FindSessionDirectory()
  • I don't think the first option will work since I use nerdtree, so opening a file that is nested within the 'project' will cause the path to be incorrect. – Dylanthepiguy Feb 2 '17 at 19:55
  • The second option looks very promising. I shall look into this and attempt to default to getcwd where argv doesn't work (I am a noob at Vimscript though so this may take a while) – Dylanthepiguy Feb 2 '17 at 20:16
  • 1
    Added a function with the fallback to cwd() – Nate Bosch Feb 3 '17 at 3:37
  • I appear to be getting some errors: Error detected while processing function FindSessionDirectory: line 2: E15: Invalid expression: ], ':p:h') E116: Invalid arguments for function fnamemodify(argv()[], ':p:h') E15: Invalid expression: fnamemodify(argv()[], ':p:h') Press ENTER or type command to continue – Dylanthepiguy Feb 3 '17 at 7:33
  • Oops, I missed a 0 - should be argv()[0]. Updated the answer – Nate Bosch Feb 4 '17 at 7:14

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.