Search code examples
windowswindows-10sublimetext3

Exclude folded code in Sublime Text search


Is there any way to exclude folded code from search. When I search for text and that text appears to be in folded part of the code Sublime always unfolds that code snippet and its annoying. I could not find any settings regarding it.


Solution

  • You can make use of Sublime Text's "Find In Selection" feature - select all the unfolded regions, then open the find panel and perform your search with "in selection" toggled on.

    Here is a plugin to do this:

    import sublime
    import sublime_plugin
    
    
    class FindInUnfoldedTextCommand(sublime_plugin.TextCommand):
        def run(self, edit):
            folded_regions = self.view.folded_regions()
            self.view.sel().clear()
            self.view.sel().add_all(folded_regions)
            self.view.run_command('invert_selection')
            self.view.window().run_command('show_panel', { "panel": "find", "reverse": False, "in_selection": True })
    

    To set this up:

    1. from the Tools menu -> Developer -> New Plugin...

    2. select the template plugin code and replace it with the above

    3. save it, in the folder ST recommends (Packages/User/) with a name like find_in_unfolded_text.py - the filename isn't important, just the extension is.

    4. Open the ST console (View menu -> Show Console)

    5. Type/paste view.run_command('find_in_unfolded_text') Enter

    6. Enter your search string

    7. Violia! The folded text is ignored.

    As an alternative to steps 4 and 5, you can add this new command to the menu, to the command palette, or create a keybinding for it.