Giter Site home page Giter Site logo

debugloop / telescope-undo.nvim Goto Github PK

View Code? Open in Web Editor NEW
523.0 7.0 8.0 56 KB

A telescope extension to view and search your undo tree ๐ŸŒด

License: MIT License

Lua 100.00%
neovim nvim nvim-plugin nvim-plugins nvim-telescope telescope-extension neovim-plugin neovim-plugins

telescope-undo.nvim's Introduction

telescope-undo.nvim

Visualize your undo tree and fuzzy-search changes in it. For those days where committing early and often doesn't work out.

screenshot

Usage

After invoking telescope-undo you can browse the current buffer's undo tree in a text-based tree representation by using telescope's move_selection_next/previous actions. These are mapped to arrow keys or <C-n>,<C-p> by default. Inserted text is fuzzy matched against the additions and deletions in each undo state in your undo tree and the finder will limit the results accordingly. While this obviously breaks the tree visuals, you can freely search in your undo states. The previewer will always show the diff of the current selection with some context according to the config or your scrolloff value.

If you have found the undo state you were looking for, you can use <C-cr> or <C-r> to revert to that state. If you'd rather not change your whole buffer, you can use <cr> to yank the additions of this undo state into your default register (use <S-cr> or <C-y> to yank the deletions).

Installation

Install with your favorite Neovim package manager.

As part of your Telescope plugin spec for lazy.nvim:

{
  "nvim-telescope/telescope.nvim",
  dependencies = {
    "nvim-lua/plenary.nvim",
    "debugloop/telescope-undo.nvim",
  },
  config = function()
    require("telescope").setup({
      -- the rest of your telescope config goes here
      extensions = {
        undo = {
          -- telescope-undo.nvim config, see below
        },
        -- other extensions:
        -- file_browser = { ... }
      },
    })
    require("telescope").load_extension("undo")
    -- optional: vim.keymap.set("n", "<leader>u", "<cmd>Telescope undo<cr>")
  end,
},

If you prefer standalone Lazy plugin specs (my personal recommendation), here's how you do that with some more options as an example:

{
  "debugloop/telescope-undo.nvim",
  dependencies = { -- note how they're inverted to above example
    {
      "nvim-telescope/telescope.nvim",
      dependencies = { "nvim-lua/plenary.nvim" },
    },
  },
  keys = {
    { -- lazy style key map
      "<leader>u",
      "<cmd>Telescope undo<cr>",
      desc = "undo history",
    },
  },
  opts = {
    -- don't use `defaults = { }` here, do this in the main telescope spec
    extensions = {
      undo = {
        -- telescope-undo.nvim config, see below
      },
      -- no other extensions here, they can have their own spec too
    },
  },
  config = function(_, opts)
    -- Calling telescope's setup from multiple specs does not hurt, it will happily merge the
    -- configs for us. We won't use data, as everything is in it's own namespace (telescope
    -- defaults, as well as each extension).
    require("telescope").setup(opts)
    require("telescope").load_extension("undo")
  end,
},

Invoke using:

" Directly by calling it through Telescope's extension interface:

" using lua
:lua require("telescope").extensions.undo.undo()

" using custom options for just this call
:lua require("telescope").extensions.undo.undo({ side_by_side = true })

" using legacy Vim script
:Telescope undo

" Using the optional mapping:

" using lua
:lua vim.keymap.set("n", "<leader>u", "<cmd>Telescope undo<cr>")
" using legacy Vim script
:nmap <leader>u <cmd>Telescope undo<cr>

Configuration

The available configuration values are:

  • use_delta, which controls whether delta is used for fancy diffs in the preview section. If set to false, telescope-undo will not use delta even when available and fall back to a plain diff with treesitter highlights.
  • use_custom_command, which can be used to use an unsupported diff tool other than delta
  • side_by_side, which tells delta to render diffs side-by-side. Thus, requires delta to be used. Be aware that delta always uses its own configuration, so it might be that you're getting the side-by-side view even if this is set to false.
  • diff_context_lines, defaults to your scrolloff value.
  • entry_format, defaults to "state #$ID, $STAT, $TIME"", which contains the three supported variables.
  • time_format, defaults to "" for a timeago-style representation. Can be set to a Lua date format string.
  • saved_only, defaults to false, but can be used to limit shown undo states to those that have been saved to disk.

Further, the undo telescope should accept any of the usual telescope attributes as well as the special theme key which auto-extends the telescope theme on top of any of your explicitly provided config. Of course, you might also want to remap some of the default keys.

This is what the defaults look like with some additional explanations:

opts = {
  extensions = {
    undo = {
      use_delta = true,
      use_custom_command = nil, -- setting this implies `use_delta = false`. Accepted format is: { "bash", "-c", "echo '$DIFF' | delta" }
      side_by_side = false,
      diff_context_lines = vim.o.scrolloff,
      entry_format = "state #$ID, $STAT, $TIME",
      time_format = "",
      saved_only = false,
    },
  },
},

The full list will always be available in the code providing the defaults here.

My personal recommendation is the following, which maximizes the width of the preview to enable side-by-side diffs:

opts = {
  extensions = {
    undo = {
      side_by_side = true,
      layout_strategy = "vertical",
      layout_config = {
        preview_height = 0.8,
      },
    },
  },
}

Mappings

By default, the following mappings are enabled.

require("telescope").setup({
  extensions = {
    undo = {
      mappings = {
        i = {
          ["<cr>"] = require("telescope-undo.actions").yank_additions,
          ["<S-cr>"] = require("telescope-undo.actions").yank_deletions,
          ["<C-cr>"] = require("telescope-undo.actions").restore,
          -- alternative defaults, for users whose terminals do questionable things with modified <cr>
          ["<C-y>"] = require("telescope-undo.actions").yank_deletions,
          ["<C-r>"] = require("telescope-undo.actions").restore,
        },
        n = {
          ["y"] = require("telescope-undo.actions").yank_additions,
          ["Y"] = require("telescope-undo.actions").yank_deletions,
          ["u"] = require("telescope-undo.actions").restore,
        },
      },
    },
  },
})

