repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

neovim/lua/bugabinga/restore_cursor_position.lua

Raw
-- Stolen from mini.misc plugin at https://github.com/echasnovski/mini.misc

local ignored = require 'std.ignored'
local auto = require 'std.auto'

local restore_cursor = function ()
  -- Stop if not a normal buffer
  if vim.bo.buftype ~= '' then return end

  -- Stop if filetype is ignored
  if vim.tbl_contains( ignored.filetypes, vim.bo.filetype ) then return end

  -- Stop if line is already specified (like during start with `nvim file +num`)
  local cursor_line = vim.api.nvim_win_get_cursor( 0 )[1]
  if cursor_line > 1 then return end

  -- Stop if can't restore proper line for some reason
  local mark_line = vim.api.nvim_buf_get_mark( 0, [["]] )[1]
  local n_lines = vim.api.nvim_buf_line_count( 0 )
  if not (1 <= mark_line and mark_line <= n_lines) then return end

  -- Restore cursor and open just enough folds
  vim.cmd [[normal! g`"zv]]
end

-- Create autocommand which runs once on `FileType` for every new buffer
auto 'restore_cursor_position_setup' {
  description = 'Setup function to restore cursor position',
  events      = 'BufReadPre',
  command     = function ( data )
    auto 'restore_cursor_position' {
      description = 'Restores last known cursor position when opening a buffer.',
      event = 'FileType',
      buffer = data.buf,
      once = true,
      command = restore_cursor,
    }
  end,
}