Something went wrong. Try again.
Library of 45+ independent Lua modules improving Neovim experience with minimal effort nvim-mini.org/mini.nvim
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279-- General design of testing sessions is to have each session file define-- `_G.session_file` variable with value being path to sourced session. So-- these assumptions are assumed:-- - If `_G.session_file` is `nil`, no session file was sourced.-- - If `_G.session_file` is not `nil`, its value is a relative (to project-- root) path to a session file that was sourced.local helpers = dofile('tests/helpers.lua')
local child = helpers.new_child_neovim()local expect, eq = helpers.expect, helpers.expect.equalitylocal new_set = MiniTest.new_set
local project_root = vim.fs.normalize(vim.fn.getcwd())local empty_dir_relpath = 'tests/dir-sessions/empty'local empty_dir_path = project_root .. '/' .. empty_dir_relpath
-- Helpers with child processeslocal load_module = function(config) child.mini_load('sessions', config) endlocal unload_module = function() child.mini_unload('sessions') endlocal reload_module = function(config) child.mini_reload('sessions', config) endlocal reload_from_strconfig = function(strconfig) child.mini_reload_strconfig('sessions', strconfig) endlocal set_lines = function(...) return child.set_lines(...) endlocal make_path = function(...) return vim.fs.normalize(table.concat({ ... }, '/')) endlocal cd = function(...) child.cmd('cd ' .. make_path(...)) endlocal sleep = function(ms) helpers.sleep(ms, child) end
-- Make helperslocal cleanup_directories = function() -- Cleanup files for directories to have invariant properties -- Ensure 'empty' directory doesn't exist child.fn.delete(empty_dir_path, 'rf')
-- Ensure 'missing-directory' doesn't exist child.fn.delete('tests/dir-sessions/missing-directory', 'rf')
-- Ensure 'global' does not contain file 'Session.vim' local files = { 'tests/dir-sessions/global/Session.vim' }
for _, f in ipairs(files) do child.fn.delete(f) endend
local get_latest_message = function() return child.cmd_capture('1messages') end
local get_buf_names = function() return child.lua_get('vim.tbl_map(function(x) return vim.fn.bufname(x) end, vim.api.nvim_list_bufs())')end
local compare_buffer_names = function(x, y) -- Don't test exact equality because different Neovim versions create -- different buffer order when sourcing session (see -- https://github.com/vim/vim/pull/9520) table.sort(x) table.sort(y) eq(x, y)end
-- Helpers for validating sessionslocal populate_sessions = function(delay) delay = delay or 0
child.fn.delete(empty_dir_path, 'rf') child.fn.mkdir(empty_dir_path)
local make_file = function(name) local path = make_path(empty_dir_path, name) local value = make_path(empty_dir_relpath, name) child.fn.writefile({ ([[lua _G.session_file = '%s']]):format(value) }, path) end
make_file('session_a') -- Modification time is up to seconds, so wait to ensure correct order sleep(delay) make_file('session_b')
return empty_dir_pathend
local validate_session_loaded = function(relative_path) local path = make_path('tests/dir-sessions', relative_path)
-- It should actually source file eq(child.lua_get('_G.session_file'), path)
-- It should set `this_session` eq(child.v.this_session, make_path(project_root, path))end
local validate_no_session_loaded = function() eq(child.lua_get('type(_G.session_file)'), 'nil') end
local reset_session_indicator = function() child.lua('_G.session_file = nil') end
-- Helpers for testing hooks--stylua: ignorelocal make_hook_string = function(pre_post, action, hook_type) if hook_type == 'config' then return string.format( [[{ %s = { %s = function(...) _G.hooks_args = { ... }; _G.hooks_%s_%s = 'config' end }}]], pre_post, action, pre_post, action ) end if hook_type == 'opts' then return string.format( [[{ %s = function(...) _G.hooks_args = { ... }; _G.hooks_%s_%s = 'opts' end }]], pre_post, pre_post, action ) endend
local validate_executed_hook = function(pre_post, action, value) local var_name = ('_G.hooks_%s_%s'):format(pre_post, action) eq(child.lua_get(var_name), value)
-- Only one argument should be passed local hooks_args = child.lua_get('_G.hooks_args') eq(vim.tbl_keys(hooks_args), { 1 })
-- It is a session data local data = hooks_args[1] local keys = vim.tbl_keys(data) table.sort(keys) eq(keys, { 'modify_time', 'name', 'path', 'type' }) eq(vim.tbl_map(function(x) return type(data[x]) end, keys), { 'number', 'string', 'string', 'string' })end
-- Time constantslocal one_second_delay = 1000local small_time = helpers.get_time_const(10)
-- Output test set ============================================================local T = new_set({ hooks = { pre_case = function() child.setup()
-- Ensure `require('mini.sessions')` is always possible (which might not be -- the case with all present `cd` calls) child.cmd('set rtp+=' .. project_root)
-- Ensure always identical starting current directory cd(project_root)
-- Ensure directory structure invariants cleanup_directories()
-- Make all showed messages full width child.o.cmdheight = 10
-- Load module load_module()
-- Ensure clear message history child.cmd('messages clear') end, post_once = function() cleanup_directories() child.stop() end, }, n_retry = helpers.get_n_retry(1),})
-- Unit tests =================================================================T['setup()'] = new_set()
T['setup()']['creates side effects'] = function() -- Global variable eq(child.lua_get('type(_G.MiniSessions)'), 'table')
-- Autocommand group eq(child.fn.exists('#MiniSessions'), 1)end
T['setup()']['creates `config` field'] = function() eq(child.lua_get('type(_G.MiniSessions.config)'), 'table')
-- Check default values local expect_config = function(field, value) eq(child.lua_get('MiniSessions.config.' .. field), value) end
expect_config('autoread', false) expect_config('autowrite', true) expect_config('directory', child.fn.stdpath('data') .. '/session') expect_config('file', 'Session.vim') expect_config('force', { read = false, write = true, delete = false }) expect_config('hooks.pre', { read = nil, write = nil, delete = nil }) expect_config('hooks.post', { read = nil, write = nil, delete = nil }) expect_config('verbose', { read = false, write = true, delete = true })end
T['setup()']['respects `config` argument'] = function() reload_module({ autoread = true }) eq(child.lua_get('MiniSessions.config.autoread'), true)end
T['setup()']['validates `config` argument'] = function() unload_module()
local expect_config_error = function(config, name, target_type) expect.error(function() load_module(config) end, vim.pesc(name) .. '.*' .. vim.pesc(target_type)) end
expect_config_error('a', 'config', 'table') expect_config_error({ autoread = 'a' }, 'autoread', 'boolean') expect_config_error({ autowrite = 'a' }, 'autowrite', 'boolean') expect_config_error({ directory = 1 }, 'directory', 'string') expect_config_error({ file = 1 }, 'file', 'string') expect_config_error({ force = 'a' }, 'force', 'table') expect_config_error({ force = { read = 'a' } }, 'force.read', 'boolean') expect_config_error({ force = { write = 'a' } }, 'force.write', 'boolean') expect_config_error({ force = { delete = 'a' } }, 'force.delete', 'boolean') expect_config_error({ hooks = 'a' }, 'hooks', 'table') expect_config_error({ hooks = { pre = 'a' } }, 'hooks.pre', 'table') expect_config_error({ hooks = { pre = { read = 'a' } } }, 'hooks.pre.read', 'function') expect_config_error({ hooks = { pre = { write = 'a' } } }, 'hooks.pre.write', 'function') expect_config_error({ hooks = { pre = { delete = 'a' } } }, 'hooks.pre.delete', 'function') expect_config_error({ hooks = { post = 'a' } }, 'hooks.post', 'table') expect_config_error({ hooks = { post = { read = 'a' } } }, 'hooks.post.read', 'function') expect_config_error({ hooks = { post = { write = 'a' } } }, 'hooks.post.write', 'function') expect_config_error({ hooks = { post = { delete = 'a' } } }, 'hooks.post.delete', 'function') expect_config_error({ verbose = 'a' }, 'verbose', 'table') expect_config_error({ verbose = { read = 'a' } }, 'verbose.read', 'boolean') expect_config_error({ verbose = { write = 'a' } }, 'verbose.write', 'boolean') expect_config_error({ verbose = { delete = 'a' } }, 'verbose.delete', 'boolean')end
T['setup()']['detects sessions and respects `config.directory`'] = function() cd('tests', 'dir-sessions')
reload_module({ directory = 'global' }) local detected = child.lua_get('MiniSessions.detected')
-- Should be a table with correct keys eq(type(detected), 'table') local keys = vim.tbl_keys(detected) table.sort(keys) --stylua: ignore eq(keys, { '.session', 'Session.vim', 'session1', 'session2.vim', 'session3.lua', 'session_cd_global', 'session_cd_local', 'session_cd_local_2' })
-- Elements should have correct structure local cur_dir = child.fn.getcwd() local session_dir = make_path(cur_dir, 'global') for key, val in pairs(detected) do eq(type(val.modify_time), 'number') eq(val.name, key)
if val.name == 'Session.vim' then eq(val.type, 'local') eq(val.path, make_path(cur_dir, 'Session.vim')) else eq(val.type, 'global') eq(val.path, make_path(session_dir, val.name)) end endend
T['setup()']['prefers local session file over global'] = function() -- Make file 'Session.vim' be in both `config.directory` and current one local path_local = 'tests/dir-sessions/global/Session.vim' child.fn.writefile({ ([[lua _G.session_file = '%s']]):format(path_local) }, path_local)
cd('tests', 'dir-sessions')
reload_module({ directory = 'global' }) local detected = child.lua_get('MiniSessions.detected') local expected_path = project_root .. '/tests/dir-sessions/Session.vim'
eq(detected['Session.vim'].path, expected_path)end
T['setup()']['allows empty string for `config.directory`'] = function() reload_module({ directory = '' }) eq(child.lua_get('MiniSessions.detected'), {})end
T['setup()']['creates missing `config.directory`'] = function() local directory = 'tests/dir-sessions/missing-directory'
eq(child.fn.isdirectory(directory), 0) reload_module({ directory = directory }) eq(child.fn.isdirectory(directory), 1)end
T['setup()']['does not create `config.directory` if it is an existing file'] = function() reload_module({ directory = 'lua/mini/sessions.lua' }) expect.match(get_latest_message(), '%(mini%.sessions%).*lua/mini/sessions%.lua.*is not a directory path')end
T['setup()']['respects `config.file`'] = function() cd('tests', 'dir-sessions', 'local')
reload_module({ autowrite = false, file = 'alternative-local-session' }) local detected = child.lua_get('MiniSessions.detected')
eq(detected['Session.vim'], nil) eq(detected['alternative-local-session'].type, 'local')end
T['setup()']['allows empty string for `config.file`'] = function() cd('tests/dir-sessions') reload_module({ file = '' }) local detected = child.lua_get('MiniSessions.detected') eq(vim.tbl_filter(function(x) return x.type == 'local' end, detected), {})end
T['detected'] = new_set()
T['detected']['is present'] = function() cd('tests', 'dir-sessions') reload_module({ directory = 'global' }) eq(child.lua_get('type(MiniSessions.detected)'), 'table')end
T['detected']['is an empty table if no sessions are detected'] = function() reload_module({ directory = vim.fn.fnamemodify(child.fn.tempname(), ':h') }) eq(child.lua_get('MiniSessions.detected'), {})end
T['read()'] = new_set()
T['read()']['works'] = function() reload_module({ autowrite = false, directory = 'tests/dir-sessions/global' }) child.lua([[MiniSessions.read('session1')]]) validate_session_loaded('global/session1')end
T['read()']['works with no detected sessions'] = function() reload_module({ directory = '', file = '' }) eq(child.lua_get('MiniSessions.detected'), {}) expect.no_error(function() child.lua('MiniSessions.read()') end) expect.match(get_latest_message(), '%(mini%.sessions%) There are no detected sessions')end
T['read()']['accepts only name of detected session'] = function() reload_module({ autowrite = false, directory = 'tests/dir-sessions/global' }) expect.error( function() child.lua([[MiniSessions.read('session-absent')]]) end, '%(mini%.sessions%) "session%-absent" is not a name for detected session' ) validate_no_session_loaded()end
T['read()']['removes stale local session from detected'] = function() -- Start in 'local' directory cd('tests', 'dir-sessions', 'local') reload_module({ autowrite = false, directory = project_root .. '/tests/dir-sessions/global' }) eq(child.lua_get([[MiniSessions.detected['Session.vim'] ~= nil]]), true)
-- Test yes local -> no local child.lua([[MiniSessions.read('session_cd_global')]]) validate_session_loaded('global/session_cd_global') eq(child.lua_get([[MiniSessions.detected['Session.vim'] ~= nil]]), false)
-- Test no local -> yes local child.lua([[MiniSessions.read('session_cd_local')]]) validate_session_loaded('global/session_cd_local') eq(child.lua_get([[MiniSessions.detected['Session.vim'] ~= nil]]), true)
-- Test yes local -> yes other local child.lua([[MiniSessions.read('session_cd_local_2')]]) validate_session_loaded('global/session_cd_local_2') eq(child.lua_get([[MiniSessions.detected['Session.vim'] ~= nil]]), true) local other_local_path = project_root .. '/tests/dir-sessions/local-2/Session.vim' eq(child.lua_get([[MiniSessions.detected['Session.vim'].path ]]), other_local_path)end
T['read()']['makes detected sessions up to date'] = function() local new_session = 'tests/dir-sessions/global/new_session' MiniTest.finally(function() vim.fn.delete(new_session) end)
-- Detect sessions without new session reload_module({ autowrite = false, directory = 'tests/dir-sessions/global' }) eq(child.lua_get('MiniSessions.detected.new_session == nil'), true)
-- Create new session file manually and try to read it directly without -- reloading whole module. child.fn.writefile({ 'lua _G.session_file = ' .. vim.inspect(new_session) }, new_session)
child.lua([[MiniSessions.read('new_session')]]) validate_session_loaded('global/new_session')end
local setup_unsaved_buffers = function() child.o.hidden = true local res = {} set_lines({ 'aaa' }) table.insert(res, child.api.nvim_get_current_buf())
child.cmd('e foo') set_lines({ 'bbb' }) table.insert(res, child.api.nvim_get_current_buf())
return resend
T['read()']['does not source if there are unsaved listed buffers'] = function() reload_module({ autowrite = false, directory = 'tests/dir-sessions/global' })
-- Setup unsaved buffers local unsaved_buffers = setup_unsaved_buffers()
-- Session should not be sourced local error_pattern = vim.pesc('(mini.sessions) There are unsaved listed buffers: ' .. table.concat(unsaved_buffers, ', ') .. '.') expect.error(function() child.lua([[MiniSessions.read('session1')]]) end, error_pattern) validate_no_session_loaded()end
T['read()']['ignores unsaved not listed buffers'] = function() reload_module({ autowrite = false, directory = 'tests/dir-sessions/global' }) local buf_id = child.api.nvim_create_buf(false, false) child.api.nvim_buf_set_lines(buf_id, 0, -1, true, { 'aaa' }) eq(child.api.nvim_buf_get_option(buf_id, 'modified'), true) eq(child.api.nvim_buf_get_option(buf_id, 'buflisted'), false)
child.lua([[MiniSessions.read('session1')]]) validate_session_loaded('global/session1')end
T['read()']['uses by default local session'] = function() cd('tests', 'dir-sessions', 'local') reload_module({ autowrite = false, directory = 'tests/dir-sessions/global' })
eq(child.lua_get([[MiniSessions.detected['Session.vim'].type]]), 'local') child.lua('MiniSessions.read()') validate_session_loaded('local/Session.vim')end
T['read()']['uses by default latest global session'] = function() local session_dir = populate_sessions(one_second_delay + small_time)
reload_module({ autowrite = false, directory = session_dir }) child.lua('MiniSessions.read()') validate_session_loaded('empty/session_b')end
T['read()']['respects `force` from `config` and `opts` argument'] = function() reload_module({ autowrite = false, directory = 'tests/dir-sessions/global', force = { read = true } })
-- Should overwrite unsaved buffers and load session if `force` is `true` setup_unsaved_buffers() child.lua([[MiniSessions.read('session1')]]) validate_session_loaded('global/session1')
-- Should prefer `opts` over `config` setup_unsaved_buffers() reset_session_indicator() expect.error( function() child.lua([[MiniSessions.read('session2.vim', { force = false })]]) end, '%(mini%.sessions%) There are unsaved listed buffers' ) validate_no_session_loaded()end
T['read()']['does not stop on source error'] = function() reload_module({ autowrite = false, directory = 'tests/dir-sessions/global' })
local session_file = 'tests/dir-sessions/global/session_with_error' local folded_file = 'tests/dir-sessions/folded_file' local extra_file = 'tests/dir-sessions/extra_file' MiniTest.finally(function() vim.fn.delete(session_file) vim.fn.delete(folded_file) vim.fn.delete(extra_file) end)
-- Create buffer with non-trivial folds to imitate "No folds found" error child.o.foldmethod = 'indent' child.cmd('edit ' .. folded_file) set_lines({ 'a', '\ta', '\ta', 'a', '\ta', '\ta' }) child.cmd('write')
child.cmd('normal! zM') child.cmd('2 | normal! zo')
-- Create another buffer to check correct session read child.cmd('edit ' .. extra_file) set_lines({ 'This should be preserved in session' }) child.cmd('write')
-- Write session and make sure it contains call to open folds child.cmd('edit ' .. folded_file) child.cmd('mksession ' .. session_file)
local session_lines = table.concat(child.fn.readfile(session_file), '\n') expect.match(session_lines, 'normal! zo')
-- Modify file so that no folds will be found by session file child.fn.writefile({ 'No folds in this file' }, folded_file)
-- Cleanly read session which should open foldless file without errors child.restart() load_module({ autowrite = false, directory = 'tests/dir-sessions/global' })
expect.no_error(function() child.lua([[MiniSessions.read('session_with_error')]]) end)
local buffers = child.api.nvim_list_bufs() eq(#buffers, 2)
child.api.nvim_set_current_buf(buffers[1]) local buf_name_1 = child.fs.normalize(child.api.nvim_buf_get_name(0)) eq(vim.endswith(buf_name_1, '/' .. folded_file), true) eq(child.api.nvim_buf_get_lines(0, 0, -1, true), { 'No folds in this file' })
child.api.nvim_set_current_buf(buffers[2]) local buf_name_2 = child.fs.normalize(child.api.nvim_buf_get_name(0)) eq(vim.endswith(buf_name_2, '/' .. extra_file), true) eq(child.api.nvim_buf_get_lines(0, 0, -1, true), { 'This should be preserved in session' })end
T['read()']['writes current session prior to reading a new one'] = function() local cur_session = project_root .. '/tests/dir-sessions/global/current-session' MiniTest.finally(function() child.fn.delete(cur_session) end)
local validate = function(ref_autowrite) reload_module({ autowrite = false, directory = 'tests/dir-sessions/global' }) child.v.this_session = cur_session child.lua('MiniSessions.config.autowrite = ' .. tostring(ref_autowrite))
eq(child.fn.filereadable(cur_session), 0) child.lua('MiniSessions.read("session1")') -- Should only write current if `autowrite` is enabled eq(child.fn.filereadable(cur_session), ref_autowrite and 1 or 0) child.fn.delete(cur_session) end
validate(true) validate(false)end
T['read()']['respects hooks from `config` and `opts` argument'] = new_set({ parametrize = { { 'pre' }, { 'post' } },}, { test = function(pre_post) -- Should use `config` local hook_string_config = make_hook_string(pre_post, 'read', 'config') reload_from_strconfig({ autowrite = 'false', directory = [['tests/dir-sessions/global']], hooks = hook_string_config, }) child.lua([[MiniSessions.read('session1')]])
validate_session_loaded('global/session1') validate_executed_hook(pre_post, 'read', 'config') -- - Make sure that current session is not written child.v.this_session = ''
-- Should prefer `opts` over `config` local hook_string_opts = make_hook_string(pre_post, 'read', 'opts') child.lua(([[MiniSessions.read('session2.vim', { hooks = %s })]]):format(hook_string_opts))
validate_session_loaded('global/session2.vim') validate_executed_hook(pre_post, 'read', 'opts') end,})
T['read()']['respects `verbose` from `config` and `opts` argument'] = function() reload_module({ autowrite = false, directory = 'tests/dir-sessions/global', verbose = { read = true } })
-- Should give message about read session child.lua([[MiniSessions.read('session1')]]) validate_session_loaded('global/session1') expect.match(get_latest_message(), '%(mini%.sessions%) Read session.*session1') -- - Make sure that current session is not written child.v.this_session = ''
-- Should prefer `opts` over `config` reset_session_indicator() child.lua([[MiniSessions.read('session2.vim', { verbose = false })]]) validate_session_loaded('global/session2.vim')end
T['read()']['respects `vim.{g,b}.minisessions_disable`'] = new_set({ parametrize = { { 'g' }, { 'b' } },}, { test = function(var_type) reload_module({ autowrite = false, directory = 'tests/dir-sessions/global' }) child[var_type].minisessions_disable = true
reset_session_indicator() child.lua([[MiniSessions.read('session1')]]) validate_no_session_loaded() end,})
T['write()'] = new_set()
T['write()']['works'] = function() child.fn.mkdir(empty_dir_path) reload_module({ autowrite = false, directory = empty_dir_path })
-- Setup buffers and autocommands child.cmd('e foo | e bar') local buf_names_expected = get_buf_names() child.lua('_G.n_pre, _G.n_post = 0, 0') child.cmd('au SessionWritePost * lua _G.n_post = _G.n_post + 1') if child.fn.has('nvim-0.13') == 1 then child.cmd('au SessionWritePre * lua _G.n_pre = _G.n_pre + 1') end
child.lua('MiniSessions.write("new_session")')
-- Should trigger session-related events eq(child.lua_get('_G.n_post'), 1) eq(child.lua_get('_G.n_pre'), child.fn.has('nvim-0.13'))
-- Should update `v:this_session` local path_expected = make_path(empty_dir_path, 'new_session') eq(child.v.this_session, path_expected)
-- Verify that written session is correct child.cmd('%bwipeout') child.cmd('source ' .. path_expected) compare_buffer_names(get_buf_names(), buf_names_expected)end
T['write()']['updates `v:this_session`'] = function() child.fn.mkdir(empty_dir_path) reload_module({ autowrite = false, directory = empty_dir_path })
eq(child.v.this_session, '') child.lua([[MiniSessions.write('new_session')]]) eq(child.v.this_session, make_path(empty_dir_path, 'new_session'))end
T['write()']['updates `MiniSessions.detected` with new session'] = function() child.fn.mkdir(empty_dir_path) reload_module({ autowrite = false, directory = empty_dir_path })
eq(child.lua_get('MiniSessions.detected'), {}) child.lua([[MiniSessions.write('new_session')]]) eq(child.lua_get('MiniSessions.detected.new_session').path, make_path(empty_dir_path, 'new_session'))end
T['write()']['updates `MiniSessions.detected` for present session'] = function() local session_dir = populate_sessions(one_second_delay + small_time) reload_module({ directory = session_dir })
child.lua([[MiniSessions.read('session_a')]]) sleep(one_second_delay + small_time) child.lua([[MiniSessions.write('session_a')]])
local detected = child.lua_get('MiniSessions.detected') eq(detected.session_a.modify_time > detected.session_b.modify_time, true)end
T['write()']['validates `session_name`'] = function() reload_module({ autowrite = false, directory = 'tests/dir-sessions/global' }) expect.error( function() child.lua([[MiniSessions.write('')]]) end, '%(mini%.sessions%) Supply non%-empty session name' )end
T['write()']['writes by default to `v:this_session`'] = function() local session_dir = populate_sessions() reload_module({ directory = session_dir }) child.lua([[MiniSessions.read('session_a')]])
-- Verify that `v:this_session` points to correct place local session_path = make_path(session_dir, 'session_a') eq(child.v.this_session, session_path)
-- Write session with `session_name = nil` child.cmd('e foo | e bar') local buf_names_expected = get_buf_names() child.lua('MiniSessions.write()')
-- Verify that it was actually written to `v:this_session` child.cmd('%bwipeout!') child.cmd('source ' .. session_path) compare_buffer_names(get_buf_names(), buf_names_expected)end
T['write()']['writes to current directory if passed name of local session file'] = function() reload_module({ file = 'new-local-session', directory = '' })
child.fn.mkdir(empty_dir_path) cd(empty_dir_path) child.lua([[MiniSessions.write('new-local-session')]])
local path = make_path(empty_dir_path, 'new-local-session') eq(child.fn.filereadable(path), 1)end
T['write()']['writes to global directory'] = function() child.fn.mkdir(empty_dir_path) reload_module({ file = '', directory = empty_dir_path })
child.lua([[MiniSessions.write('new-global-session')]])
local target_path = make_path(empty_dir_path, 'new-global-session') eq(child.fn.filereadable(target_path), 1)end
T['write()']['respects `force` from `config` and `opts` argument'] = function() child.fn.mkdir(empty_dir_path) reload_module({ directory = empty_dir_path, force = { write = false } })
-- Should not allow writing to existing file if `force` is `false` local path = make_path(empty_dir_path, 'existing-file') child.fn.writefile({}, path)
expect.error( function() child.lua([[MiniSessions.write('existing-file')]]) end, [[%(mini%.sessions%) Can't write to existing]] ) eq(child.fn.readfile(path), {})
-- Should prefer `opts` over `config` child.lua([[MiniSessions.write('existing-file', { force = true })]]) eq(#child.fn.readfile(path) > 0, true)end
T['write()']['respects hooks from `config` and `opts` argument'] = new_set({ parametrize = { { 'pre' }, { 'post' } },}, { test = function(pre_post) child.fn.mkdir(empty_dir_path) local path
-- Should use `config` local hook_string_config = make_hook_string(pre_post, 'write', 'config') reload_from_strconfig({ directory = vim.inspect(empty_dir_path), hooks = hook_string_config }) child.lua([[MiniSessions.write('file_01')]])
path = make_path(empty_dir_path, 'file_01') eq(#child.fn.readfile(path) > 0, true) validate_executed_hook(pre_post, 'write', 'config')
-- Should prefer `opts` over `config` local hook_string_opts = make_hook_string(pre_post, 'write', 'opts') child.lua(([[MiniSessions.write('file_02', { hooks = %s })]]):format(hook_string_opts))
path = make_path(empty_dir_path, 'file_02') eq(#child.fn.readfile(path) > 0, true) validate_executed_hook(pre_post, 'write', 'opts') end,})
T['write()']['respects `verbose` from `config` and `opts` argument'] = function() child.fn.mkdir(empty_dir_path) reload_module({ directory = empty_dir_path, verbose = { write = false } }) local msg_pattern = '%(mini%.sessions%) Written session.*session%-written'
-- Should not give message about written session child.lua([[MiniSessions.write('session-written')]]) local path = make_path(empty_dir_path, 'session-written') eq(#child.fn.readfile(path) > 0, true) expect.no_match(get_latest_message(), msg_pattern)
-- Should prefer `opts` over `config` child.fn.delete(path) child.lua([[MiniSessions.write('session-written', { verbose = true })]]) eq(#child.fn.readfile(path) > 0, true) expect.match(get_latest_message(), msg_pattern)end
T['write()']['respects `vim.{g,b}.minisessions_disable`'] = new_set({ parametrize = { { 'g' }, { 'b' } },}, { test = function(var_type) child.fn.mkdir(empty_dir_path) reload_module({ directory = empty_dir_path }) local path = make_path(empty_dir_path, 'session-file')
child[var_type].minisessions_disable = true
child.fn.delete(path) child.lua([[MiniSessions.write('session-file')]]) eq(child.fn.filereadable('session-file'), 0) end,})
T['delete()'] = new_set()
T['delete()']['works'] = function() local session_dir = populate_sessions() reload_module({ directory = session_dir }) local path = make_path(session_dir, 'session_a')
eq(child.lua_get('MiniSessions.detected')['session_a'].path, path) child.lua([[MiniSessions.delete('session_a')]]) eq(child.fn.filereadable(path), 0)end
T['delete()']['validates presence of detected sessions'] = function() reload_module({ file = '', directory = '' })
expect.error( function() child.lua([[MiniSessions.delete('aaa')]]) end, '%(mini%.sessions%) There are no detected sessions' )end
T['delete()']['validates `session_name`'] = function() reload_module({ directory = 'tests/dir-sessions/global' }) expect.error( function() child.lua([[MiniSessions.delete('')]]) end, '%(mini%.sessions%) Supply non%-empty session name' )end
T['delete()']['deletes by default `v:this_session`'] = function() local session_dir = populate_sessions() reload_module({ directory = session_dir, force = { delete = true } })
child.lua([[MiniSessions.read('session_a')]]) local path = make_path(session_dir, 'session_a') eq(child.v.this_session, path)
child.lua('MiniSessions.delete()') eq(child.fn.filereadable(path), 0)
-- Should also update `v:this_session` eq(child.v.this_session, '')end
T['delete()']['deletes from current directory if passed name of local session file'] = function() local session_dir = populate_sessions() cd(session_dir) reload_module({ file = 'session_a', directory = '' }) eq(child.lua_get('MiniSessions.detected.session_a.type'), 'local')
child.lua([[MiniSessions.delete('session_a')]])
local path = make_path(session_dir, 'session_a') eq(child.fn.filereadable(path), 0)end
T['delete()']['deletes from global directory'] = function() local session_dir = populate_sessions() reload_module({ file = '', directory = session_dir }) eq(child.lua_get('MiniSessions.detected.session_a.type'), 'global')
child.lua([[MiniSessions.delete('session_a')]])
local path = make_path(session_dir, 'session_a') eq(child.fn.filereadable(path), 0)end
T['delete()']['makes detected sessions up to date'] = function() local new_session = 'tests/dir-sessions/global/new_session' MiniTest.finally(function() vim.fn.delete(new_session) end)
-- Detect sessions without new session reload_module({ autowrite = false, directory = 'tests/dir-sessions/global' }) eq(child.lua_get('MiniSessions.detected.new_session == nil'), true)
-- Create new session file manually and try to delete it directly without -- reloading whole module. child.fn.writefile({ 'lua _G.session_file = ' .. vim.inspect(new_session) }, new_session)
child.lua([[MiniSessions.delete('new_session')]]) eq(child.fn.filereadable(new_session), 0)end
T['delete()']['respects `force` from `config` and `opts` argument'] = function() local session_dir = populate_sessions() reload_module({ directory = session_dir, force = { delete = true } }) local path
-- Should allow deleting current session if `force` is `false` child.lua([[MiniSessions.read('session_a')]]) path = make_path(session_dir, 'session_a') eq(child.v.this_session, path)
child.lua([[MiniSessions.delete('session_a')]]) eq(child.fn.filereadable(path), 0)
-- Should prefer `opts` over `config` child.lua([[MiniSessions.read('session_b')]]) path = make_path(session_dir, 'session_b') eq(child.v.this_session, path)
expect.error( function() child.lua([[MiniSessions.delete('session_b', { force = false })]]) end, [[%(mini%.sessions%) Can't delete current session]] ) eq(child.fn.filereadable(path), 1)end
T['delete()']['respects hooks from `config` and `opts` argument'] = new_set({ parametrize = { { 'pre' }, { 'post' } },}, { test = function(pre_post) local session_dir = populate_sessions() local path
-- Should use `config` local hook_string_config = make_hook_string(pre_post, 'delete', 'config') reload_from_strconfig({ directory = vim.inspect(session_dir), hooks = hook_string_config }) child.lua([[MiniSessions.delete('session_a')]])
path = make_path(session_dir, 'session_a') eq(child.fn.filereadable(path), 0) validate_executed_hook(pre_post, 'delete', 'config')
-- Should prefer `opts` over `config` local hook_string_opts = make_hook_string(pre_post, 'delete', 'opts') child.lua(([[MiniSessions.delete('session_b', { hooks = %s })]]):format(hook_string_opts))
path = make_path(session_dir, 'session_b') eq(child.fn.filereadable(path), 0) validate_executed_hook(pre_post, 'delete', 'opts') end,})
T['delete()']['respects `verbose` from `config` and `opts` argument'] = function() local session_dir = populate_sessions() reload_module({ directory = session_dir, verbose = { delete = false } }) local msg_pattern = '%(mini%.sessions%) Deleted session.*' local path
-- Should not give message about deleted session child.lua([[MiniSessions.delete('session_a')]]) path = make_path(session_dir, 'session_a') eq(child.fn.filereadable(path), 0) expect.no_match(get_latest_message(), msg_pattern .. 'session_a')
-- Should prefer `opts` over `config` child.lua([[MiniSessions.delete('session_b', { verbose = true })]]) path = make_path(session_dir, 'session_b') eq(child.fn.filereadable(path), 0) expect.match(get_latest_message(), msg_pattern .. 'session_b')end
T['delete()']['respects `vim.{g,b}.minisessions_disable`'] = new_set({ parametrize = { { 'g' }, { 'b' } },}, { test = function(var_type) local session_dir = populate_sessions() reload_module({ directory = session_dir }) local path = make_path(session_dir, 'session_a')
child[var_type].minisessions_disable = true
if child.fn.filereadable(path) == 0 then populate_sessions() end child.lua([[MiniSessions.delete('session_a')]]) eq(child.fn.filereadable(path), 1) end,})
T['restart()'] = new_set({ hooks = { pre_case = function() if child.fn.has('nvim-0.12') == 0 then MiniTest.skip('`MiniSessions.restart()` requires `:restart` from Neovim>=0.12') end
-- Attach a UI since it makes easier dealing with `:restart` child.api.nvim_ui_attach(child.o.columns, child.o.lines, { rgb = true }) end, post_case = function() pcall(vim.fn.delete, 'track-vim-cmd') end, },})
local restart = function(vimrc, restart_cmd) -- Monkey-patch `vim.cmd` inside child process to intercept `:restart` args child.lua([[ vim.fn.writefile({}, 'track-vim-cmd') _G.cmd_orig = vim.cmd vim.cmd = function(command) -- Log into the file to be available even after child is stopped vim.fn.writefile({ command }, 'track-vim-cmd', 'a') _G.cmd_orig(command) end ]])
-- Restart within the child. It disconnects with "ch xxx closed by the peer" -- error, so gather the "aftercommand" passed to `:restart` to execute it by -- hand after setting up new child. It might be improved on later versions. local ok, msg = pcall(child.lua, restart_cmd or 'MiniSessions.restart()') -- Propagate unexpected error after a cleanup if not (ok or vim.endswith(msg, 'closed by the peer')) then child.lua('vim.cmd = _G.cmd_orig') child.fn.delete('track-vim-cmd') error(msg) end vim.uv.sleep(10 * small_time)
local cmd_after_restart for _, l in ipairs(vim.fn.readfile('track-vim-cmd')) do cmd_after_restart = cmd_after_restart or l:match('^restart!? (.*)$') end if cmd_after_restart == nil then error('Could not detect restart "after" command') end
-- Mock `vim.notify` to test notification local mock_notify_cmd = 'lua _G.notify_log={}; vim.notify=function(...) table.insert(_G.notify_log, {...}) end' local args = { '-u', vimrc or 'scripts/minimal_init.lua', '-c', mock_notify_cmd, '-c', cmd_after_restart } child.restart(args)end
local setup_cur_session = function() child.cmd('edit aaa | edit tests/dir-sessions/file') local buf_names_expected = get_buf_names() local lines_expected = child.get_lines() child.set_cursor(2, 2) child.o.termguicolors = true
-- Add some changes in this session to check that the actual restart child.type_keys('i', 'abc', '<Esc>', 'u') local big_changedtick = child.b.changedtick
-- Return validator return function(ref_this_session) compare_buffer_names(get_buf_names(), buf_names_expected) eq(child.get_lines(), lines_expected) eq(child.get_cursor(), { 2, 2 }) eq(vim.fs.normalize(child.v.this_session), vim.fs.normalize(ref_this_session)) eq(child.lua_get('_G.notify_log'), { { '(mini.sessions) Restarted' } }) eq(child.b.changedtick < big_changedtick, true) eq(child.o.termguicolors, true) endend
local validate_no_restart_sideffects = function() for _, f in ipairs(child.fn.readdir(child.fn.getcwd())) do if f:find('^restart_session_') ~= nil then error('There is a leftover temporary session file: ' .. f) end endend
T['restart()']['works without active session'] = function() local validate = setup_cur_session() restart() validate('')
-- Should be no side effects from creating a temporary session file validate_no_restart_sideffects()end
T['restart()']['ignores global arguments without active session'] = function() child.restart({ '-u', 'scripts/minimal_init.lua', '--', 'file-a1', 'file-a2' }) child.cmd('%bwipeout') child.cmd('edit file-b')
load_module() restart()
eq(get_buf_names(), { 'file-b' }) eq(child.fn.argv(-1), {})end
T['restart()']["works with active 'mini.sessions' session"] = function() child.fn.mkdir(empty_dir_path) reload_module({ autowrite = false, directory = empty_dir_path })
local validate = setup_cur_session() child.lua('MiniSessions.write("new_session")') local ref_this_session = child.v.this_session
restart() validate(ref_this_session)end
T['restart()']['works with active regular session'] = function() local validate = setup_cur_session() child.fn.mkdir(empty_dir_path) local session_path = make_path(empty_dir_path, 'new_session') child.cmd('mksession! ' .. session_path) local ref_this_session = child.v.this_session
restart() validate(ref_this_session)end
T['restart()']['works with enabled autoread'] = function() local validate = setup_cur_session() restart('tests/dir-sessions/init-files/autoread.lua') validate('')
-- Should not autoread the session from 'mini.sessions' eq(child.lua_get('_G.session_file'), vim.NIL)end
T['restart()']['works without loading the module'] = function() child.setup() local validate = setup_cur_session() restart(nil, 'require("mini.sessions").restart()') validate('')end
T['restart()']['works when special characters in session name'] = function() local validate = setup_cur_session() child.fn.mkdir(empty_dir_path) local session_path = make_path(empty_dir_path, 'new %! session') child.cmd('mksession! ' .. vim.fn.fnameescape(session_path)) local ref_this_session = child.v.this_session
restart() validate(ref_this_session)end
T['restart()']['handles the error during restart'] = function() -- No active session child.cmd('edit aaa') set_lines({ 'Modified' })
expect.error(restart, 'No write since last change') validate_no_restart_sideffects() eq(child.v.this_session, '')
child.cmd('bwipeout!')
-- Active session setup_cur_session() child.fn.mkdir(empty_dir_path) local session_path = make_path(empty_dir_path, 'new_session') child.cmd('mksession! ' .. session_path) local ref_this_session = child.v.this_session set_lines({ 'Modified' })
expect.error(restart, 'No write since last change') validate_no_restart_sideffects() eq(child.v.this_session, ref_this_session) eq(child.fn.filereadable(session_path), 1)end
T['select()'] = new_set({ hooks = { pre_case = function() -- Mock `vim.ui.select` child.lua('vim.ui = { select = function(...) _G.ui_select_args = { ... } end }')
-- Load module with detected sessions local session_dir = populate_sessions()
-- Add local session cd(session_dir) child.fn.writefile({}, make_path(session_dir, 'Session.vim'), '')
reload_module({ directory = session_dir }) end, },})
T['select()']['works'] = function() child.lua('MiniSessions.select()')
-- Should place local session first and then others alphabetically eq(child.lua_get('_G.ui_select_args[1]'), { 'Session.vim', 'session_a', 'session_b' })
-- Should give informative prompt eq(child.lua_get('_G.ui_select_args[2].prompt'), 'Select session to read')
-- Should format items by appending session type eq(child.lua_get([[_G.ui_select_args[2].format_item('Session.vim')]]), 'Session.vim (local)') eq(child.lua_get([[_G.ui_select_args[2].format_item('session_a')]]), 'session_a (global)')
-- By default should read selected session validate_no_session_loaded() child.lua([[_G.ui_select_args[3]('session_a', 2)]]) validate_session_loaded('empty/session_a')end
T['select()']['makes detected sessions up to date'] = function() child.lua('MiniSessions.select()') eq(child.lua_get('_G.ui_select_args[1]'), { 'Session.vim', 'session_a', 'session_b' })
-- Remove 'session_a' manually which should be shown in `select()` output local directory = child.lua_get('MiniSessions.config.directory') child.fn.delete(make_path(directory, 'session_a'), 'rf')
child.lua('MiniSessions.select()') eq(child.lua_get('_G.ui_select_args[1]'), { 'Session.vim', 'session_b' })end
T['select()']['verifies presence of `vim.ui` and `vim.ui.select`'] = function() child.lua('vim.ui = 1') expect.error(function() child.lua('MiniSessions.select()') end, '%(mini%.sessions%).*vim%.ui')
child.lua('vim.ui = {}') expect.error(function() child.lua('MiniSessions.select()') end, '%(mini%.sessions%).*vim%.ui%.select')end
T['select()']['validates `action` argument'] = function() expect.error( function() child.lua([[MiniSessions.select('aaa')]]) end, [[%(mini%.sessions%) `action` should be one of 'read', 'write', or 'delete'.]] )end
T['select()']['respects `action` argument'] = function() local session_dir = child.lua_get('MiniSessions.config.directory') local path = make_path(session_dir, 'session_a') eq(child.fn.filereadable(path), 1)
child.lua([[MiniSessions.select('delete')]]) child.lua([[_G.ui_select_args[3]('session_a', 2)]]) eq(child.fn.filereadable(path), 0)end
T['select()']['respects `opts` argument'] = function() child.lua([[MiniSessions.select('read', { verbose = true })]])
local msg_pattern = '%(mini%.sessions%) Read session.*session_a' expect.no_match(get_latest_message(), msg_pattern) child.lua([[_G.ui_select_args[3]('session_a', 2)]]) validate_session_loaded('empty/session_a') expect.match(get_latest_message(), msg_pattern)end
T['get_latest()'] = new_set()
T['get_latest()']['works'] = function() local dir = populate_sessions(one_second_delay + small_time) reload_module({ directory = dir }) eq(child.lua_get('MiniSessions.get_latest()'), 'session_b')end
T['get_latest()']['works if there are no detected sessions'] = function() reload_module({ directory = '', file = '' }) eq(child.lua_get('MiniSessions.get_latest()'), vim.NIL)end
-- Integration tests ==========================================================T['Autoreading sessions'] = new_set()
T['Autoreading sessions']['works'] = function() child.restart({ '-u', 'tests/dir-sessions/init-files/autoread.lua' }) validate_session_loaded('local/Session.vim') local ref_events = vim.fn.has('nvim-0.12') == 1 and { 'SessionLoadPre', 'SessionLoadPost' } or { 'SessionLoadPost' } eq(child.lua_get('_G.event_log'), ref_events)end
T['Autoreading sessions']['does not autoread if Neovim started to show something'] = function() local init_autoread = 'tests/dir-sessions/init-files/autoread.lua' local validate = function(...) child.restart({ '-u', init_autoread, ... }) validate_no_session_loaded() end
-- There are files in arguments (like `nvim foo.txt` with new file). validate('new-file.txt')
-- Several buffers are listed (like session with placeholder buffers) validate('-c', 'e foo | set buflisted | e bar | set buflisted')
-- Unlisted buffers (like from `nvim-tree`) don't affect decision child.restart({ '-u', init_autoread, '-c', 'e foo | set nobuflisted | e bar | set buflisted' }) validate_session_loaded('local/Session.vim')
-- Current buffer is meant to show something else validate('-c', 'set filetype=text')
-- Current buffer has any lines (something opened explicitly) validate('-c', [[call setline(1, 'a')]])end
T['Autowriting sessions'] = new_set()
T['Autowriting sessions']['works'] = function() local init_autowrite = 'tests/dir-sessions/init-files/autowrite.lua' child.restart({ '-u', init_autowrite })
-- Create session with one buffer, expect to autowrite it with second child.fn.mkdir(empty_dir_path) cd(empty_dir_path) child.cmd('e aaa | w | mksession') local path_local = make_path(empty_dir_path, 'Session.vim') eq(child.fn.filereadable(path_local), 1)
child.cmd('e bbb | w') child.cmd('au SessionWritePost * call writefile([""], "SessionWritePost")') if child.fn.has('nvim-0.13') == 1 then child.cmd('au SessionWritePre * call writefile([""], "SessionWritePre")') end
child.restart({ '-u', 'NONE' }) child.cmd('source ' .. path_local) compare_buffer_names(get_buf_names(), { 'aaa', 'bbb' })
-- should trigger session-related events eq(child.fn.filereadable('SessionWritePost'), 1) eq(child.fn.filereadable('SessionWritePre'), child.fn.has('nvim-0.13'))end
return T