Streamline Codebase Maintenance: Project-Wide Find and Replace in Neovim with Telescope and Quickfix List

Posted by Chaitanya Shahare on Thu, Oct 19, 2023

Introduction

Maintaining an organized and efficient codebase is essential for every developer. Neovim, a powerful text editor, offers a range of tools that can help you make global changes throughout your project with ease.

In this blog post, we’ll explore how to perform a project-wide find and replace using Neovim, Telescope, the Quickfix List, and the :cdo command. No complicated jargon, just straightforward guidance to enhance your coding experience.

Prerequisites

Before you start, ensure you have the following prerequisites in place:

  1. Neovim installed.
  2. The Telescope plugin installed.
  3. A project directory opened in Neovim.

Using Telescope for Live Grep

1. Initiate Telescope

In Neovim’s Normal mode, execute the following command:

:Telescope live_grep

This opens the Telescope live grep prompt, ready for your query.

2. Enter Your Search Query

Type your search query. Telescope will display a list of search results throughout your project.

3. Open Results in Quickfix List

After searching for your query, press Ctrl + q to open the search results in the Quickfix List.

Utilizing :cdo for Find and Replace

4. Run the :cdo Command

With the Quickfix List open, you can now perform the find and replace operation. Execute the following command:

:cdo s/query_string/replacement_string/gc
  • :cdo applies a command to each entry in the Quickfix List.
  • s/query_string/replacement_string/gc is the find and replace command, with g for global replacement.
  • The /c flag provides confirmation before each replacement.

Press Enter to initiate the find and replace with confirmation.

5. Save Changes

If you’re satisfied with the changes and want to save them across all files in your project, you can use the :wa command:

:wa

Conclusion

Performing a project-wide find and replace in Neovim using Telescope, the Quickfix List, and the :cdo command is a potent approach that simplifies codebase maintenance. It allows you to make comprehensive changes while retaining full control over the replacement process, with the added /c flag providing a confirmation step for each replacement. By incorporating these techniques into your Neovim workflow, you’ll significantly improve your coding experience and efficiency. Use :wa to save your changes across all files and ensure your project is up to date.