Important

Note how above example uses the call to telescope's setup(). This is due to the fact that directly requiring these actions needs telescope-undo to be available already, which it is not inside lazy's opts key when using above "standalone" spec. See the next example for how to do it inside opts.

There is one more mapping available, yank_larger. This yanks either the additions or the deletions based on their line count, with the additions winning in case of a tie. This is how you configure this mapping, or remap any of the default actions for that matter:

opts = {
  extensions = {
    undo = {
      mappings = {
        -- Wrapping the actions inside a function prevents the error due to telescope-undo being not
        -- yet loaded.
        i = {
          ["<cr>"] = function(bufnr)
            return require("telescope-undo.actions").yank_larger(bufnr)
          end,
        },
        n = {
          ["y"] = function(bufnr)
            return require("telescope-undo.actions").yank_larger(bufnr)
          end,
        },
      },
    },
  },
}

If you wish to disable one of the default mappings, just set it to false.

opts = {
  extensions = {
    undo = {
      mappings = {
        i = {
          ["<C-y>"] = false,
        },
      },
    },
  },
}

Contributions

Suggestions, issues and patches are very much welcome. There are some TODOs sprinkeled into the code that need addressing, but could also use some input and opinions.

telescope-undo.nvim's People

Contributors

debugloop avatar emmanueltouzery avatar jason0x43 avatar lamprospitsillos avatar pwnalone avatar pynappo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

telescope-undo.nvim's Issues

Alternative to $TIME with absolute time

I want to see the time without timeago conversion. So I have a feature request to get a date/time view similar to the one you get when pressing u or even better in some RFC3339 format?

Diff View output is wrong

The diff appears to wrong in the following scenario.

Steps

  1. Open new buffer
  2. Type:
    1. i
    2. a<cr>
    3. b<cr>
    4. c<cr>
    5. d<cr>
    6. esc
  3. Move up one line (to line 3), then dd
  4. Move up one line (to line 2), then:
    1. o
    2. X
    3. esc
  5. Open Telescope Undo.

The initial state was:

a
b
c
d

The final contents of the buffer is:

a
b
X
d

The output of the diff for the last/latest state shows:

a
+X
b
d

Which is wrong (I think). Shouldn't it be the following instead?

a
b
+X
d

Add an option to merge yank_addition and yank_deletion

Hi,
Thanks for this plugin, a bit confusing to use for me, but its good to have it, just in case to recover a lost piece of code in the undo tree...

I think however than having to key bindings to yank according to addition/deletion state is

  1. complicate
  2. prone to unwanted behaviors :naming create an empty register if I press on a deletion...

So I propose to just add an option to merge the two commands : it will detects if the item is a deletion or addition and yank accordingly. It is not a problem in any case : we just yank something to the register, it can be bad! And it will avoid the possibility of empty register entries.

I am just suggesting this change. As I am just setting up my vim config, I am not going to dif the code and send a pull request. Maybe oneday if nothing hcange and I use this plugin a lot...

If anyone listen my advice and change that, thank you by advance!

Restore does not seem to be working

           :extensions {:undo { :mappings {:i {:<cr> (fn [...] ((. (require :telescope-undo.actions) :yank_additions) ...))   ; TODO: Fix these mappings!
                                               :<S-cr> (fn [...] ((. (require :telescope-undo.actions) :yank_deletions) ...))
                                               :<C-R> (fn [...] (print "Does not work!\n!") ((. (require :telescope-undo.actions) :restore) ...))}}}}}}]

This is my config:

  • yank_deletions and yank_additions work
  • restore does not work, although the (print "Does not work!\n!) is called, which tells me that the mappings itself is properly configured

Any ideas on how to debug this?

u_undo: line numbers wrong

Sorry in advance because I really don't know how to replicate this on a new file.

This is hapenning on a specific file in one of my projects. Once I do require("telescope").extensions.undo.undo() it fails with "u_undo: line numbers wrong" and (very important, I think) my buffer loses a ton of code out of nowhere right after executing that.

Again, telescope-undo.nvim works on any other file except for this one.

Here's the error log.

1 / 2: Checking for worktree /home/serranomorante/work/.../gems/GEMS-0001
2 / 2: Running post switch callbacks
E5108: Error executing lua: vim/_editor.lua:0: nvim_exec2(): Vim(undo):E438: u_undo: line numbers wrong
stack traceback:
        [C]: in function 'nvim_exec2'
        vim/_editor.lua: in function 'cmd'
        ...vim/lazy/telescope-undo.nvim/lua/telescope-undo/init.lua:17: in function '_traverse_undotree'
        ...vim/lazy/telescope-undo.nvim/lua/telescope-undo/init.lua:100: in function '_traverse_undotree'
        ...vim/lazy/telescope-undo.nvim/lua/telescope-undo/init.lua:119: in function 'build_undolist'
        ...vim/lazy/telescope-undo.nvim/lua/telescope-undo/init.lua:141: in function 'undo'
        ...y/telescope-undo.nvim/lua/telescope/_extensions/undo.lua:41: in function 'undo'
        ...te/.config/nvim/lua/serranomorante/plugins/telescope.lua:206: in function <...te/.config/nvim/lua/serranomorante/plugins/telescope.lua:206>
Press ENTER or type command to continue

Bug: text-overflow/line-wrap not working properly in side-by-side view

Hey!

Thx for your awesome plugin :-)

Here's a small UI-bug I just stumbled upon.
Not sure if it's a telescope or even nvim issue or even a git-delta issue,
but since I'm seeing this the first time right here in this plugin, I'm reporting it here.

image

