Searching for the Line Under Cursor in Neovim Using Telescope

In this post, we’ll explore how to leverage Telescope to search for the line under the cursor. This can be particularly useful when you want to quickly find occurrences of a specific line across your project.

Prerequisites

Before we begin, ensure you have Neovim and the Telescope plugin installed. If you haven’t installed Telescope yet, you can add it to your Neovim configuration as follows:

use {
  'nvim-telescope/telescope.nvim',
  requires = {{'nvim-lua/plenary.nvim'}}
}

Mapping the Search Function

To create a mapping that searches for the line under the cursor, we need to define a custom function in our Neovim configuration. This function will use Telescope’s live_grep to search for the line’s content, taking care to handle special characters and whitespace.

Just add the following code to your init.lua or where you configure your Neovim mapings:

vim.key.set('n', '<leader>fl', function()
  local str = vim.fn.getline('.')
  -- Trim leading and trailing whitespace and escape newlines
  str = str:gsub('^%s*(.-)%s*$', '%1'):gsub('\n', '\\n')
  -- Escape regex characters including \n, ^, $, ., *, +, ?, (, ), [, ], {, }, |
  str = vim.fn.escape(str, '\\^$.*+?()[]{}|')
  require('telescope.builtin').live_grep({ default_text = str })
end)

Explanation of the Code

  • Mapping the Function: The vim.keymap.set function maps the custom search function to <leader>fl.
  • Retrieving the Line: vim.fn.getline('.') retrieves the current line under the cursor.
  • Trimming Whitespace: str:gsub('^%s*(.-)%s*$', '%1') removes leading and trailing whitespace from the line.
  • Escaping Newlines: str:gsub('\n', '\\n') ensures newlines are properly escaped.
  • Escaping Regex Characters: vim.fn.escape(str, '\\^$.*+?()[]{}|') escapes characters that have special meaning in regular expressions.
  • Live Grep with Telescope: require('telescope.builtin').live_grep({ default_text = str }) calls Telescope’s live_grep with the processed string as the default search text.

Usage

After adding the above code to your configuration, reload Neovim or restart it. Now, when you press <leader>fl in normal mode, Telescope will open with live_grep, pre-filled with the line under your cursor, allowing you to search for its occurrences quickly.

Conclusion

By adding this custom mapping to your Neovim setup, you can enhance your productivity and streamline your search workflow. Telescope’s powerful fuzzy finding capabilities, combined with Neovim’s extensibility, make it a robust solution for navigating large codebases.

Happy coding!

:wq