Creating a PySide6 window within the Notepad++ PythonScript plugin environment can be challenging, as the plugin may not fully support integration with PySide6 due to threading and event loop issues. However, we can achieve similar functionality using the built-in forms module provided by the PythonScript plugin, which allows us to create GUI elements using Windows Forms.
Below, I'll provide a Python script that implements a fuzzy search in Notepad++ using the TheFuzz library and creates a custom search dialog using the forms module. The script will:
- Display a search window where the user can input the search term.
- Show a list of matching results with their scores.
- Allow the user to navigate between results using "Next" and "Previous" buttons.
- Move the editor view to the line of the selected result.
- Highlight the current result in focus.
Python Script for Fuzzy Search in Notepad++
Prerequisites:
- PythonScript Plugin: Ensure that you have the PythonScript plugin installed in Notepad++.
- TheFuzz Library: Install the
TheFuzz library in the Python environment used by the PythonScript plugin. You can usually find the Python executable used by the plugin and run:
pip install thefuzz
# Import necessary modules
from Npp import *
import re
import sys
# Import TheFuzz for fuzzy search
from thefuzz import process
# Import forms module from PythonScript plugin
import clr
clr.AddReference('System.Windows.Forms')
clr.AddReference('System.Drawing')
from System.Windows.Forms import Form, Label, TextBox, Button, ListBox, DockStyle, AnchorStyles, MessageBox, MessageBoxButtons, DialogResult
from System.Drawing import Point, Size, Font, FontStyle
class FuzzySearchForm(Form):
def __init__(self):
self.Text = "Fuzzy Search"
self.Width = 600
self.Height = 400
self.MinimumSize = Size(400, 300)
self.search_label = Label()
self.search_label.Text = "Search:"
self.search_label.Location = Point(10, 10)
self.search_label.AutoSize = True
self.search_input = TextBox()
self.search_input.Location = Point(70, 10)
self.search_input.Width = 400
self.search_button = Button()
self.search_button.Text = "Search"
self.search_button.Location = Point(480, 8)
self.search_button.Click += self.perform_search
self.result_list = ListBox()
self.result_list.Location = Point(10, 40)
self.result_list.Size = Size(560, 280)
self.result_list.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right
self.result_list.DoubleClick += self.goto_result
self.prev_button = Button()
self.prev_button.Text = "Previous"
self.prev_button.Location = Point(10, 330)
self.prev_button.Click += self.prev_result
self.prev_button.Enabled = False
self.next_button = Button()
self.next_button.Text = "Next"
self.next_button.Location = Point(100, 330)
self.next_button.Click += self.next_result
self.next_button.Enabled = False
self.Controls.Add(self.search_label)
self.Controls.Add(self.search_input)
self.Controls.Add(self.search_button)
self.Controls.Add(self.result_list)
self.Controls.Add(self.prev_button)
self.Controls.Add(self.next_button)
self.results = []
self.current_index = -1
def perform_search(self, sender, args):
search_text = self.search_input.Text
if not search_text:
MessageBox.Show("Please enter search text.", "Warning")
return
# Get the text from the current document
doc_text = editor.getText()
lines = doc_text.splitlines()
# Use TheFuzz to find matches
self.results = []
for idx, line in enumerate(lines):
# Set a threshold for matching, e.g., ratio >= 70
ratio = process.extractOne(search_text, [line])[1]
if ratio >= 70:
self.results.append({'index': idx, 'line': line, 'ratio': ratio})
# Sort results by ratio
self.results.sort(key=lambda x: -x['ratio'])
# Populate the result list
self.result_list.Items.Clear()
for result in self.results:
display_text = f"Line {result['index'] + 1}: {result['line']} (Score: {result['ratio']})"
self.result_list.Items.Add(display_text)
self.current_index = -1
if self.results:
self.next_button.Enabled = True
self.prev_button.Enabled = True
self.next_result(None, None)
else:
self.next_button.Enabled = False
self.prev_button.Enabled = False
MessageBox.Show("No matches found.", "Information")
def goto_result(self, sender, args):
index = self.result_list.SelectedIndex
if index >= 0:
self.current_index = index
self.highlight_result()
def highlight_result(self):
if 0 <= self.current_index < len(self.results):
line_number = self.results[self.current_index]['index']
# Move editor to the line
editor.gotoLine(line_number)
# Highlight the line
start = editor.positionFromLine(line_number)
end = editor.getLineEndPosition(line_number)
editor.setSelectionStart(start)
editor.setSelectionEnd(end)
# Ensure the line is visible
editor.ensureVisible(line_number)
# Update the selection in the list
self.result_list.SelectedIndex = self.current_index
def next_result(self, sender, args):
if self.current_index < len(self.results) - 1:
self.current_index += 1
self.highlight_result()
else:
MessageBox.Show("Reached the last result.", "Information")
def prev_result(self, sender, args):
if self.current_index > 0:
self.current_index -= 1
self.highlight_result()
else:
MessageBox.Show("Reached the first result.", "Information")
# Show the form
form = FuzzySearchForm()
form.ShowDialog()
Instructions:
-
Copy the Script:
- Copy the script above into a new script file in the PythonScript plugin:
- In Notepad++, go to
Plugins > Python Script > New Script.
- Name the script, e.g.,
FuzzySearch.py.
-
Install TheFuzz Library:
-
Run the Script:
- In Notepad++, go to
Plugins > Python Script > Scripts > Select your script (FuzzySearch.py).
- The "Fuzzy Search" window will appear.
-
Using the Fuzzy Search Window:
- Search:
- Enter the search text in the input field.
- Click the
Search button.
- Results:
- Matching lines are displayed with their corresponding line numbers and scores.
- Double-click a result to navigate to that line in the editor.
- Navigation:
- Use the
Next and Previous buttons to iterate over the results.
- The editor view will move to the line of the current result, and the line will be highlighted.
Features:
- Search Input:
- Enter any text to search for fuzzy matches within the current document.
- Results List:
- Displays the matching lines with line numbers and fuzzy matching scores.
- Results are sorted by relevance (highest score first).
- Navigation Buttons:
Next and Previous buttons allow you to iterate through the results.
- The current result is highlighted in the editor.
- Interactive Results:
- Double-click on any result in the list to jump directly to that line.
Notes:
-
Threshold Adjustment:
- The matching threshold is currently set to 70.
- To adjust the sensitivity, modify the line in the
perform_search method:
if ratio >= 70:
- Increase the value to make the search stricter or decrease it for looser matching.
-
Encoding Issues:
- If you encounter encoding issues, ensure that your document is saved with UTF-8 encoding.
-
Large Documents:
- For very large documents, the search may take longer. Be patient as the script processes the lines.
Troubleshooting:
I hope this script meets your requirements and provides the fuzzy search functionality in Notepad++ as you requested. Let me know if you have any questions or need further assistance!