As you can see in the side-by-side view the wrapped lines follow up in the wrong column ... partially at least.

Cheers, Joehannes

bash on windows

use_delta = true,
side_by_side = true,
layout_strategy = 'vertical',
layout_config = {
preview_height = 0.8,
},

does not work on windows even if delta is present.

if opts.use_delta and vim.fn.executable("bash") == 1 and vim.fn.executable("delta") == 1 then in previewers.lua may be the issue. Windows has bash but it will spawn WSL. If you could invoke delta without bash it may work.

Unable to change mappings

I want to map <cr> to restore instead of of yank_additions so have the following setup (with lazy.nvim):

return {
  {
    "telescope.nvim",
    opts = {
      defaults = {
        dynamic_preview_title = true,
        file_ignore_patterns = {
          "yarn.lock",
          "^./.git/",
        },
        vimgrep_arguments = {
          "rg",
          "--color=never",
          "--no-heading",
          "--with-filename",
          "--line-number",
          "--column",
          "--smart-case",
          "--hidden",
          "-g",
          "!.git/*",
        },
      },
      extensions = {
        fzf = {
          fuzzy = true,
          override_generic_sorter = true,
          override_file_sorter = true,
          case_mode = "smart_case",
        },
        undo = {
          use_delta = true,
          side_by_side = true,
          diff_context_lines = 15,
          mappings = {
            i = {
              ["<cr>"] = require("telescope-undo.actions").restore,
              ["<c-cr>"] = require("telescope-undo.actions").yank_additions,
              ["<S-cr>"] = require("telescope-undo.actions").yank_deletions,
            },
          },
        },
      },
      pickers = {
        buffers = {
          show_all_buffers = true,
          sort_lastused = true,
        },
        command_history = {
          theme = "ivy",
        },
        find_files = {
          hidden = true,
          fuzzy = true,
        },
        live_grep = {
          file_ignore_patterns = {
            "yarn.lock",
            "^./.git/",
            "pnpm-lock.yaml",
          },
        },
        lsp_code_actions = {
          theme = "cursor",
        },
        spell_suggest = {
          theme = "cursor",
        },
      },
    },
    dependencies = {
      {
        "debugloop/telescope-undo.nvim",
        config = function()
          require("telescope").load_extension("undo")
        end,
      },
    },
  },
}

But I get the following error:

 ๏™™  Error  17:20:13 notify.error lazy.nvim Failed to load `plugins.telescope`

~/.config/nvim/lua/plugins/telescope.lua:65: module 'telescope-undo.actions' not found:

What am I doing wrong here?

I thought that having telescope-undo.nvim in the dependencies loading the undo extension there should do the trick to allow me to change mappings.

crash when trying to use actions

i'm getting this crash when trying to run the actions, for instance reverting to the undo version:

E5108: Error executing lua Vim:Can't send data to closed stream
stack traceback:
	[C]: in function 'chansend'
	...lescope.nvim/lua/telescope/previewers/term_previewer.lua:223: in function '_send_input'
	...rt/telescope.nvim/lua/telescope/previewers/previewer.lua:84: in function 'send_input'
	...lescope.nvim/lua/telescope/previewers/term_previewer.lua:237: in function '_scroll_fn'
	...rt/telescope.nvim/lua/telescope/previewers/previewer.lua:92: in function 'scroll_fn'
	...acker/start/telescope.nvim/lua/telescope/actions/set.lua:192: in function 'run_replace_or_original'
	...packer/start/telescope.nvim/lua/telescope/actions/mt.lua:65: in function 'scroll_previewer'
	...cker/start/telescope.nvim/lua/telescope/actions/init.lua:210: in function 'run_replace_or_original'
	...packer/start/telescope.nvim/lua/telescope/actions/mt.lua:65: in function 'key_func'
	...k/packer/start/telescope.nvim/lua/telescope/mappings.lua:341: in function 'execute_keymap'
	[string ":lua"]:1: in main chunk

(nvim 0.8.0, telescope 0.1.0 stable and also the latest telescope master)

the plugin is looking great otherwise!

Bug: Options are ignored

This works well, and removes the need of messing with Telescope, which should remain as a separate plugin.

  -- telescope-undo.nvim
  -- https://github.com/debugloop/telescope-undo.nvim
  {
    "debugloop/telescope-undo.nvim",
    opts = {
      side_by_side = true
    },
  },
  -- Telescope integration (:Telescope projects)
  { "nvim-telescope/telescope.nvim", opts = function() require("telescope").load_extension "undo" end },

Maybe it would be a good idea to add it to the readme?

Bug: Telescope plugin configuration does not work

Thanks for the plugin, undotree was one of the few non-lua plugins I still have.

I tried configuring the extension's telescope layout, but it seems that these configs have no effect?

require("telescope").setup {
        extensions = {
		undo = {
			prompt_prefix = "?",
			initial_mode = "normal",
		},
	},
}

Requirements to see preview window?

Hi!

I love the concept behind this package! I added it to my config:

	use({
		"nvim-telescope/telescope.nvim",
		requires = {
			"nvim-lua/plenary.nvim",
			"debugloop/telescope-undo.nvim",
		},
		config = function()
			require("telescope").setup({
				extensions = {
					undo = {
						use_delta = false,
						side_by_side = true,
						layout_strategy = "vertical",
						layout_config = {
							preview_height = 0.8,
						},
					},
				},
			})
			require("telescope").load_extension("undo")
		end,
	})

However, when I attempt to browse my undo tree -- I don't get a preview window:

image

I do get a preview window when I use telescope for other things.

Is there some requirement to get a preview window which I might be missing?

Incompatibility with Zellij

I've encountered a compatibility issue between this plugin and Zellij, the terminal multiplexer. Pressing doesn't revert to a previous state.

Is there any known workaround?

Thanks!

Unable to disable default key mappings

Description

