You could use the following function. It is extremely hacky and I haven't tested
it plenty but it seems to work.
The idea is to create a command :Mksession
which will work like the original
:mksession
but will also save the unnamed buffers.
(Note that I had some inspiration from this
answer
To do so it will call a function which does the following:
- First handle the argument so that you can call the command with of without a filename as argument
- Execute the original
:mksession
- Use a list which will contain the content of the unnamed buffer
- Use a command which will test the name of each buffers. When the name is empty,
getline()
is used to add the content of the buffer to the list of contents.
- Finally for each set of line, instructions are added to the session file to create a new buffer and put the content into it.
Add theses lines to your .vimrc
:
function! MkSession(...)
" Handle the argument
if empty(a:000)
let filename = "Session.vim"
else
let filename = fnameescape(a:1)
endif
" Create the session file according to the argument passed
execute 'mksession! ' . filename
" The list containing the lines on the unnmaed buffers
let noname_buffers = []
" Get the lines of all the unnamed buffers in the list
execute "silent! bufdo \| if expand('%')=='' \| call add(noname_buffers, getline(1, '$')) \| endif"
" For each set of lines
" Add into the session file a line creating an empty buffer
" and a line adding its content
for lines in noname_buffers
call system('echo "enew" >> '.filename)
call system('echo "call append(0, [\"'. join(lines, '\",\"') .'\"])" >>'. filename)
endfor
endfunction
command! -nargs=? Mksession call MkSession(<f-args>)
You can then simply call the command like that:
:Mksession
Or with a file name
:Mksession mysession.vim
Edit
As @DJ McMayhem pointed it out in the comments you can even add this line to your .vimrc
:
cnoremap mksession Mksession
This would make ̀ :mksession(without capitalized
m) behave like the
:Mksessioncommand we just defined (with capitalized
M`).
I mentioned it because for some user it could be seen as an advantage. However I would not recommend to use it: it hides the fact that you're using a custom function and if a side-effect appears it could add some difficulty to debug a problem.