Compare commits

..

No commits in common. "main" and "v1.0.1" have entirely different histories.
main ... v1.0.1

20 changed files with 295 additions and 403 deletions

View File

@ -1,7 +0,0 @@
root = true
[*]
insert_final_newline = true
indent_style = space
indent_size = 2
charset = utf-8

View File

@ -6,10 +6,7 @@ body:
- type: markdown - type: markdown
attributes: attributes:
value: | value: |
**Before** reporting an issue, make sure to read the [documentation](https://github.com/folke/persistence.nvim) **Before** reporting an issue, make sure to read the [documentation](https://github.com/folke/persistence.nvim) and search [existing issues](https://github.com/folke/persistence.nvim/issues). Usage questions such as ***"How do I...?"*** belong in [Discussions](https://github.com/folke/persistence.nvim/discussions) and will be closed.
and search [existing issues](https://github.com/folke/persistence.nvim/issues).
Usage questions such as ***"How do I...?"*** belong in [Discussions](https://github.com/folke/persistence.nvim/discussions) and will be closed.
- type: checkboxes - type: checkboxes
attributes: attributes:
label: Did you check docs and existing issues? label: Did you check docs and existing issues?
@ -17,11 +14,9 @@ body:
options: options:
- label: I have read all the persistence.nvim docs - label: I have read all the persistence.nvim docs
required: true required: true
- label: I have updated the plugin to the latest version before submitting this issue
required: true
- label: I have searched the existing issues of persistence.nvim - label: I have searched the existing issues of persistence.nvim
required: true required: true
- label: I have searched the existing issues of plugins related to this issue - label: I have searched the exsiting issues of plugins related to this issue
required: true required: true
- type: input - type: input
attributes: attributes:
@ -62,15 +57,32 @@ body:
label: Repro label: Repro
description: Minimal `init.lua` to reproduce this issue. Save as `repro.lua` and run with `nvim -u repro.lua` description: Minimal `init.lua` to reproduce this issue. Save as `repro.lua` and run with `nvim -u repro.lua`
value: | value: |
vim.env.LAZY_STDPATH = ".repro" -- DO NOT change the paths and don't remove the colorscheme
load(vim.fn.system("curl -s https://raw.githubusercontent.com/folke/lazy.nvim/main/bootstrap.lua"))() local root = vim.fn.fnamemodify("./.repro", ":p")
-- set stdpaths to use .repro
for _, name in ipairs({ "config", "data", "state", "cache" }) do
vim.env[("XDG_%s_HOME"):format(name:upper())] = root .. "/" .. name
end
require("lazy.minit").repro({ -- bootstrap lazy
spec = { local lazypath = root .. "/plugins/lazy.nvim"
{ "folke/persistence.nvim", opts = {} }, if not vim.loop.fs_stat(lazypath) then
-- add any other plugins here vim.fn.system({ "git", "clone", "--filter=blob:none", "https://github.com/folke/lazy.nvim.git", lazypath, })
}, end
vim.opt.runtimepath:prepend(lazypath)
-- install plugins
local plugins = {
"folke/tokyonight.nvim",
"folke/persistence.nvim",
-- add any other plugins here
}
require("lazy").setup(plugins, {
root = root .. "/plugins",
}) })
render: lua
vim.cmd.colorscheme("tokyonight")
-- add anything else here
render: Lua
validations: validations:
required: false required: false

View File

@ -1,5 +0,0 @@
blank_issues_enabled: false
contact_links:
- name: Ask a question
url: https://github.com/folke/persistence.nvim/discussions
about: Use Github discussions instead

View File

@ -1,16 +0,0 @@
## Description
<!-- Describe the big picture of your changes to communicate to the maintainers
why we should accept this pull request. -->
## Related Issue(s)
<!--
If this PR fixes any issues, please link to the issue here.
- Fixes #<issue_number>
-->
## Screenshots
<!-- Add screenshots of the changes if applicable. -->

View File

@ -1,6 +0,0 @@
version: 2
updates:
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "weekly"

View File

@ -1,14 +1,68 @@
name: CI name: CI
on: on:
push: push:
branches: [main, master]
pull_request: pull_request:
jobs: jobs:
ci: tests:
uses: folke/github/.github/workflows/ci.yml@main strategy:
secrets: inherit matrix:
with: # os: [ubuntu-latest, windows-latest]
plugin: persistence.nvim os: [ubuntu-latest]
repo: folke/persistence.nvim runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v3
- name: Install Neovim
shell: bash
run: |
wget -q https://github.com/neovim/neovim/releases/download/nightly/nvim-linux64.deb -O /tmp/nvim.deb
sudo dpkg -i /tmp/nvim.deb
- name: Run Tests
run: |
nvim --version
[ ! -d tests ] && exit 0
nvim --headless -u tests/init.lua -c "PlenaryBustedDirectory tests/ {minimal_init = 'tests/init.lua', sequential = true}"
docs:
runs-on: ubuntu-latest
needs: tests
if: ${{ github.ref == 'refs/heads/main' }}
steps:
- uses: actions/checkout@v3
- name: panvimdoc
uses: kdheepak/panvimdoc@main
with:
vimdoc: persistence.nvim
version: "Neovim >= 0.8.0"
demojify: true
treesitter: true
- name: Push changes
uses: stefanzweifel/git-auto-commit-action@v4
with:
commit_message: "chore(build): auto-generate vimdoc"
commit_user_name: "github-actions[bot]"
commit_user_email: "github-actions[bot]@users.noreply.github.com"
commit_author: "github-actions[bot] <github-actions[bot]@users.noreply.github.com>"
release:
name: release
if: ${{ github.ref == 'refs/heads/main' }}
needs:
- docs
- tests
runs-on: ubuntu-latest
steps:
- uses: google-github-actions/release-please-action@v3
id: release
with:
release-type: simple
package-name: persistence.nvim
- uses: actions/checkout@v2
- name: tag stable versions
if: ${{ steps.release.outputs.release_created }}
run: |
git config user.name github-actions[bot]
git config user.email github-actions[bot]@users.noreply.github.com
git remote add gh-token "https://${{ secrets.GITHUB_TOKEN }}@github.com/google-github-actions/release-please-action.git"
git tag -d stable || true
git push origin :stable || true
git tag -a stable -m "Last Stable Release"
git push origin stable

View File

@ -1,8 +0,0 @@
name: "PR Labeler"
on:
- pull_request_target
jobs:
labeler:
uses: folke/github/.github/workflows/labeler.yml@main
secrets: inherit

View File

@ -1,18 +0,0 @@
name: PR Title
on:
pull_request_target:
types:
- opened
- edited
- synchronize
- reopened
- ready_for_review
permissions:
pull-requests: read
jobs:
pr-title:
uses: folke/github/.github/workflows/pr.yml@main
secrets: inherit

View File

@ -1,11 +0,0 @@
name: Stale Issues & PRs
on:
schedule:
- cron: "30 1 * * *"
jobs:
stale:
if: contains(fromJSON('["folke", "LazyVim"]'), github.repository_owner)
uses: folke/github/.github/workflows/stale.yml@main
secrets: inherit

View File

@ -1,13 +0,0 @@
name: Update Repo
on:
workflow_dispatch:
schedule:
# Run every hour
- cron: "0 * * * *"
jobs:
update:
if: contains(fromJSON('["folke", "LazyVim"]'), github.repository_owner)
uses: folke/github/.github/workflows/update.yml@main
secrets: inherit

15
.gitignore vendored
View File

@ -1,9 +1,8 @@
*.log
/.repro
/.tests
/build
/debug
/doc/tags
foo.*
node_modules
tt.* tt.*
.tests
doc/tags
debug
.repro
foo.*
*.log
data

View File

@ -1,79 +1,5 @@
# Changelog # Changelog
## [3.1.0](https://github.com/folke/persistence.nvim/compare/v3.0.1...v3.1.0) (2024-07-07)
### Features
* **load:** fallback to regular session when branch session does not exist (yet) ([a93748a](https://github.com/folke/persistence.nvim/commit/a93748acdb2e7bc4389b3738b4c787b764c3b2a6))
## [3.0.1](https://github.com/folke/persistence.nvim/compare/v3.0.0...v3.0.1) (2024-07-07)
### Bug Fixes
* branch detection. Closes [#62](https://github.com/folke/persistence.nvim/issues/62) ([a1d37fa](https://github.com/folke/persistence.nvim/commit/a1d37fa32ef9431f6a57c217ba5c456d20834679))
* **branch:** escape branch name. Fixes [#65](https://github.com/folke/persistence.nvim/issues/65) ([1565ca0](https://github.com/folke/persistence.nvim/commit/1565ca0af2d93ee94335c2950d92bc133c90aa82))
* windows ([2d83b1a](https://github.com/folke/persistence.nvim/commit/2d83b1a5c3fe5b2251866f5263fb9607db8d64c0))
## [3.0.0](https://github.com/folke/persistence.nvim/compare/v2.0.0...v3.0.0) (2024-07-06)
### ⚠ BREAKING CHANGES
* opts.need specifieds how many buffers should be open for saving. Replaces save_empty. Closes #19
* removed load_pre/load_post/save_pre/save_post in favor of events. Check the readme
* removed `opts.options`. Use `vim.o.sessionoptions` instead.
### Features
* added `require("persistence").select()` to select a session to load ([5346b53](https://github.com/folke/persistence.nvim/commit/5346b5346a2dd1732ae84f05251ecb704f35df87))
* opts.need specifieds how many buffers should be open for saving. Replaces save_empty. Closes [#19](https://github.com/folke/persistence.nvim/issues/19) ([7bb5755](https://github.com/folke/persistence.nvim/commit/7bb575517cebbc2b172caa04581dc5d91be90136))
* persistence.active. Check if a session saving is active ([f0ac0e9](https://github.com/folke/persistence.nvim/commit/f0ac0e981e4c864df11e613636a23c5bad09376d))
* **persistence:** add `pre-` and `post-` load hooks ([#24](https://github.com/folke/persistence.nvim/issues/24)) ([3d443bd](https://github.com/folke/persistence.nvim/commit/3d443bd0a7e1d9eebfa37321fc8118d8d538af13))
* removed `opts.options`. Use `vim.o.sessionoptions` instead. ([eb5622e](https://github.com/folke/persistence.nvim/commit/eb5622edae69ec65f6f83fcdd0eb5a70ce48ece7))
* removed load_pre/load_post/save_pre/save_post in favor of events. Check the readme ([f58a838](https://github.com/folke/persistence.nvim/commit/f58a838282dac1ed33165a5fd03829b036584df2))
* sessions per branch. Closes [#9](https://github.com/folke/persistence.nvim/issues/9) ([cd0054e](https://github.com/folke/persistence.nvim/commit/cd0054e6a4c17e4068a3e69a030013d268e569f9))
### Bug Fixes
* don't save `gitrebase` session ([#44](https://github.com/folke/persistence.nvim/issues/44)) ([9dbe264](https://github.com/folke/persistence.nvim/commit/9dbe2648c67b678bf7fe688f03b57a2514e03e6f))
* opts.need ([9c0e522](https://github.com/folke/persistence.nvim/commit/9c0e5227fa7b36208a2db0d812008965c1aac889))
* remove expand() as stdpath() expands itself ([#50](https://github.com/folke/persistence.nvim/issues/50)) ([a2fd3d9](https://github.com/folke/persistence.nvim/commit/a2fd3d99656ac496e56233aa4a40dd045a16fdc4))
## [2.0.0](https://github.com/folke/persistence.nvim/compare/v1.2.1...v2.0.0) (2023-10-15)
### ⚠ BREAKING CHANGES
* **start:** session name is now based on the cwd when the session starts and not when the session ends. Fixes #1688
### Bug Fixes
* **start:** session name is now based on the cwd when the session starts and not when the session ends. Fixes [#1688](https://github.com/folke/persistence.nvim/issues/1688) ([0361df7](https://github.com/folke/persistence.nvim/commit/0361df7775f5b4ed51a6d7fe159438573b7f07a6))
## [1.2.1](https://github.com/folke/persistence.nvim/compare/v1.2.0...v1.2.1) (2023-10-13)
### Bug Fixes
* dont save the session when only `gitcommit` buffers are present. Fixes [#14](https://github.com/folke/persistence.nvim/issues/14) ([8f7cbcc](https://github.com/folke/persistence.nvim/commit/8f7cbccfb506fe6cb35db9ad966137c363b049c5))
## [1.2.0](https://github.com/folke/persistence.nvim/compare/v1.1.0...v1.2.0) (2023-10-13)
### Features
* don't save the session when no files are open (save_empty = false) ([e9afeaf](https://github.com/folke/persistence.nvim/commit/e9afeaf3a7bb645ca73980cd13048c48c292500c))
## [1.1.0](https://github.com/folke/persistence.nvim/compare/v1.0.1...v1.1.0) (2023-02-28)
### Features
* **persistence:** `pre_save` option to call before saving ([#22](https://github.com/folke/persistence.nvim/issues/22)) ([f4bb0c5](https://github.com/folke/persistence.nvim/commit/f4bb0c5641a0e6c9ac3675ddd794ca78099d8510))
## [1.0.1](https://github.com/folke/persistence.nvim/compare/v1.0.0...v1.0.1) (2023-01-06) ## [1.0.1](https://github.com/folke/persistence.nvim/compare/v1.0.0...v1.0.1) (2023-01-06)

View File

@ -4,7 +4,7 @@
## ✨ Features ## ✨ Features
- automatically saves the active session under `~/.local/state/nvim/sessions` on exit - automatically saves the active session under `.config/nvim/sessions` on exit
- simple API to restore the current or last session - simple API to restore the current or last session
## ⚡️ Requirements ## ⚡️ Requirements
@ -15,17 +15,33 @@
Install the plugin with your preferred package manager: Install the plugin with your preferred package manager:
### [lazy.nvim](https://github.com/folke/lazy.nvim) ### [packer](https://github.com/wbthomason/packer.nvim)
```lua ```lua
-- Lua -- Lua
{ use({
"folke/persistence.nvim", "folke/persistence.nvim",
event = "BufReadPre", -- this will only start session saving when an actual file was opened event = "BufReadPre", -- this will only start session saving when an actual file was opened
opts = { module = "persistence",
-- add any custom options here config = function()
require("persistence").setup()
end,
})
```
### [vim-plug](https://github.com/junegunn/vim-plug)
```vim
" Vim Script
Plug 'folke/persistence.nvim'
lua << EOF
require("persistence").setup {
-- your configuration comes here
-- or leave it empty to use the default settings
-- refer to the configuration section below
} }
} EOF
``` ```
## ⚙️ Configuration ## ⚙️ Configuration
@ -34,39 +50,23 @@ Persistence comes with the following defaults:
```lua ```lua
{ {
dir = vim.fn.stdpath("state") .. "/sessions/", -- directory where session files are saved dir = vim.fn.expand(vim.fn.stdpath("state") .. "/sessions/"), -- directory where session files are saved
-- minimum number of file buffers that need to be open to save options = { "buffers", "curdir", "tabpages", "winsize" }, -- sessionoptions used for saving
-- Set to 0 to always save
need = 1,
branch = true, -- use git branch to save session
} }
``` ```
> [!TIP]
> To configure what should be saved in your session, check [:h 'sessionoptions'](https://neovim.io/doc/user/options.html#'sessionoptions')
## 🚀 Usage ## 🚀 Usage
**Persistence** works well with plugins like `startify` or `dashboard`. It will never restore a session automatically, **Persistence** works well with plugins like `startify` or `dashboard`. It will never restore a session automatically,
but you can of course write an autocmd that does exactly that if you want. but you can of course write an autocmd that does exactly that if you want.
```lua ```lua
-- load the session for the current directory -- restore the session for the current directory
vim.keymap.set("n", "<leader>qs", function() require("persistence").load() end) vim.api.nvim_set_keymap("n", "<leader>qs", [[<cmd>lua require("persistence").load()<cr>]], {})
-- select a session to load -- restore the last session
vim.keymap.set("n", "<leader>qS", function() require("persistence").select() end) vim.api.nvim_set_keymap("n", "<leader>ql", [[<cmd>lua require("persistence").load({ last = true })<cr>]], {})
-- load the last session
vim.keymap.set("n", "<leader>ql", function() require("persistence").load({ last = true }) end)
-- stop Persistence => session won't be saved on exit -- stop Persistence => session won't be saved on exit
vim.keymap.set("n", "<leader>qd", function() require("persistence").stop() end) vim.api.nvim_set_keymap("n", "<leader>qd", [[<cmd>lua require("persistence").stop()<cr>]], {})
``` ```
## 📅 Events
- **PersistenceLoadPre**: before loading a session
- **PersistenceLoadPost**: after loading a session
- **PersistenceSavePre**: before saving a session
- **PersistenceSavePost**: after saving a session

View File

@ -1,98 +1,98 @@
*persistence.nvim.txt* For Neovim Last change: 2025 February 25 *persistence.nvim.txt* For Neovim >= 0.8.0 Last change: 2023 January 06
============================================================================== ==============================================================================
Table of Contents *persistence.nvim-table-of-contents* Table of Contents *persistence.nvim-table-of-contents*
1. Persistence |persistence.nvim-persistence| 1. Persistence |persistence.nvim-persistence|
- Features |persistence.nvim-persistence-features| - Features |persistence.nvim-features|
- Requirements |persistence.nvim-persistence-requirements| - Requirements |persistence.nvim-requirements|
- Installation |persistence.nvim-persistence-installation| - Installation |persistence.nvim-installation|
- Configuration |persistence.nvim-persistence-configuration| - Configuration |persistence.nvim-configuration|
- Usage |persistence.nvim-persistence-usage| - Usage |persistence.nvim-usage|
- Events |persistence.nvim-persistence-events|
============================================================================== ==============================================================================
1. Persistence *persistence.nvim-persistence* 1. Persistence *persistence.nvim-persistence*
**Persistence** is a simple lua plugin for automated session management. **Persistence** is a simple lua plugin for automated session management.
FEATURES *persistence.nvim-features*
FEATURES *persistence.nvim-persistence-features*
- automatically saves the active session under `~/.local/state/nvim/sessions` on exit - automatically saves the active session under `.config/nvim/sessions` on exit
- simple API to restore the current or last session - simple API to restore the current or last session
REQUIREMENTS *persistence.nvim-persistence-requirements* REQUIREMENTS *persistence.nvim-requirements*
- Neovim >= 0.7.2 - Neovim >= 0.7.2
INSTALLATION *persistence.nvim-persistence-installation* INSTALLATION *persistence.nvim-installation*
Install the plugin with your preferred package manager: Install the plugin with your preferred package manager:
PACKER <HTTPS://GITHUB.COM/WBTHOMASON/PACKER.NVIM> ~
LAZY.NVIM ~
>lua >lua
-- Lua -- Lua
{ use({
"folke/persistence.nvim", "folke/persistence.nvim",
event = "BufReadPre", -- this will only start session saving when an actual file was opened event = "BufReadPre", -- this will only start session saving when an actual file was opened
opts = { module = "persistence",
-- add any custom options here config = function()
} require("persistence").setup()
} end,
})
< <
CONFIGURATION *persistence.nvim-persistence-configuration* VIM-PLUG <HTTPS://GITHUB.COM/JUNEGUNN/VIM-PLUG> ~
>vim
" Vim Script
Plug 'folke/persistence.nvim'
lua << EOF
require("persistence").setup {
-- your configuration comes here
-- or leave it empty to use the default settings
-- refer to the configuration section below
}
EOF
<
CONFIGURATION *persistence.nvim-configuration*
Persistence comes with the following defaults: Persistence comes with the following defaults:
>lua >lua
{ {
dir = vim.fn.stdpath("state") .. "/sessions/", -- directory where session files are saved dir = vim.fn.expand(vim.fn.stdpath("state") .. "/sessions/"), -- directory where session files are saved
-- minimum number of file buffers that need to be open to save options = { "buffers", "curdir", "tabpages", "winsize" }, -- sessionoptions used for saving
-- Set to 0 to always save
need = 1,
branch = true, -- use git branch to save session
} }
< <
[!TIP] To configure what should be saved in your session, check |:h USAGE *persistence.nvim-usage*
'sessionoptions'|
USAGE *persistence.nvim-persistence-usage*
**Persistence** works well with plugins like `startify` or `dashboard`. It will **Persistence** works well with plugins like `startify` or `dashboard`. It will
never restore a session automatically, but you can of course write an autocmd never restore a session automatically, but you can of course write an autocmd
that does exactly that if you want. that does exactly that if you want.
>lua >lua
-- load the session for the current directory -- restore the session for the current directory
vim.keymap.set("n", "<leader>qs", function() require("persistence").load() end) vim.api.nvim_set_keymap("n", "<leader>qs", [[<cmd>lua require("persistence").load()<cr>]], {})
-- select a session to load -- restore the last session
vim.keymap.set("n", "<leader>qS", function() require("persistence").select() end) vim.api.nvim_set_keymap("n", "<leader>ql", [[<cmd>lua require("persistence").load({ last = true })<cr>]], {})
-- load the last session
vim.keymap.set("n", "<leader>ql", function() require("persistence").load({ last = true }) end)
-- stop Persistence => session won't be saved on exit -- stop Persistence => session won't be saved on exit
vim.keymap.set("n", "<leader>qd", function() require("persistence").stop() end) vim.api.nvim_set_keymap("n", "<leader>qd", [[<cmd>lua require("persistence").stop()<cr>]], {})
< <
EVENTS *persistence.nvim-persistence-events*
- **PersistenceLoadPre**before loading a session
- **PersistenceLoadPost**after loading a session
- **PersistenceSavePre**before saving a session
- **PersistenceSavePost**after saving a session
Generated by panvimdoc <https://github.com/kdheepak/panvimdoc> Generated by panvimdoc <https://github.com/kdheepak/panvimdoc>
vim:tw=78:ts=8:noet:ft=help:norl: vim:tw=78:ts=8:noet:ft=help:norl:

98
doc/persistence.txt Normal file
View File

@ -0,0 +1,98 @@
*persistence.txt* For NVIM v0.8.0 Last change: 2023 January 04
==============================================================================
Table of Contents *persistence-table-of-contents*
1. 💾 Persistence |persistence-💾-persistence|
- ✨ Features |persistence-✨-features|
- ⚡️ Requirements |persistence-⚡️-requirements|
- 📦 Installation |persistence-📦-installation|
- ⚙️ Configuration |persistence-⚙️-configuration|
- 🚀 Usage |persistence-🚀-usage|
==============================================================================
1. 💾 Persistence *persistence-💾-persistence*
**Persistence** is a simple lua plugin for automated session management.
✨ FEATURES *persistence-✨-features*
- automatically saves the active session under `.config/nvim/sessions` on exit
- simple API to restore the current or last session
⚡️ REQUIREMENTS *persistence-⚡️-requirements*
- Neovim >= 0.5.0
📦 INSTALLATION *persistence-📦-installation*
Install the plugin with your preferred package manager:
PACKER <HTTPS://GITHUB.COM/WBTHOMASON/PACKER.NVIM> ~
>
-- Lua
use({
"folke/persistence.nvim",
event = "BufReadPre", -- this will only start session saving when an actual file was opened
module = "persistence",
config = function()
require("persistence").setup()
end,
})
<
VIM-PLUG <HTTPS://GITHUB.COM/JUNEGUNN/VIM-PLUG> ~
>
" Vim Script
Plug 'folke/persistence.nvim'
lua << EOF
require("persistence").setup {
-- your configuration comes here
-- or leave it empty to use the default settings
-- refer to the configuration section below
}
EOF
<
⚙️ CONFIGURATION *persistence-⚙️-configuration*
Persistence comes with the following defaults:
>
{
dir = vim.fn.expand(vim.fn.stdpath("state") .. "/sessions/"), -- directory where session files are saved
options = { "buffers", "curdir", "tabpages", "winsize" }, -- sessionoptions used for saving
}
<
🚀 USAGE *persistence-🚀-usage*
**Persistence** works well with plugins like `startify` or `dashboard`. It will
never restore a session automatically, but you can of course write an autocmd
that does exactly that if you want.
>
-- restore the session for the current directory
vim.api.nvim_set_keymap("n", "<leader>qs", [[<cmd>lua require("persistence").load()<cr>]], {})
-- restore the last session
vim.api.nvim_set_keymap("n", "<leader>ql", [[<cmd>lua require("persistence").load({ last = true })<cr>]], {})
-- stop Persistence => session won't be saved on exit
vim.api.nvim_set_keymap("n", "<leader>qd", [[<cmd>lua require("persistence").stop()<cr>]], {})
<
Generated by panvimdoc <https://github.com/kdheepak/panvimdoc>
vim:tw=78:ts=8:noet:ft=help:norl:

View File

@ -1,15 +1,12 @@
local M = {} local M = {}
---@class Persistence.Config ---@class PersistenceOptions
local defaults = { local defaults = {
dir = vim.fn.stdpath("state") .. "/sessions/", -- directory where session files are saved dir = vim.fn.expand(vim.fn.stdpath("state") .. "/sessions/"), -- directory where session files are saved
-- minimum number of file buffers that need to be open to save options = { "buffers", "curdir", "tabpages", "winsize" }, -- sessionoptions used for saving
-- Set to 0 to always save
need = 1,
branch = true, -- use git branch to save session
} }
---@type Persistence.Config ---@type PersistenceOptions
M.options = {} M.options = {}
function M.setup(opts) function M.setup(opts)

View File

@ -1,146 +1,61 @@
local Config = require("persistence.config") local Config = require("persistence.config")
local uv = vim.uv or vim.loop
local M = {} local M = {}
M._active = false
local e = vim.fn.fnameescape local e = vim.fn.fnameescape
---@param opts? {branch?: boolean} function M.get_current()
function M.current(opts) local pattern = "/"
opts = opts or {} if vim.fn.has("win32") == 1 then
local name = vim.fn.getcwd():gsub("[\\/:]+", "%%") pattern = "[\\:]"
if Config.options.branch and opts.branch ~= false then
local branch = M.branch()
if branch and branch ~= "main" and branch ~= "master" then
name = name .. "%%" .. branch:gsub("[\\/:]+", "%%")
end
end end
local name = vim.fn.getcwd():gsub(pattern, "%%")
return Config.options.dir .. name .. ".vim" return Config.options.dir .. name .. ".vim"
end end
function M.get_last()
local sessions = M.list()
table.sort(sessions, function(a, b)
return vim.loop.fs_stat(a).mtime.sec > vim.loop.fs_stat(b).mtime.sec
end)
return sessions[1]
end
function M.setup(opts) function M.setup(opts)
Config.setup(opts) Config.setup(opts)
M.start() M.start()
end end
function M.fire(event)
vim.api.nvim_exec_autocmds("User", {
pattern = "Persistence" .. event,
})
end
-- Check if a session is active
function M.active()
return M._active
end
function M.start() function M.start()
M._active = true
vim.api.nvim_create_autocmd("VimLeavePre", { vim.api.nvim_create_autocmd("VimLeavePre", {
group = vim.api.nvim_create_augroup("persistence", { clear = true }), group = vim.api.nvim_create_augroup("persistence", { clear = true }),
callback = function() callback = function()
M.fire("SavePre")
if Config.options.need > 0 then
local bufs = vim.tbl_filter(function(b)
if vim.bo[b].buftype ~= "" or vim.tbl_contains({ "gitcommit", "gitrebase", "jj" }, vim.bo[b].filetype) then
return false
end
return vim.api.nvim_buf_get_name(b) ~= ""
end, vim.api.nvim_list_bufs())
if #bufs < Config.options.need then
return
end
end
M.save() M.save()
M.fire("SavePost")
end, end,
}) })
end end
function M.stop() function M.stop()
M._active = false
pcall(vim.api.nvim_del_augroup_by_name, "persistence") pcall(vim.api.nvim_del_augroup_by_name, "persistence")
end end
function M.save() function M.save()
vim.cmd("mks! " .. e(M.current())) local tmp = vim.o.sessionoptions
vim.o.sessionoptions = table.concat(Config.options.options, ",")
vim.cmd("mks! " .. e(M.get_current()))
vim.o.sessionoptions = tmp
end end
---@param opts? { last?: boolean } function M.load(opt)
function M.load(opts) opt = opt or {}
opts = opts or {} local sfile = opt.last and M.get_last() or M.get_current()
---@type string if sfile and vim.fn.filereadable(sfile) ~= 0 then
local file vim.cmd("silent! source " .. e(sfile))
if opts.last then
file = M.last()
else
file = M.current()
if vim.fn.filereadable(file) == 0 then
file = M.current({ branch = false })
end
end
if file and vim.fn.filereadable(file) ~= 0 then
M.fire("LoadPre")
vim.cmd("silent! source " .. e(file))
M.fire("LoadPost")
end end
end end
---@return string[]
function M.list() function M.list()
local sessions = vim.fn.glob(Config.options.dir .. "*.vim", true, true) return vim.fn.glob(Config.options.dir .. "*.vim", true, true)
table.sort(sessions, function(a, b)
return uv.fs_stat(a).mtime.sec > uv.fs_stat(b).mtime.sec
end)
return sessions
end
function M.last()
return M.list()[1]
end
function M.select()
---@type { session: string, dir: string, branch?: string }[]
local items = {}
local have = {} ---@type table<string, boolean>
for _, session in ipairs(M.list()) do
if uv.fs_stat(session) then
local file = session:sub(#Config.options.dir + 1, -5)
local dir, branch = unpack(vim.split(file, "%%", { plain = true }))
dir = dir:gsub("%%", "/")
if jit.os:find("Windows") then
dir = dir:gsub("^(%w)/", "%1:/")
end
if not have[dir] then
have[dir] = true
items[#items + 1] = { session = session, dir = dir, branch = branch }
end
end
end
vim.ui.select(items, {
prompt = "Select a session: ",
format_item = function(item)
return vim.fn.fnamemodify(item.dir, ":p:~")
end,
}, function(item)
if item then
vim.fn.chdir(item.dir)
M.load()
end
end)
end
--- get current branch name
---@return string?
function M.branch()
if uv.fs_stat(".git") then
local ret = vim.fn.systemlist("git branch --show-current")[1]
return vim.v.shell_error == 0 and ret or nil
end
end end
return M return M

View File

@ -1,4 +1 @@
std="vim" std="lua51+vim"
[lints]
mixed_table="allow"

View File

@ -1,6 +1,3 @@
indent_type = "Spaces" indent_type = "Spaces"
indent_width = 2 indent_width = 2
column_width = 120 column_width = 120
[sort_requires]
enabled = true

View File

@ -1,21 +1,2 @@
[selene]
base = "lua51"
name = "vim"
[vim] [vim]
any = true any = true
[jit]
any = true
[assert]
any = true
[describe]
any = true
[it]
any = true
[before_each.args]
any = true