In Telescope, I have some default key mappings for all pickers, including:

  • <C-y> = Scroll results window up
  • <C-e> = Scroll results window down

Therefore, I would like to disable telescope-undo's default key mapping of <C-y> and use the one that I have setup in Telescope's default mappings option. I have tried the following configurations, but none of them work.

-- ERROR
opts = {
  extensions = {
    undo = {
      mappings = {
        i = {
          ["<C-y>"] = false,
        },
      },
    },
  },
}
-- ERROR
opts = {
  extensions = {
    undo = {
      mappings = {
        i = {
          ["<C-y>"] = "results_scrolling_up",
        },
      },
    },
  },
}
-- No error, but still doesn't work
opts = function(_, opts)
  opts.extensions = opts.extensions or {}
  opts.extensions.undo = {
    mappings = {
      i = {
        ["<C-y>"] = require("telescope.actions").results_scrolling_up,
      },
    },
  }
  return opts
end

NOTE: The above examples show partial configurations for Telescope using the Lazy plugin manager.

Is it possible to disable the default key mappings, and, if so, how?

Minimal Config

vim.g.mapleader = " "
vim.g.maplocalleader = " "

local lazypath = vim.fn.stdpath("data") .. "/lazy/lazy.nvim"
if not vim.loop.fs_stat(lazypath) then
  -- stylua: ignore
  vim.fn.system({ "git", "clone", "--filter=blob:none", "https://github.com/folke/lazy.nvim.git", "--branch=stable", lazypath })
end
vim.opt.rtp:prepend(lazypath)

require("lazy").setup({
  {
    "nvim-telescope/telescope.nvim",
    dependencies = {
      "nvim-lua/plenary.nvim",
      "debugloop/telescope-undo.nvim",
    },
    cmd = "Telescope",
    keys = {
      { "<Leader>u", "<Cmd>Telescope undo<CR>" },
    },
    opts = {
      extensions = {
        undo = {
          mappings = {
            i = {
              ["<C-y>"] = false,
            },
          },
        },
      },
    },
    config = function(_, opts)
      require("telescope").setup(opts)
      require("telescope").load_extension("undo")
    end,
  },
})

[Feature request]: Show which version is currently saved

When moving around the versions, it is sometimes easy to get lost when we want to go back to our currently saved version. So having a notation (e.g an (S) at the end of the state) to indicate the current version would be much helpful.

Making bindings configurable

The <C-CR> key sequence does not work in some terminals, the bindings for restore, yank deletions, and yank additions should be user configurable.

Also, the descriptions in telescope whichkey (<C-_> in insert mode, ? in normal) show as the action name instead of the mapped action.

<CR> results only in new blank buffer

Hello,

Thanks for your work here, I've been exploring undo trees and I like yours the best.

However, there's a critical issue I'm facing which makes it impossible for me to reasonably use this.

Say I have a file I've been working on that has an undo history. I call :Telescope undo, and I see the telescope window pop up with the whole undo tree, fuzzy searchable, snappy, looking great.

I enter normal mode within the telescope prompt (and this is a clean telescope install, no config), navigate to my desired entry, and press <CR>. What I expect is for the additions from that entry to be copied to my default register, but what happens instead is that a new empty buffer is created, with the title of the entry I selected, something like state #1386, -1, 2 days ago, and nothing is added to my default register.

Am I doing something wrong in the configuration here?

EDIT: Put some quotes around <CR> which didn't show up

Error executing lua [string ":lua"]:1: ...

Hello,

I'm very excited about this plugin, but I cannot get it to work.

I've installed it using Plug, is that a viable means?

It is installed after telescope.

Here is the error I'm getting:

E5108: Error executing lua [string ":lua"]:1: attempt to call a table value
stack traceback:
        [string ":lua"]:1: in main chunk

This happens when I call :lua require('telescope-undo')().

Also, Telescope undo results in another error, [telescope.run_command]: Unknown command

Is it somehow not picking up my telescope install? Do I need to make the switch to packer or something?

:checkhealth telescope results in

   
telescope: require("telescope.health").check()    
========================================================================    
## Checking for required plugins    
  - OK: plenary installed.    
  - WARNING: nvim-treesitter not found.     
    
## Checking external dependencies    
  - OK: rg: found ripgrep 13.0.0    
  - WARNING: fd: not found. Install sharkdp/fd for extended capabilities    
    
## ===== Installed extensions =====

with notably no installed extensions, although I use telescope regularly, and have other plugins that sit on that window like ChatGPT working just fine. I'm not super well versed in this stuff so I don't know if that's even a correct analysis, sorry in advance for my noobishness.

Unable to map `<cr>` to `require("telescope-undo.actions").restore` when using lazy.nvim

To preface, yank_additions, yank_deletions, and restore all work prior to editing mappings so I know the issue is not with my terminal.

Proof of telescope-undo working normally with <C-cr> restoring the buffer

I have tried a variation of the following:

return {
  "nvim-telescope/telescope.nvim",
  dependencies = {
    "nvim-lua/plenary.nvim",
    {
      "nvim-telescope/telescope-fzf-native.nvim",
      build = "make",
    },
    "debugloop/telescope-undo.nvim",
  },
  keys = {
    {
      "<leader>fu",
      "<cmd>Telescope undo<cr>",
      desc = "View undos",
    },
  },
  opts = {
    extensions = {
      undo = {
        mappings = {
          i = {
            ["<S-cr>"] = require("telescope-undo.actions").yank_additions,
            ["<C-cr>"] = require("telescope-undo.actions").yank_deletions,
            ["<cr>"] = require("telescope-undo.actions").restore,
          },
        }
      }
    }
  },
  config = function()
    require("telescope").load_extension("undo")
  end,
}

which gives me this error:

Error detected while processing /home/franky/Projects/dotfiles/neovim/.config/nvim/init.lua:
Failed to load `plugins.telescope`
/home/franky/.config/nvim/lua/plugins/telescope.lua:55: module 'telescope-undo.actions' not found:

