robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1if vim . g . loaded_shada_plugin then 2return 3end 4vim . g . loaded_shada_plugin =1 5 6local augroup =vim . api . nvim_create_augroup ( 'nvim.shada' , {} ) 7 8---@type fun(binstrings: string[]): string[] 9local shada_get_strings =vim . fn [ 'shada#get_strings' ] 10 11---@type fun(strings: string[]): string[] 12local shada_get_binstrings =vim . fn [ 'shada#get_binstrings' ] 13 14---Ensures that pattern and augroup are set correctly. 15---@param event vim.api.keyset.events|vim.api.keyset.events[] 16---@param opts vim.api.keyset.create_autocmd 17---@param fn fun(args: vim.api.keyset.create_autocmd.callback_args): boolean? 18local function def_autocmd ( event , opts , fn ) 19opts =opts or {} 20opts . group =augroup 21opts . pattern ={ '*.shada' , '*.shada.tmp.[a-z]' } 22opts . callback =function ( ev ) 23if vim . v . cmdarg ~= '' then 24error ( '++opt not supported' ) 25end 26fn ( ev ) 27end 28vim . api . nvim_create_autocmd ( event , opts ) 29end 30 31---Read shada strings from file. 32---@param file string Filename 33---@return string[] # lines from shada file 34local function read_strings ( file ) 35local f =assert ( io . open ( file , 'rb' )) 36local strings =f : read ( '*a' ) 37f : close () 38return shada_get_strings ( strings ) 39end 40 41def_autocmd ( 'BufReadCmd' , {} , function ( ev ) 42local lines =read_strings ( ev . file ) 43vim . api . nvim_buf_set_lines ( ev . buf , 0 , - 1 , false , lines ) 44vim . bo [ ev . buf ]. filetype ='shada' 45end ) 46 47def_autocmd ( 'FileReadCmd' , {} , function ( ev ) 48local lines =read_strings ( ev . file ) 49local lnum =vim . fn . line ( "'[" ) 50vim . api . nvim_buf_set_lines ( ev . buf , lnum , lnum , true , lines ) 51end ) 52 53def_autocmd ( 'BufWriteCmd' , {} , function ( ev ) 54local buflines =vim . api . nvim_buf_get_lines ( 0 , 0 , - 1 , false ) 55local ret =vim . fn . writefile ( shada_get_binstrings ( buflines ), ev . file , 'b' ) 56if ret == 0 then 57-- To check that we are not saving into a different file, we must compare ev.match (always an 58-- absolute path), and not ev.file (can be relative), against nvim_buf_get_name() (always 59-- returns an absolute path). 60if ev . match == vim . api . nvim_buf_get_name ( ev . buf ) or vim . o . cpoptions : find ( '%+' ) then 61vim . bo [ ev . buf ]. modified =false 62end 63end 64end ) 65 66def_autocmd ( { 'FileWriteCmd' , 'FileAppendCmd' } , {} , function ( ev ) 67vim . fn . writefile ( 68shada_get_binstrings ( 69vim . fn . getline ( 70math . min ( vim . fn . line ( "'[" ), vim . fn . line ( "']" )), 71math . max ( vim . fn . line ( "'[" ), vim . fn . line ( "']" )) 72) --[=[@as string[] ]=] 73), 74ev . file , 75ev . event == 'FileAppendCmd' and 'ab' or 'b' 76) 77end ) 78 79def_autocmd ( 'SourceCmd' , {} , function ( ev ) 80vim . cmd . rshada ( vim . fn . fnameescape ( ev . file )) 81end )