olimorris / persisted.nvim Goto Github PK
View Code? Open in Web Editor NEW๐พ Simple session management for Neovim with git branching, autoloading and Telescope support
License: MIT License
๐พ Simple session management for Neovim with git branching, autoloading and Telescope support
License: MIT License
It would be great if the plugin could respect Neovim's sessionoptions
setting, instead of having to repeat the list. Another option would be to provide a 'default' flag to pass to the plugin's options
setting.
Thanks!
{
name = "PersistedHooks",
{
"User",
function(session)
require("persisted").save()
-- Delete all of the open buffers
vim.api.nvim_input("<ESC>:%bd!<CR>")
-- Don't start saving the session yet
require("persisted").stop()
end,
opts = { pattern = "PersistedTelescopeLoadPre" },
},
},
No response
I want to pin / sticky a buffer through sessions save/switching, more verbose below:
<C-\><C-n>
to bring terminal buffer to normal mode (you can now switch to other buffers)How to not save terminal buffer from sessionA at step 5? other buffers at step 4 should still be saved to sessionA.
When switch to sessionB at step 6, terminal buffer from sessionA should be avail/merged to sessionB buffers list
minimal.lua
config file above and still get the issueSessionSave
to save the session before restarting Neovim and using SessionLoad
I installed persisted.nvim
on my experimental dotfiles branch but the plugin still assigns the default branch name (main
) to the session entry instead of the name of the branch.
The config is more or less a duplicate of what's in the README:
use { 'olimorris/persisted.nvim',
config = function ()
require('persisted').setup {}
require('telescope').load_extension 'persisted'
end
}
When determining if a directory matches a directory in allowed_dirs
or ignored_dirs
the dirs_match()
function uses directory names as lua patterns to match against the current working directory. This causes issues when a directory name contains a special lua pattern matching character, "(", ")", ".", "%", "+", "-", "*", "?", "[", "^", "$"
, because it will be interpreted as such and cause some directories to not be properly detected despite being exact matches of directories in allowed_dirs
or ignored_dirs
.
Thanks for the plugin! Unfotunately, I have some problems with it.
When I call Telescope persisted
I get the error message:
Error executing Lua callback: .../pack/packer/start/persisted.nvim/lua/persisted/init.lua:199: attempt to index a nil value
stack traceback:
.../pack/packer/start/persisted.nvim/lua/persisted/init.lua:199: in function 'list'
...t/persisted.nvim/lua/telescope/_extensions/persisted.lua:15: in function <...t/persisted.nvim/lua/telescope/_extensions/persisted.lua:9>
...ck/packer/start/telescope.nvim/lua/telescope/command.lua:193: in function 'run_command'
...ck/packer/start/telescope.nvim/lua/telescope/command.lua:253: in function 'load_command'
...te/pack/packer/start/telescope.nvim/plugin/telescope.lua:109: in function <...te/pack/packer/start/telescope.nvim/plugin/telescope.lua:108>
I expected to get Telescope window with sessions instead.
Persisted related part of packer config:
-- * Session management.
use({
'olimorris/persisted.nvim',
--module = "persisted", -- For lazy loading
config = [[ require('config.persisted') ]],
});
Persisted config:
local prequire = require('utils').prequire;
local persisted_status_is_ok, persisted = prequire("persisted");
if not persisted_status_is_ok then
return;
end
--local ENV = require('global');
persisted.setup({
-- Unfortunately, SessionLoadLast doesn't work with save_dir even though it's
-- newer.
--save_dir = ENV.NVIM_DATA .. '/sessions/', -- directory where session files are saved
--dir = ENV.NVIM_DATA .. '/sessions/', -- directory where session files are saved
save_dir = vim.fn.expand(vim.fn.stdpath("data") .. "/sessions/"),
--dir = vim.fn.expand(vim.fn.stdpath("data") .. "/sessions/"),
--command = 'VimLeavePre', -- the autocommand for which the session is saved
--use_git_branch = true, -- create session files based on the branch of the git enabled repository
--autosave = true, -- automatically save session files when exiting Neovim
--autoload = false, -- automatically load the session for the cwd on Neovim startup
--allowed_dirs = nil, -- table of dirs that the plugin will auto-save and auto-load from
--ignored_dirs = nil, -- table of dirs that are ignored when auto-saving and auto-loading
--before_save = function() end, -- function to run before the session is saved to disk
--after_save = function() end, -- function to run after the session is saved to disk
--telescope = { -- options for the telescope extension
--before_source = function(session) end, -- function to run before the session is sourced via telescope
--after_source = function(session) end, -- function to run after the session is sourced via telescope
--},
});
-- To load the telescope extension.
local telescope_status_is_ok, telescope = prequire("telescope");
if not telescope_status_is_ok then
return;
end
telescope.load_extension("persisted");
prequire
is likepcall
but withnvim.notify
for errors, nothing fancy.
Tried to call lua require('persisted').list()
directly to understand if the problem on Telescope or this plugin's side and got this error:
E5108: Error executing lua .../pack/packer/start/persisted.nvim/lua/persisted/init.lua:199: attempt to index a nil value
stack traceback:
.../pack/packer/start/persisted.nvim/lua/persisted/init.lua:199: in function 'list'
[string ":lua"]:1: in main chunk
Unfortunately, I couldn't make any progress by
PackerSync
& PackerCompile
That's why I'm posting this issue here. Hope you will help me solve it!
I want to ignore user's home dir specifically but not whatever dirs under that home, so when i at home cd ~
and start nvim, this session will be ignored.
but when i do like cd ~/.config/nvim; nvim
then the session for ~/.config/nvim
will not
be ignored.
howto?
Hi, thanks for the amazing plugin!
I have a particular workflow where I will open a session in one directory and then possibly change directory to open files in a separate directory (for example notes in Dropbox). However, once I have done this, my session is automatically saved in the new directory location rather than the original. I'd prefer that once a session is opened, it is always saved back to it's original location.
If this is something you'd be open to implementing, it could use a global variable such as vim.g.persistlocation
which is used in the VimLeavePre
autocommand to determine save location rather than the current directory. This could also be a toggleable option.
If it is interesting to you, I'd be happy to submit a PR.
Use case: I have autoload = true
in persisted.nvim
, as well as a custom, bespoke startup screen (not using any plugin) in my config, but I only want to show the startup screen if persisted.nvim
is not going to load a session.
Maybe an API like:
require('persisted').setup({
autoload = true,
on_no_session_to_autoload = function()
-- load my custom startup screen
end
})
After the commit 774e4d7
startup time in lazy.nvim increased by 400 msec
Hi,
Been looking into replacing my current session plugin so I can better replicate the https://github.com/emacs-dashboard/emacs-dashboard by listing my sessions and was also looking for something that handled git branches nicely which this does.
One rather frustrating issue I've encountered though is that when auto-restoring a session there is a brief flicker as either my start screen or the first empty buffer is briefly shown before it then auto restores the session. I've tried to get used to it but the flicker is maddening unfortunately.
I had a look through the code and compared it with things like autosession and possession.nvim etc. and noticed the cause I believe to be the line below.
persisted.nvim/lua/persisted/utils.lua
Line 68 in 325cda4
When this plugin restores a session it uses vim.schedule
rather than executing the command immediately which means it defers it and vim the loads the start buffer (or the dashboard) before eventually getting to the autorestore causing the flicker. I can see that removing the scheduling does make it instantaneous but there is a brief flicker since the first autorestore should not happen whilst vim is still starting up but should be delayed till VimEnter
I believe.
Any chance you'd be up for changing how auto restoration is handled to avoid the flicker? is it something that you've seen? I'm a bit surprised no one else has mentioned this in the closed issues AFAICT
The following features appear to be broken:
autoload = true
lua require("persisted").list()
Config:
-- Sessions --
use {
"olimorris/persisted.nvim",
config = function()
require("persisted").setup({
use_git_branch = true,
autoload = true,
autosave = true,
allowed_dirs = {"/projects/eaglesys"},
options = {"curdir", "folds", "help", "tabpages", "winsize", "winpos", "terminal"},
})
end
}
Thanks! It's awesome that this plugin supports git branches, I think this is the first one to do so.
Edit: Not sure what happened, but I ran a PackerSync
again and autoload started working.
Edit #2: Ah, I figured it out. The allowed_dirs
setting was preventing the autoload (despite me being in that directory). Perhaps I configured it wrong?
vim.opt.sessionoptions = { -- required
"buffers",
"curdir",
"folds",
"globals",
"resize",
"tabpages",
"winsize",
}
require("persisted").setup({
follow_cwd = false, -- change session file name to match current working directory if it changes
})
require("telescope").load_extension("persisted")
-- define a command to close sesssion
function SessionClose()
cmd[[SessionStop]]
cmd[[%bd!]]
cmd[[cd]]
end
cmd[[command! -nargs=0 SessionClose lua SessionClose()]]
-- auto save/load scope
require("scope").setup({})
local group = vim.api.nvim_create_augroup("PersistedHooks", {})
vim.api.nvim_create_autocmd({ "User" }, {
pattern = "PersistedSavePost",
group = group,
callback = function()
cmd[[ScopeSaveState]]
end,
})
vim.api.nvim_create_autocmd({ "User" }, {
pattern = "PersistedLoadPost",
group = group,
callback = function()
cmd[[ScopeLoadState]]
cmd[[e]]
end,
})
Error executing Lua callback: ...share/nvim/lazy/telescope.nvim/lua/telescope/pickers.lua:347: Invalid 'event': 'User TelescopeFindPre'
stack traceback:
[C]: in function 'nvim_exec_autocmds'
...share/nvim/lazy/telescope.nvim/lua/telescope/pickers.lua:347: in function 'find'
...y/persisted.nvim/lua/telescope/_extensions/persisted.lua:40: in function <...y/persisted.nvim/lua/telescope/_extensions/persisted.lua:11>
...share/nvim/lazy/telescope.nvim/lua/telescope/command.lua:193: in function 'run_command'
...share/nvim/lazy/telescope.nvim/lua/telescope/command.lua:253: in function 'load_command'
...ocal/share/nvim/lazy/telescope.nvim/plugin/telescope.lua:108: in function <...ocal/share/nvim/lazy/telescope.nvim/plugin/telescope.lua:107>
Calling :Telescope persisted
produces an error mentioned above. Previously worked fine, but started to happen after neovim update.
No response
minimal.lua
config file above and still get the issueSessionSave
to save the session before restarting Neovim and using SessionLoad
Hi there, thanks for your amazing plugin,
"on_autoload_no_session" is now broken, after commit# 226db92
{
save_dir = "sessions/",
autoload = false,
autosave = false,
}
No response
Not saved session
Session is saved
I did some small research. I guess it is related to the https://github.com/olimorris/persisted.nvim/blob/main/lua/persisted/init.lua#L148-L153 block.
Small test:
local function check(conf)
if (conf.options.autosave and type(conf.options.should_autosave) == "function")
and not conf.options.should_autosave()
then
print("not saving")
else
print("saving")
end
end
-- Works as expected
-- autosave = true and should_autosave = true
local config1 = {}
config1.options = {}
config1.options.autosave = true
config1.options.should_autosave = function()
return true
end
check(config1)
-- output: saving
-- Doesn't work as expected
-- autosave = false and should_autosave = true
local config2 = {}
config2.options = {}
config2.options.autosave = false
config2.options.should_autosave = function()
return true
end
check(config2)
-- output: saving
-- Works as expected
-- autosave = true and should_autosave = false
local config3 = {}
config3.options = {}
config3.options.autosave = true
config3.options.should_autosave = function()
return false
end
check(config3)
-- output: not saving
-- Doesn't work as expected
-- autosave = false and should_autosave = false
local config4 = {}
config4.options = {}
config4.options.autosave = false
config4.options.should_autosave = function()
return false
end
check(config4)
-- output: saving
Setup minimal.lua with my config.
1 Enter vim.
2. Escape vim.
3. ls sessions/ | wc -l
4. in sessions folder is a saved session.
minimal.lua
config file above and still get the issueSessionSave
to save the session before restarting Neovim and using SessionLoad
I'm using the totally unchanged sample minimal.lua
:
local root = "/tmp/persisted"
-- Set stdpaths to use root dir
for _, name in ipairs({ "config", "data", "state", "cache" }) do
vim.env[("XDG_%s_HOME"):format(name:upper())] = root .. "/" .. name
end
-- Bootstrap lazy
local lazypath = root .. "/plugins/lazy.nvim"
if not vim.loop.fs_stat(lazypath) then
vim.fn.system({
"git",
"clone",
"--filter=blob:none",
"--single-branch",
"https://github.com/folke/lazy.nvim.git",
lazypath,
})
end
vim.opt.runtimepath:prepend(lazypath)
vim.opt.sessionoptions = "buffers,curdir,folds,globals,tabpages,winpos,winsize" -- Session options to store in the session
-- Install plugins
local plugins = {
{
"olimorris/persisted.nvim",
opts = {
-- Your custom config here
}
},
-- Put any other plugins here
}
require("lazy").setup(plugins, {
root = root .. "/plugins",
})
The following error message can not be seen with the minimal.lua
configuration, but with my regular init.lua
(which has plenty more plugins), I also experience a non-zero exit code, and the following error flashes very briefly (had to record my screen to read the text) in the top left of the screen before Neovim quits:
nvim: src/unix/core.c:147: uv_close: Assertion `!uv__is_closing(handle' failed.
Neovim quits with a zero as exit code.
Neovim quits with a non-zero exit code.
I did a git bisect
to figure out when the issue was introduced, and it seems like the problem (at least for my setup) started in this commit: 774e4d7
nvim --clean -u minimal.lua
):q
minimal.lua
config file above and still get the issueSessionSave
to save the session before restarting Neovim and using SessionLoad
If a session directory is a subdirectory of a git repo rather that the top level directory of the repo, the git branch for the session will not be properly detected because the presence of a .git
directory, which only exists in the top level, is used to determine if a directory is tracked in git.
Currently, it is not possible to obtain the session directory and git branch from the session
table passed to the telescope before_source()
and after_source()
callbacks. I think it may be useful to provide these fields as part of the session
table passed to the callbacks. For example I am trying to obtain the git branch of a session selected in the telescope picker in order to automatically check out the branch before sourcing the session file. This would be especially useful in the event that buffers for files that only exist on that branch are restored by the session file.
Also, I am not sure why a default branch name is appended to session files whose directories are not git repositories. I find that this makes it difficult to determine if a session's directory is actually a git repo or not because they all have a branch name even if it's just a default. Wouldn't it make more sense to just not append anything for session directories that are not git repos?
return {
"olimorris/persisted.nvim",
lazy = false,
config = function()
require("persisted").setup({
save_dir = vim.fn.expand(vim.fn.stdpath("data") .. "/sessions/"), -- directory where session files are saved
silent = false, -- silent nvim message when sourcing session file
use_git_branch = false, -- create session files based on the branch of the git enabled repository
autosave = true, -- automatically save session files when exiting Neovim
should_autosave = nil, -- function to determine if a session should be autosaved
autoload = true, -- automatically load the session for the cwd on Neovim startup
on_autoload_no_session = nil, -- function to run when `autoload = true` but there is no session to load
follow_cwd = true, -- change session file name to match current working directory if it changes
allowed_dirs = nil, -- table of dirs that the plugin will auto-save and auto-load from
ignored_dirs = nil, -- table of dirs that are ignored when auto-saving and auto-loading
telescope = { -- options for the telescope extension
reset_prompt_after_deletion = true, -- whether to reset prompt after session deleted
},
})
require("telescope").load_extension("persisted") -- To load the telescope extension
end,
}
autocmd.lua
autocmd({ "User" }, {
pattern = "PersistedTelescopeLoadPre",
group = augroup,
callback = function()
vim.schedule(function()
pcall(vim.cmd, "SessionSave")
pcall(vim.cmd, "silent %bd!")
end)
end,
})
No response
Steps:
1. cd /path/to/folder1
2. nvim
3. open some buffers
4. :bd!
5. nvim #sesison restored correctly
6. :bd!
9. cd /path/to/folder2
10. nvim
11. open some buffers
12. :bd! #trigger autosave session
13. nvim #restored correctly
14. :bd!
15. nvim
16. :Telescope persisted
17. <select session of folder1>
18. <switched successfully to session folder1>
19. :bd!
20. nvim #still under /path/to/folder2
21. <now nvim auto restore to session of folder1, :pwd show that it's folder1's path>
Expected here that when under folder1 or folder2, start nvim will restore session of each.
when switch via telescope, all current buffers of current session will be tried to del if not having un-saved/modifed files and then switch cwd and restore the selecting session from telescope. Do not overwrite current session next session (currently it did)
NVIM v0.9.0-dev-1260+ga7b537c7
latest persisted.nvim
minimal.lua
config file above and still get the issueSessionSave
to save the session before restarting Neovim and using SessionLoad
buffers are not closed when using telescope.
I have to use this workaround:
telescope = { -- options for the telescope extension
-- jump between session smoothly
after_source = function(param)
vim.api.nvim_command "%bd"
local path = param.dir_path
print(path)
if string.find(path, "/") ~= 1 then
vim.api.nvim_command("cd " .. vim.fn.expand "~" .. "/" .. path)
vim.api.nvim_command("tcd " .. vim.fn.expand "~" .. "/" .. path)
else
vim.api.nvim_command("cd " .. path)
vim.api.nvim_command("tcd " .. path)
end
end,
},
make this by default?
minimal.lua
config{
"olimorris/persisted.nvim",
-- stylua: ignore
keys = {
{ "<leader>qs", function() require("persisted").load() end, desc = "Restore Session" },
{ "<leader>ql", function() require("persisted").load({ last = true }) end, desc = "Restore Last Session" },
{ "<leader>qd", function() require("persisted").stop() end, desc = "Don't Save Current Session" },
{
"<leader>fs",
"<cmd>Telescope persisted<cr>",
desc = "Find Session",
},
},
opts = {
save_dir = vim.fn.expand(vim.fn.stdpath("data") .. "/sessions/"), -- directory where session files are saved
silent = false, -- silent nvim message when sourcing session file
use_git_branch = false, -- create session files based on the branch of a git enabled repository
default_branch = "main", -- the branch to load if a session file is not found for the current branch
autosave = true, -- automatically save session files when exiting Neovim
autoload = true, -- automatically load the session for the cwd on Neovim startup
on_autoload_no_session = nil, -- function to run when `autoload = true` but there is no session to load
follow_cwd = true, -- change session file name to match current working directory if it changes
allowed_dirs = nil, -- table of dirs that the plugin will auto-save and auto-load from
ignored_dirs = nil, -- table of dirs that are ignored when auto-saving and auto-loading
telescope = {
reset_prompt = true, -- Reset the Telescope prompt after an action?
},
should_autosave = function()
local excluded_filetypes = {
"alpha",
"oil",
"lazy",
"",
}
for _, filetype in ipairs(excluded_filetypes) do
if vim.bo.filetype == filetype then
return false
end
end
return true
end,
},
},
None
When I open a folder , no session is restored automatically. Manually restoring works though
Open a directory in neovim
Open few files
Exit vim
Repopen the directory
minimal.lua
config file above and still get the issueSessionSave
to save the session before restarting Neovim and using SessionLoad
github.com/ayamir/nvimdots
No response
Same issue as auto-session
has: rmagatti/auto-session#223
No response
minimal.lua
config file above and still get the issueSessionSave
to save the session before restarting Neovim and using SessionLoad
Any plans on adding named sessions? In order to allow to switch between groups of related files or folders.
Something I have been mulling over for a while now is replacing the mess that is user callbacks in this plugin. As time has progressed, so have the number of callbacks. Whilst they're all justified, their implementation couldn't help but feel clunky.
To remedy this, callbacks will be replaced with user events which can be hooked into via autocmds. The benefits of this are:
persisted.nvim
configMy use case is the following:
I want to autoload a session for the cwd at start if it exits. If not I want to open alpha dashboard. I have setup alpha
not to start automatically and have the following function as on_autoload_no_session
function:
local on_autoload_no_session = function()
-- need to pass true (on_vimenter) so that alpha clears the unnamed buffer vim creates at start
require("alpha").start(true)
end
The first run everything goes fine, alpha
dashboard starts up:
(just noticed the typo in "Find sesssion" :))
Then I hit <leader>q
which is bound to :qa!
in the dashboard settings.
The next time I open nvim in the same cwd, persisted
loads practically an empty session:
Here's the actual session.vim file saved:
let SessionLoad = 1
let s:so_save = &g:so | let s:siso_save = &g:siso | setg so=0 siso=0 | setl so=-1 siso=-1
let v:this_session=expand("<sfile>:p")
silent only
cd ~/gits/persisted.nvim
if expand('%') == '' && !&modified && line('$') <= 1 && getline(1) == ''
let s:wipebuf = bufnr('%')
endif
let s:shortmess_save = &shortmess
if &shortmess =~ 'A'
set shortmess=aoOA
else
set shortmess=aoO
endif
argglobal
%argdel
set lines=61 columns=232
if exists('s:wipebuf') && len(win_findbuf(s:wipebuf)) == 0 && getbufvar(s:wipebuf, '&buftype') isnot# 'terminal'
silent exe 'bwipe ' . s:wipebuf
endif
unlet! s:wipebuf
set winheight=1 winwidth=20
let &shortmess = s:shortmess_save
let s:sx = expand("<sfile>:p:r")."x.vim"
if filereadable(s:sx)
exe "source " . fnameescape(s:sx)
endif
let &g:so = s:so_save | let &g:siso = s:siso_save
set hlsearch
nohlsearch
doautoall SessionLoadPost
unlet SessionLoad
" vim: set ft=vim :
What should've happened (imo) is that the alpha
dashboard would've opened instead of this "session".
My question is: is there a way to prevent persisted
from saving such an "empty" session?
As discussed in #5:
I thought I could create a mapping directly to lua require("persisted").list() and have it open in a Telescope window. Perhaps you would consider adding in a telescope extension? Then all that would be required for the user would be something along the lines of (note that I use the cartographer plugin for my mappings):
require('telescope').load_extension('persisted') map.n.nore.silent['<leader>tp'] = ':Telescope persisted<cr>'
require('persisted').setup {
save_dir = vim.fn.expand(vim.fn.stdpath 'data' .. '/sessions/'),
autosave = true,
should_autosave = function()
vim.notify 'Session saved'
end,
telescope = {
reset_prompt_after_deletion = true,
},
}
No response
It will pump up my saved session when I use :SessionLoad or :SessionLoadLast or :Telescope persisted
Nothing, I checked the session directory and it's completely empty
minimal.lua
config file above and still get the issueSessionSave
to save the session before restarting Neovim and using SessionLoad
This plugin error occurred when I tried to load the session. This happened after I updated my neovim and git.
Current neovim (nightly):
NVIM v0.9.0-dev-987+g371a74e4e
Build type: RelWithDebInfo
LuaJIT 2.1.0-beta3
git version 2.39.2
Error:
E5108: Error executing lua ...site/pack/lazy/opt/persisted.nvim/lua/persisted/init.lua:68: attempt to concatenate field 'branch_separator' (a nil value)
stack traceback:
...site/pack/lazy/opt/persisted.nvim/lua/persisted/init.lua:68: in function 'get_branch'
...site/pack/lazy/opt/persisted.nvim/lua/persisted/init.lua:75: in function 'get_current'
...site/pack/lazy/opt/persisted.nvim/lua/persisted/init.lua:103: in function 'load'
[string ":lua"]:1: in main chunk
minimal.lua
configlocal root = "/tmp/persisted"
-- Set stdpaths to use root dir
for _, name in ipairs({ "config", "data", "state", "cache" }) do
vim.env[("XDG_%s_HOME"):format(name:upper())] = root .. "/" .. name
end
-- Bootstrap lazy
local lazypath = root .. "/plugins/lazy.nvim"
if not vim.loop.fs_stat(lazypath) then
vim.fn.system({
"git",
"clone",
"--filter=blob:none",
"--single-branch",
"https://github.com/folke/lazy.nvim.git",
lazypath,
})
end
vim.opt.runtimepath:prepend(lazypath)
vim.opt.sessionoptions = "buffers,curdir,folds,globals,tabpages,winpos,winsize" -- Session options to store in the session
-- Install plugins
local plugins = {
{
"olimorris/persisted.nvim",
opts = {
use_git_branch = true,
should_autosave = true,
autoload = true
-- Your custom config here
}
},
-- Put any other plugins here
}
require("lazy").setup(plugins, {
root = root .. "/plugins",
})
[Persisted.nvim]
Could not load a session for branch master
Trying to load a session for branch main ...
[Persisted.nvim]
Could not find a session for /home/miversen/.local/share/nvim/lazy/marks.nvim
As per https://github.com/olimorris/persisted.nvim/discussions/103 you may need to remove the branch from the name
After the changes referenced in #103 , it seems that autoloading while using git repositories is kinda broken. This issue only pops up when you enter a repository (or branch) for the first time. After the session is created initially it goes away. I ignored the error for a while but it is getting irritating that I am ignoring false errors. Do let me know if there is anything I can provide to help :)
minimal.lua
config file above and still get the issueSessionSave
to save the session before restarting Neovim and using SessionLoad
I have session at ~/.local/share/chezmoi
, the autosave should trigger in any directory if I run nvim
in that directory, and it's true and works.
But the previous behavior seems lost. When I open file with nvim $HISTFILE
in ~/.local/share/chezmoi
, then close it, now the session contain only file $HISTFILE
, which is not what I desire and not the previous behaivor.
The autosave should automatically not triggered when opening file directly, i.e. nvim /path/to/file
, nvim $HISTFILE
, etc.
Tool | Version |
---|---|
NVIM | NVIM v0.9.0-dev-1166+g06aed7c17 |
Persisted | 88f27dc |
Originally posted by @latipun7 in #51 (comment)
I just installed the plugin and it seems like autosave is not working. If I am explicitly calling session save command and session load last command then it worked. but autosave not working
minimal.lua
configlocal root = "/tmp/persisted"
-- Set stdpaths to use root dir
for _, name in ipairs({ "config", "data", "state", "cache" }) do
vim.env[("XDG_%s_HOME"):format(name:upper())] = root .. "/" .. name
end
-- Bootstrap lazy
local lazypath = root .. "/plugins/lazy.nvim"
if not vim.loop.fs_stat(lazypath) then
vim.fn.system({
"git",
"clone",
"--filter=blob:none",
"--single-branch",
"https://github.com/folke/lazy.nvim.git",
lazypath,
})
end
vim.opt.runtimepath:prepend(lazypath)
vim.opt.sessionoptions = "buffers,curdir,folds,globals,tabpages,winpos,winsize" -- Session options to store in the session
-- Install plugins
local plugins = {
{
"olimorris/persisted.nvim",
opts = {
-- Your custom config here
}
},
-- Put any other plugins here
}
require("lazy").setup(plugins, {
root = root .. "/plugins",
})
No response
I found that when autoload=true
, neovim's startup time becomes significantly longer.
After troubleshooting, I found that this was because of the git command
As for why the startup time increased so much, it's because I'm using pwsh
as the shell:
vim.opt.shell = "pwsh -NoLogo"
If comment out the above, that is, use the windows default shell:
Then I checked the autoload
function and found that if the get_branch
function was changed from:
function M.get_branch()
vim.fn.system([[git rev-parse 2> /dev/null]])
local git_enabled = (vim.v.shell_error == 0)
if config.options.use_git_branch and git_enabled then
local branch = vim.fn.systemlist([[git rev-parse --abbrev-ref HEAD 2>/dev/null]])
...
to
function M.get_branch()
if config.options.use_git_branch then
vim.fn.system([[git rev-parse 2> /dev/null]])
local git_enabled = (vim.v.shell_error == 0)
if git_enabled then
local branch = vim.fn.systemlist([[git rev-parse --abbrev-ref HEAD 2>/dev/null]])
...
Then the startup time is normal:
Therefore, I think this code should be changed.
No response
minimal.lua
config file above and still get the issueSessionSave
to save the session before restarting Neovim and using SessionLoad
minimal.lua
configCopy paste of the above config, no configurations
local root = "/tmp/persisted"
-- Set stdpaths to use root dir
for _, name in ipairs({ "config", "data", "state", "cache" }) do
vim.env[("XDG_%s_HOME"):format(name:upper())] = root .. "/" .. name
end
-- Bootstrap lazy
local lazypath = root .. "/plugins/lazy.nvim"
if not vim.loop.fs_stat(lazypath) then
vim.fn.system({
"git",
"clone",
"--filter=blob:none",
"--single-branch",
"https://github.com/folke/lazy.nvim.git",
lazypath,
})
end
vim.opt.runtimepath:prepend(lazypath)
vim.opt.sessionoptions = "buffers,curdir,folds,globals,tabpages,winpos,winsize" -- Session options to store in the session
-- Install plugins
local plugins = {
{
"olimorris/persisted.nvim",
opts = {
-- Your custom config here
}
},
-- Put any other plugins here
}
require("lazy").setup(plugins, {
root = root .. "/plugins",
})
no error message
The autosave
feature doesn't function if no session file exists initially. To enable autosave for a directory, you need to manually create a sessions file by running :SessionSave
. Once this file is in place, autosave operates as expected.
However, when opening Neovim without a file and subsequently closing it, an empty session file is automatically generated, allowing autoload to function correctly thereafter.
nvim --clean -u minimal.lua minimal.lua
:q
nvim
:SessionLoad
minimal.lua
config file above and still get the issueSessionSave
to save the session before restarting Neovim and using SessionLoad
Hello!
I ran a PackerSync
and now or some reason I keep getting the below error when trying to reinstate a session:
[persisted.nvim]: Error loading the session! Vim(normal):E19: Mark has invalid line number
or sometimes I don't get the error but all I get are blank windows where my files used to be.
persisted.nvim/lua/persisted/utils.lua
Lines 52 to 60 in 03f11b5
persisted.nvim/lua/persisted/init.lua
Lines 200 to 235 in fb8b3b4
:gsub(save_dir, "")
can fail if session or save_dir contains lua special characters. There's an explanation on s/o about this with a nifty function to handle the substitution: https://stackoverflow.com/a/29379912
The following change works for me and includes an improvement to get the paths displayed properly on windows os:
local function replace(str, what, with, repl)
what = string.gsub(what, "[%(%)%.%+%-%*%?%[%]%^%$%%]", "%%%1") -- escape pattern
with = string.gsub(with, "[%%]", "%%%%") -- escape replacement
return string.gsub(str, what, with, repl)
end
---List all of the sessions
---@return table
function M.list()
local save_dir = config.options.save_dir
local session_files = vim.fn.glob(save_dir .. "*.vim", true, true)
local branch_separator = config.options.branch_separator
local sessions = {}
for _, session in pairs(session_files) do
local session_name = replace(session, save_dir, "")
-- :gsub(save_dir, "")
:gsub("%%", utils.get_dir_pattern())
:gsub(vim.fn.expand("~"), utils.get_dir_pattern())
:gsub("//", "")
:gsub("//", "")
:sub(1, -5)
if vim.fn.has("win32") == 1 then
-- format drive letter (no trailing separator)
session_name = replace(session_name, utils.get_dir_pattern(), ":", 1)
-- format filepath separator
session_name = replace(session_name, utils.get_dir_pattern(), "\\")
end
local branch, dir_path
if string.find(session_name, branch_separator, 1, true) then
local splits = vim.split(session_name, branch_separator, { plain = true })
branch = table.remove(splits, #splits)
dir_path = vim.fn.join(splits, branch_separator)
else
dir_path = session_name
end
table.insert(sessions, {
["name"] = session_name,
["file_path"] = session,
["branch"] = branch,
["dir_path"] = dir_path,
})
end
return sessions
end
If this is acceptable, I can submit a PR.
I am trying out this plugin after auto-session, I would like to have the functionality of choosing the directories I want to save session for, or specifying the directories I don't want to save the session for.
When I open a file (i.e., using nvim foo.txt
), the session autoloads and the desired file is not displayed. Would it be possible to prevent autoloading when a file or directory is explicitly passed to neovim?
Thanks!
As discussed in #2, it would be nice to enable auto-loading of sessions.
As this will disrupt a lot of startup screen plugins, it should be disabled by default.
I set vim.o.cmdheight=2
in my init.lua
and the cmdheight
is 2 when enter the nvim. But it will be set to 1 after open session (by SessionLoad
).
Before SessionLoad
, :verb set cmdheight
shows,
cmdheight=2
Last set from Lua
After SessionLoad
, :verb set cmdheight
shows,
cmdheight=1
Last set from Lua
Notice: When a session saved two or more buffers, cmdheight will be set to 1. If a session saved only 1 buffer, the cmdheight
is still be 2.
I have disabled all plugins except persisted.nvim. So I am sure this issue is related with persisted.nvim.
The cmdheight
won't be set to 1 when open files directly with nvim file
and nvim -o file1 file2
.
nvim version: NVIM v0.8.0 Build type: Release LuaJIT 2.1.0-beta3
persisted.nvim version: commit 587b90b
My persisted.nvim options:
{
silent = false, -- silent nvim message when sourcing session file
use_git_branch = true, -- create session files based on the branch of the git enabled repository
autosave = true, -- automatically save session files when exiting Neovim
}
My sessionoptions
vim option: curdir,folds,tabpages,winpos
For example, it is the sesssion file which saved two buffers.
let SessionLoad = 1
let s:so_save = &g:so | let s:siso_save = &g:siso | setg so=0 siso=0 | setl so=-1 siso=-1
let v:this_session=expand("<sfile>:p")
silent only
silent tabonly
cd ~/.local/share/nvim/plugins/trouble.nvim
if expand('%') == '' && !&modified && line('$') <= 1 && getline(1) == ''
let s:wipebuf = bufnr('%')
endif
let s:shortmess_save = &shortmess
if &shortmess =~ 'A'
set shortmess=aoOA
else
set shortmess=aoO
endif
badd +0 README.md
badd +0 CHANGELOG.md
argglobal
%argdel
edit CHANGELOG.md
let s:save_splitbelow = &splitbelow
let s:save_splitright = &splitright
set splitbelow splitright
wincmd _ | wincmd |
split
1wincmd k
wincmd w
let &splitbelow = s:save_splitbelow
let &splitright = s:save_splitright
wincmd t
let s:save_winminheight = &winminheight
let s:save_winminwidth = &winminwidth
set winminheight=0
set winheight=1
set winminwidth=0
set winwidth=1
wincmd =
argglobal
balt README.md
setlocal fdm=manual
setlocal fde=0
setlocal fmr={{{,}}}
setlocal fdi=#
setlocal fdl=0
setlocal fml=1
setlocal fdn=20
setlocal fen
silent! normal! zE
let &fdl = &fdl
let s:l = 3 - ((2 * winheight(0) + 9) / 18)
if s:l < 1 | let s:l = 1 | endif
keepjumps exe s:l
normal! zt
keepjumps 3
normal! 0
wincmd w
argglobal
if bufexists(fnamemodify("README.md", ":p")) | buffer README.md | else | edit README.md | endif
if &buftype ==# 'terminal'
silent file README.md
endif
balt CHANGELOG.md
setlocal fdm=manual
setlocal fde=0
setlocal fmr={{{,}}}
setlocal fdi=#
setlocal fdl=0
setlocal fml=1
setlocal fdn=20
setlocal fen
silent! normal! zE
let &fdl = &fdl
let s:l = 1 - ((0 * winheight(0) + 9) / 18)
if s:l < 1 | let s:l = 1 | endif
keepjumps exe s:l
normal! zt
keepjumps 1
normal! 0
wincmd w
wincmd =
tabnext 1
if exists('s:wipebuf') && len(win_findbuf(s:wipebuf)) == 0 && getbufvar(s:wipebuf, '&buftype') isnot# 'terminal'
silent exe 'bwipe ' . s:wipebuf
endif
unlet! s:wipebuf
set winheight=1 winwidth=20
let &shortmess = s:shortmess_save
let &winminheight = s:save_winminheight
let &winminwidth = s:save_winminwidth
let s:sx = expand("<sfile>:p:r")."x.vim"
if filereadable(s:sx)
exe "source " . fnameescape(s:sx)
endif
let &g:so = s:so_save | let &g:siso = s:siso_save
set hlsearch
nohlsearch
doautoall SessionLoadPost
unlet SessionLoad
" vim: set ft=vim :
Hello. Is it possible to load session which is associated with current folder with nvim -S
like in obsession?
Off the back of #46 something I'm trying to get in order to reach the goal that is a copy of the emacs-dashboard is the ability to load a session on demand without going through the telescope picker i.e. to have a list of session names and then load of those with just the name. I noticed a utils.load
but this seems to be the raw logic and perhaps is not intended for use externally?
A command like SessionLoad name/of/my/session@@branch
which correctly loads the session just like the telescope plugin does would be ideal.
I've noticed that if I have a repository with a package.json
file with no license, then persisted
stores the git branch name as:
warning package.json: No license field
This is because when the get_branch()
function is called and currently it picks up the second line of output from the git rev-parse --abbrev-ref HEAD
command, which is the warning message. The plugin should actually pick up the last line from the output.
Thanks for the plugin! Unfotunately, I have some problems with it.
Is the issue #10 really resolved? I have just installed this plugin and have this problem while calling SessionLoadLast
:
E5108: Error executing lua .../pack/packer/start/persisted.nvim/lua/persisted/init.lua:48: attempt to concatenate field 'dir' (a nil value)
stack traceback:
.../pack/packer/start/persisted.nvim/lua/persisted/init.lua:48: in function 'get_last'
.../pack/packer/start/persisted.nvim/lua/persisted/init.lua:105: in function 'load'
[string ":lua"]:1: in main chunk
Persisted related part of packer config:
-- * Session management.
use({
'olimorris/persisted.nvim',
--module = "persisted", -- For lazy loading
config = [[ require('config.persisted') ]],
});
Persisted config:
local prequire = require('utils').prequire;
local persisted_status_is_ok, persisted = prequire("persisted");
if not persisted_status_is_ok then
return;
end
--local ENV = require('global');
persisted.setup({
-- Unfortunately, SessionLoadLast doesn't work with save_dir even though it's
-- newer.
--save_dir = ENV.NVIM_DATA .. '/sessions/', -- directory where session files are saved
--dir = ENV.NVIM_DATA .. '/sessions/', -- directory where session files are saved
save_dir = vim.fn.expand(vim.fn.stdpath("data") .. "/sessions/"),
--dir = vim.fn.expand(vim.fn.stdpath("data") .. "/sessions/"),
--command = 'VimLeavePre', -- the autocommand for which the session is saved
--use_git_branch = true, -- create session files based on the branch of the git enabled repository
--autosave = true, -- automatically save session files when exiting Neovim
--autoload = false, -- automatically load the session for the cwd on Neovim startup
--allowed_dirs = nil, -- table of dirs that the plugin will auto-save and auto-load from
--ignored_dirs = nil, -- table of dirs that are ignored when auto-saving and auto-loading
--before_save = function() end, -- function to run before the session is saved to disk
--after_save = function() end, -- function to run after the session is saved to disk
--telescope = { -- options for the telescope extension
--before_source = function(session) end, -- function to run before the session is sourced via telescope
--after_source = function(session) end, -- function to run after the session is sourced via telescope
--},
});
-- To load the telescope extension.
local telescope_status_is_ok, telescope = prequire("telescope");
if not telescope_status_is_ok then
return;
end
telescope.load_extension("persisted");
prequire
is likepcall
but withnvim.notify
for errors, nothing fancy.
As you can see config is default. However, if I set the dir
instead of save_dir
everything will start working (just as it's written in the error message).
This bug is easy to dissect but quite upsetting to get after installing the plugin, hope it will be fixed!
local root = "/tmp/persisted"
-- Set stdpaths to use root dir
for _, name in ipairs({ "config", "data", "state", "cache" }) do
vim.env[("XDG_%s_HOME"):format(name:upper())] = root .. "/" .. name
end
-- Bootstrap lazy
local lazypath = root .. "/plugins/lazy.nvim"
if not vim.loop.fs_stat(lazypath) then
vim.fn.system({
"git",
"clone",
"--filter=blob:none",
"--single-branch",
"https://github.com/folke/lazy.nvim.git",
lazypath,
})
end
vim.opt.runtimepath:prepend(lazypath)
vim.opt.sessionoptions = "buffers,curdir,folds,globals,tabpages,winpos,winsize" -- Session options to store in the session
-- Install plugins
local plugins = {
{
"olimorris/persisted.nvim",
opts = {
"olimorris/persisted.nvim",
event = "VimEnter",
keys = {
{ "<leader>ss", "<cmd>SessionSave<cr>", desc = "Save" },
{ "<leader>sl", "<cmd>SessionLoad<cr>", desc = "Load" },
},
config = true,
opts = {
save_dir = vim.fn.expand(vim.fn.stdpath("data") .. "/sessions/"),
command = "",
silent = false,
use_git_branch = true,
branch_separator = "_",
autosave = false,
autoload = false,
}
},
-- Put any other plugins here
}
require("lazy").setup(plugins, {
root = root .. "/plugins",
})
There are no error messages.
SessionSave
and SessionLoad
commands are currently not working.
I followed your instructions with minimal.lua
and tried to open some files, run SessionSave
, quit NVim and run SessionLoad
, but nothing is happens. I don't get errors or any message that could help me further.
Could you help me with that.
minimal.lua
with my configuration dataminimal.lua
SessionSave
minimal.lua
SessionLoad
minimal.lua
config file above and still get the issueSessionSave
to save the session before restarting Neovim and using SessionLoad
I see that you use save_dir
in the example, and I read your code, you use both save_dir
and dir
but the save_dir
doesn't work for me and dir works fine. I know that you've just rename dir
to save_dir
but seem like there's a bug here?
Below are a collection of callbacks which you may find useful.
How to show notify window after source? I configured as follows:
require("persisted").setup({
telescope = {
after_source = function(session)
vim.notify("Loaded session " .. session.name
end,
},
})
After the session is sourced via telescope, it seems notify window not showed. Even thought the notify history is there.
How to show that window?
PS:
If I configured like this:
require("persisted").setup({
after_source = function()
vim.notify("Loaded session")
end,
})
Notification window is showed after sourcing cwd session or last session (without picked session thru telescope).
Thanks for your work on this plugin, it's awesome.
I just have one issue when a session is restored.
On the opened focused buffer, LSP is not running.
I have to close the buffer and reopen it.
The other opened buffers are fine tho.
I don't know what could cause such behavior.
Any help is appreciated :)
My default telescope config:
layout_config = {
vertical = {
height = { 0.8, min = 30, max = 80 },
width = { 0.8, min = 80, max = 130 }
}
}
persisted telescope extension will throw an error.
The extension should use the resolver.resolve_width()
.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.