And so, I manually passed opts to config and called setup myself.

config = function(_, opts)
    require("telescope").load_extension("undo")
    require("telescope").setup(opts)
  end,

but I get the same error.

I wrapped my calls init callbacks with

opts = {
  extensions = {
    undo = {
      mappings = {
        i = {
          ["<S-cr>"] = function()
            require("telescope-undo.actions").yank_additions()
          end,

          ["<C-cr>"] = function()
            require("telescope-undo.actions").yank_deletions()
            end,

            ["<cr>"] = function()
            require("telescope-undo.actions").restore()
            end,
        },
        }
    }
    }
},
config = function(_, opts)
  require("telescope").setup(opts)
  require("telescope").load_extension("undo")
end,

And that causes telescope-undo not work in the telescope floating window. Every press of enter resets the cursor

Video showcase #1

---

Edit: I have also tried the following, but this still doesn't work. I decided to include it because I'm not sure if this is *progress*. Pressing enter on on an undo item opens a blank screen (video example below)

opts = {
  extensions = {
    undo = {
      mappings = {
        ["<s-cr>"] = function()
          require("telescope-undo.actions").yank_additions()
        end,
        ["<c-cr>"] = function()
          require("telescope-undo.actions").yank_deletions()
        end,
        ["<cr>"] = function()
          require("telescope-undo.actions").restore()
        end,
      },
    },
  },
},
config = function(_, opts)
  require("telescope").setup(opts)
  require("telescope").load_extension("undo")
end,

Video showcase #2

I removed the opts and did everything in the config.

config = function()
  require("telescope").load_extension("undo")

  local opts = {
    extensions = {
      undo = {
        mappings = {
          ["<s-cr>"] = require("telescope-undo.actions").yank_additions,
          ["<c-cr>"] = require("telescope-undo.actions").yank_deletions,
          ["<cr>"] = require("telescope-undo.actions").restore
        },
      },
    },
  }

  require("telescope").setup(opts)
end,

And putting the setup before the load_extension

config = function()
  local opts = {
    extensions = {
      undo = {
        mappings = {
          ["<s-cr>"] = require("telescope-undo.actions").yank_additions,
          ["<c-cr>"] = require("telescope-undo.actions").yank_deletions,
          ["<cr>"] = require("telescope-undo.actions").restore
        },
      },
    },
  }

  require("telescope").setup(opts)
  require("telescope").load_extension("undo")
end,

Putting the setup after the load_extensions does nothing

Here's what happens before setup is before the load_extensions

Allow having a different telescope layout for this extension than the default

(continuing #1 )

If you find that this extension doesn't respect telescope-wide settings please reopen with an example ๐Ÿ‘๐Ÿป

Probably didn't explain it properly in the previous issue: the issue is not that telescope-configs are not respected, but rather that this extension cannot have a configs that differ from the default telescope config.

With telescope, we are able to configure every picker individually, spell suggestion can have a different layout from file opener. Buffer selection can start in normal mode, while file opener can start in insert mode, etc.

Especially for this undo tree picker, it would make much sense to have the same kind of configurability. For example due to the diff views, it would make sense to have a wider preview window etc.

delta in wsl not working

Hi!

First of all, thanks for the plugin.

I'm having issues with trying to use it with delta inside WSL. I've looked into the code and discovered if opts.use_delta and not is_wsl which lead me to #14, but I'm not sure why this restriction took place. While working in WSL with delta installed within it should be exactly the same workflow as if we were running via any other linux shell.

Is this restriction still relevant?

PS: it actually works fine, I've removed is_wsl check and reordered if/elseif branches to use bash right away and it works as expected, not sure if I want to use delta now (a bit too noisy for me), but the initial question stands.

add new option: diff_context_lines?

i'd rather not touch my neovim-wide scrolloff, but increasing this to non-zero really improves the display... so ideally i'd prefer if you could extend the extension options to add a new optional diff_context_lines: number...

If not possible, I guess I could setlocal the scrolloff before and after invoking telescope-undo but it's really a huge hack...

Minor FR: abbreviate list of items

Especially with a horizontal layout on a smaller screen, these do cost quite a bit of space. to save space, one could:

  • remove the word "state", it's redundant
  • remove "ago"
  • remove zero diff counts (+0 and -0)
  • abbreviate "minutes" to "min", etc.
  • abbreviate "just now" to "now"

Pasted image 2022-12-20 16 26 43

Not showing all undolevels

Hi

When comparing this plugin and mbbill undotree, I am able to see a much longer list of file states in undotree compared to telescope undo. I couldn't seem to find a configuration item for this?

Error : after the second argument: expected table, got nil

Error executing Lua callback: vim/shared.lua:0: after the second argument: expected table, got nil                                                                                              
stack traceback:                                                                                                                                                                                
        [C]: in function 'error'                                                                                                                                                                
        vim/shared.lua: in function 'validate'                                                                                                                                                  
        vim/shared.lua: in function 'tbl_deep_extend'                                                                                                                                           
        ...y/telescope-undo.nvim/lua/telescope/_extensions/undo.lua:37: in function <...y/telescope-undo.nvim/lua/telescope/_extensions/undo.lua:36>                                            
        ...share/nvim/lazy/telescope.nvim/lua/telescope/command.lua:193: in function 'run_command'                                                                                              
        ...share/nvim/lazy/telescope.nvim/lua/telescope/command.lua:259: 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>      

The entire Telescope conf: https://github.com/LamprosPitsillos/nixos-config/blob/main/home-manager/programs/nvim/lua/plugins/Telescope.lua
A snipet:

                extensions = {
                    undo = {
                        use_delta = false,
                        use_custom_command = nil, -- setting this implies `use_delta = false`. Accepted format is: { "bash", "-c", "echo '$DIFF' | delta" }
                        side_by_side = false,
                        layout_strategy = "vertical",
                        layout_config = {
                            preview_height = 0.8,
                        },
                        diff_context_lines = vim.o.scrolloff,
                        entry_format = "state #$ID, $STAT, $TIME",
                        time_format = "",
                        mappings = {
                            i = {
                                -- IMPORTANT: Note that telescope-undo must be available when telescope is configured if
                                -- you want to replicate these defaults and use the following actions. This means
                                -- installing as a dependency of telescope in it's `requirements` and loading this
                                -- extension from there instead of having the separate plugin definition as outlined
                                -- above.
                                ["<cr>"] = require("telescope-undo.actions").yank_additions,
                                ["<S-cr>"] = require("telescope-undo.actions").yank_deletions,
                                ["<C-cr>"] = require("telescope-undo.actions").restore,
                            },
                        },
                    },
                    ast_grep = {
                        command = {
                        ......

Clear undo history

Is it currently possible clear history or delete a specific state? For example over time the undo history becomes very large and I know I won't need it anymore, so it would be nice to at least manually delete older state. Currently I have saved_only turn on to keep it somewhat getting out of control.

Thanks!

Can't restore or yank deletions

  • I can yank additions just fine
  • When I attempt to yank deletions, it empties my register
  • When I attempt to restore, it closes Telescope but the buffer doesn't change

I've tried moving around where the extension is loaded, tried your setup in your dotfiles, and made it print something random to make sure the keybinds are getting called, can't figure it out, here's my setup using lazy.nvim:

return {
	"nvim-telescope/telescope.nvim",
	dependencies = {
		"nvim-lua/plenary.nvim",
		"nvim-telescope/telescope-file-browser.nvim",
		"gbrlsnchs/telescope-lsp-handlers.nvim",
		"debugloop/telescope-undo.nvim",
	},
	lazy = false,
	config = function()
		local actions = require("telescope.actions")
		local builtin = require("telescope.builtin")

		vim.keymap.set("n", "<Leader>ff", function()
			builtin.find_files({
				no_ignore = false,
				hidden = true,
			})
		end)

		vim.keymap.set("n", "<Leader>fr", function()
			builtin.lsp_references()
		end)

		vim.keymap.set("n", ";f", function()
			builtin.find_files({
				no_ignore = false,
				hidden = true,
			})
		end)

		vim.keymap.set("n", "<Leader>fg", function()
			builtin.live_grep()
		end)

		vim.keymap.set("n", "<Leader>fb", function()
			builtin.buffers()
		end)

		vim.keymap.set("n", "<Leader>fj", function()
			builtin.jumplist()
		end)

		vim.keymap.set("n", "<Leader>fe", function()
			builtin.diagnostics()
		end)

		vim.keymap.set("n", "<Leader>fs", function()
			builtin.lsp_document_symbols()
		end)

		require("telescope").setup({
			defaults = {
				vimgrep_arguments = {
					"rg",
					"--color=never",
					"--no-heading",
					"--with-filename",
					"--line-number",
					"--column",
					"--smart-case",
				},
				prompt_prefix = " ๏‡ฅ  ",
				selection_caret = "  ",
				entry_prefix = "  ",
				initial_mode = "insert",
				selection_strategy = "reset",
				sorting_strategy = "ascending",
				layout_strategy = "horizontal",
				layout_config = {
					horizontal = {
						prompt_position = "top",
						preview_width = 0.55,
						results_width = 0.8,
					},
					vertical = {
						mirror = false,
					},
					width = 0.87,
					height = 0.80,
					preview_cutoff = 120,
				},
				file_sorter = require("telescope.sorters").get_fuzzy_file,
				file_ignore_patterns = { "node_modules" },
				generic_sorter = require("telescope.sorters").get_generic_fuzzy_sorter,
				path_display = { "truncate" },
				winblend = 0,
				border = {},
				borderchars = { "โ”€", "โ”‚", "โ”€", "โ”‚", "โ•ญ", "โ•ฎ", "โ•ฏ", "โ•ฐ" },
				color_devicons = true,
				set_env = {
					["COLORTERM"] = "truecolor",
				}, -- default = nil,
				file_previewer = require("telescope.previewers").vim_buffer_cat.new,
				grep_previewer = require("telescope.previewers").vim_buffer_vimgrep.new,
				qflist_previewer = require("telescope.previewers").vim_buffer_qflist.new,
				buffer_previewer_maker = require("telescope.previewers").buffer_previewer_maker,
				mappings = {
					n = {
						["q"] = actions.close,
					},
					i = {
						["<c-j>"] = actions.move_selection_next,
						["<c-k>"] = actions.move_selection_previous,
						["<esc>"] = actions.close,
					},
				},
			},
			extensions = {
				undo = {
					side_by_side = true,
					mappings = {
						i = {
							["<cr>"] = require("telescope-undo.actions").yank_additions,
							["<S-cr>"] = require("telescope-undo.actions").yank_deletions,
							["<C-cr>"] = require("telescope-undo.actions").restore,
						},
					},
				},
			},
		})

		require("telescope").load_extension("undo")
		vim.keymap.set("n", "<leader>u", "<cmd>Telescope undo<cr>")
	end,
}

Diff Preview Against Current File

Is it possible to show the diff against the current file rather than smaller diffs against the previous state?

If I'm looking back at a file that has many changes, I'd like to be able to see all of the changes between the previous state and the current state to better understand what I'd be undoing. I understand that might have greater costs to performance given a large undo history so maybe this could be a mapping to telescope that opens vimdiff against the changeset to preview all changes in full.

Expected behavior of key mappings seems like they are not working.

How are the key maps supposed to work with this extension?

Regardless of whether I press Shift+Enter, Ctrl+Enter, or just Enter, the behavior is the same. The addition gets added to the clipboard as can be seen by pressing paste.

If I have an undo snapshot that looks like this:

--- lua/plugins/telescope.lua
+++ lua/plugins/telescope.lua
@@ -109,7 +109,7 @@
-  mappings = {
-    i = {
-      ['<cr>'] = function() vim.notify('enter') end,
-      ['<S-cr>'] = function() vim.notify('shift enter') end,
-      ['<C-cr>'] = function() vim.notify('ctrl enter') end,
-    },
-  },
+  --mappings = {
+  --      i = {
+  --              ['<cr>'] = function() vim.notify('enter') end,
+  --              ['<S-cr>'] = function() vim.notify('shift enter') end,
+  --              ['<C-cr>'] = function() vim.notify('ctrl enter') end,
+  --      },
+  --},

If i'm in INSERT mode (which I am when opening Telescope undo), I would expect Shift+Enter to yank:

mappings = {
  i = {
    ['<cr>'] = function() vim.notify('enter') end,
    ['<S-cr>'] = function() vim.notify('shift enter') end,
    ['<C-cr>'] = function() vim.notify('ctrl enter') end,
  },
},

And Ctrl+Enter to yank:

--mappings = {
--      i = {
--              ['<cr>'] = function() vim.notify('enter') end,
--              ['<S-cr>'] = function() vim.notify('shift enter') end,
--              ['<C-cr>'] = function() vim.notify('ctrl enter') end,
--      },
--},

Neither of these things happen and the addition is always yanked regardless of if I press Enter, Shift+Enter, or Ctrl+Enter. Same is true in normal mode with y, Y, and Enter.

As you can see from the example, I tried overriding the key mappings with a function call that prints a message. However, they don't get printed on key press. When I open telescope undo, I do see the 'enter' message which seems strange.

Here's the relevant parts of my lazy.nvim config:

https://github.com/freddiehaddad/nvim/blob/main/lua/plugins/telescope.lua

Error: Illegal Flag 's'

Hey!

I do have no idea if this is due to my setup or this plugin.
Anyway, can't seem to use it, well, actually, the preview doesn't work, it gives "Illegal flag 's'" ...

screenie

Please have a look.

My config:require

use({
    "nvim-telescope/telescope.nvim",
    requires = {
    "nvim-lua/popup.nvim",
    "nvim-lua/plenary.nvim",
    "tami5/sqlite.lua",
    "nvim-telescope/telescope-project.nvim",
    "nvim-telescope/telescope-smart-history.nvim",
    "nvim-telescope/telescope-frecency.nvim",
    "nvim-telescope/telescope-symbols.nvim",
    "nvim-telescope/telescope-node-modules.nvim",
    "nvim-telescope/telescope-github.nvim",
    "nvim-telescope/telescope-arecibo.nvim",
    "nvim-telescope/telescope-ui-select.nvim",
    "nvim-telescope/telescope-dap.nvim",
    -- "nvim-telescope/telescope-media-files.nvim",
    "~/.local/git/joehannes-os/telescope-media-files.nvim",
    -- "tom-anders/telescope-vim-bookmarks.nvim",
    "debugloop/telescope-undo.nvim",
    "sudormrfbin/cheatsheet.nvim",
    "AckslD/nvim-neoclip.lua",
    "rmagatti/auto-session",
    "rmagatti/session-lens",
    "Azeirah/nvim-redux",
    },
    config = function()
    local config = require("plugins/telescope")
    local neoclip = require("plugins/neoclip")

    config.setup()
    neoclip.setup()
    require("session-lens").setup({
        path_display = { "shorten" },
        theme_conf = { border = false },
        previewer = false,
    })
    end,
})

My config:setup

---@diagnostic disable: undefined-global
local config = {}

function config.setup()
  local trouble = require("trouble.providers.telescope")
  local telescope = require("telescope")
  local actions = require("telescope.actions")

  telescope.setup({
    -- find_command = {
    -- 	"rg",
    -- 	"--no-heading",
    -- 	"--with-filename",
    -- 	"--line-number",
    -- 	"--column",
    -- 	"--smart-case",
    -- },
    -- use_less = true,
    -- file_previewer = require("telescope.previewers").vim_buffer_cat.new,
    -- grep_previewer = require("telescope.previewers").vim_buffer_vimgrep.new,
    -- qflist_previewer = require("telescope.previewers").vim_buffer_qflist.new,
    pickers = {
      spell_suggest = {
        theme = "cursor",
      },
      lsp_code_actions = {
        theme = "cursor",
      },
      lsp_range_code_actions = {
        theme = "cursor",
      },
      buffers = {
        theme = "dropdown",
      },
      oldfiles = {
        theme = "dropdown",
      },
      git_branches = {
        theme = "dropdown",
      },
      find_files = {
        theme = "dropdown",
        hidden = true,
      },
      git_commits = {
        mappings = {
          i = {
            ["<CR>"] = function(prompt_bufnr)
              actions.close(prompt_bufnr)
              local value = actions.get_selected_entry(prompt_bufnr).value
              vim.cmd("DiffviewOpen " .. value .. "~1.." .. value)
            end,
          },
        },
      },
    },
    extensions = {
      -- arecibo = {
      --     ["selected_engine"] = 'google',
      --     ["url_open_command"] = 'open',
      --     ["show_http_headers"] = false,
      --     ["show_domain_icons"] = false
      -- },
      undo = {
        side_by_side = true,
        layout_strategy = "vertical",
        layout_config = {
          preview_height = 0.8,
        },
      },
      ["ui-select"] = {
        require("telescope.themes").get_dropdown {}
      },
      arecibo = {
        ["selected_engine"] = "google",
        ["url_open_command"] = "open",
        ["show_http_headers"] = false,
        ["show_domain_icons"] = false,
      },
      frecency = {
        db_root = vim.fn.stdpath("data") .. "/databases/",
        show_scores = false,
        show_unindexed = true,
        ignore_patterns = { "*.git/*", "*/tmp/*" },
        disable_devicons = false,
        workspaces = {
          ["conf"] = vim.fn.expand("$HOME") .. "/.config",
          ["data"] = vim.fn.expand("$HOME") .. "/.local/share",
          ["project"] = vim.fn.expand("$HOME") .. "./.local/git",
          ["wiki"] = vim.fn.expand("$HOME") .. "/wiki",
          ["orb"] = vim.fn.expand("$HOME") .. "/.local/git/orbital",
        },
      },
      media_files = {
        filetypes = { "png", "webp", "jpg", "jpeg", "mp4", "webm", "pdf" },
        find_cmd = "rg",
      },
      -- fzf = {
      --   fuzzy = true,
      --   override_generic_sorter = true,
      --   override_file_sorter = true,
      --   case_mode = "smart_case",
      -- },
      project = {
        base_dirs = {
          { path = "~/.config/nvim" },
          { path = "~/.local/git", max_depth = 3 },
        },
        hidden_files = true,
      },
      dash = {
        -- configure path to Dash.app if installed somewhere other than /Applications/Dash.app
        dash_app_path = '/Applications/Dash.app',
        -- search engine to fall back to when Dash has no results, must be one of: 'ddg', 'duckduckgo', 'startpage', 'google'
        search_engine = 'google',
        -- debounce while typing, in milliseconds
        debounce = 300,
        -- map filetype strings to the keywords you've configured for docsets in Dash
        -- setting to false will disable filtering by filetype for that filetype
        -- filetypes not included in this table will not filter the query by filetype
        -- check src/lua_bindings/dash_config_binding.rs to see all defaults
        -- the values you pass for file_type_keywords are merged with the defaults
        -- to disable filtering for all filetypes,
        -- set file_type_keywords = false
        file_type_keywords = {
          dashboard = false,
          NvimTree = false,
          TelescopePrompt = true,
          terminal = true,
          packer = true,
          fzf = false,
          -- a table of strings will search on multiple keywords
          lua = { "lua", "Neovim" },
          clojure = { 'clojure', 'clj', 'javascript', 'html', 'svg', 'css' },
          javascript = { 'javascript', 'html', 'svg', 'nodejs', 'css', 'sass', 'react' },
          typescript = { 'typescript', 'javascript', 'nodejs', 'html', 'svg', 'nodejs', 'css', 'sass' },
          typescriptreact = { 'typescript', 'javascript', 'html', 'svg', 'nodejs', 'css', 'sass', 'react' },
          javascriptreact = { 'javascript', 'html', 'svg', 'nodejs', 'css', 'sass', 'react' },
          -- you can also do a string, for example,
          -- sh = 'bash'
        },
      }
    },
    defaults = {
      mappings = {
        i = {
          ["<c-q>"] = actions.smart_send_to_qflist,
          ["<c-l>"] = trouble.open_with_trouble,
        },
        n = {
          ["<c-q>"] = actions.smart_send_to_qflist,
          ["<c-l>"] = trouble.open_with_trouble,
        },
      },
      history = {
        path = vim.fn.stdpath("data") .. "/databases/telescope_history.sqlite3",
        limit = 100,
      },
      preview = {
        mime_hook = function(filepath, bufnr, opts)
          local is_image = function(filepath)
            local image_extensions = { "png", "jpg", "jpeg", "gif" } -- Supported image formats
            local split_path = vim.split(filepath:lower(), ".", { plain = true })
            local extension = split_path[#split_path]
            return vim.tbl_contains(image_extensions, extension)
          end
          if is_image(filepath) then
            local term = vim.api.nvim_open_term(bufnr, {})
            local function send_output(_, data, _)
              for _, d in ipairs(data) do
                vim.api.nvim_chan_send(term, d .. "\r\n")
              end
            end

            vim.fn.jobstart({
              "viu",
              filepath,
            }, {
              on_stdout = send_output,
              stdout_buffered = true,
            })
          else
            require("telescope.previewers.utils").set_preview_message(
              bufnr,
              opts.winid,
              "Binary cannot be previewed"
            )
          end
        end,
      }
    },
  })

  -- telescope.load_extension("fzf")
  telescope.load_extension("gh")
  telescope.load_extension("dap")
  telescope.load_extension("node_modules")
  telescope.load_extension("session-lens")
  -- telescope.load_extension("vim_bookmarks")
  telescope.load_extension("project")
  telescope.load_extension("neoclip")
  telescope.load_extension("smart_history")
  -- telescope.load_extension("aerial")
  -- require('telescope').load_extension('snippets')
  telescope.load_extension("arecibo")
  telescope.load_extension("media_files")
  telescope.load_extension("frecency")
  telescope.load_extension("ui-select")
  telescope.load_extension("undo")
end

return config

No preview window

When I open the plugin no preview window is shown.

image

My config is as follows:

  {
    "nvim-telescope/telescope.nvim",
    dependencies = {
      { "nvim-lua/plenary.nvim" },
      {
        "debugloop/telescope-undo.nvim",
        config = function(plugin, opts)
          require "plugins.configs.telescope" (plugin, opts) -- include the default astronvim config that calls the setup call
          local telescope = require "telescope"
          telescope.setup {
            pickers = { oldfiles = { cwd_only = true } }, -- only show files in current directory
            extensions = {
              undo = {
                use_delta = true,
                side_by_side = true,
                layout_strategy = "vertical",
                layout_config = {
                  preview_height = 0.8,
                },
              },
            },
          }
          telescope.load_extension "undo"
        end,
      },
    },
    keys = {
      { "<leader>fu", "<cmd>Telescope undo<cr>", desc = "Open File Undo His. in Telescope" },
    },
  },

Not sure if this is how I've had to integrate the plugin with astronvim's telescope integration. However changing layout_strategy to horizontal works as expected and the preview window is shown.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.