Creating a Visual Studio Code (VSCode) extension that integrates the fuzzy-search library can enhance your development workflow by providing powerful fuzzy search capabilities within the editor. Below is a step-by-step guide to help you create this extension from scratch.
Table of Contents
- Prerequisites
- Setting Up the Extension Scaffolding
- Installing the Fuzzy Search Library
- Implementing the Extension Functionality
- Testing the Extension
- Packaging and Publishing the Extension
- Sample Code Structure
Prerequisites
Before you begin, ensure you have the following installed on your machine:
Setting Up the Extension Scaffolding
VSCode provides a Yeoman generator that streamlines the process of setting up a new extension.
-
Generate the Extension Scaffold:
Open your terminal and run:
yo code
-
Answer the Prompts:
You'll be prompted with several questions. Here's a recommended setup:
- What type of extension do you want to create?:
New Extension (TypeScript)
- What's the name of your extension?:
fuzzy-search-extension
- What's the identifier of your extension?:
fuzzy-search-extension (or any unique identifier)
- Description:
A VSCode extension integrating fuzzy search functionality
- Enable Git?:
Yes
- Which package manager to use?:
npm
This will create a new directory named fuzzy-search-extension with the necessary files.
-
Navigate to the Directory:
cd fuzzy-search-extension
-
Open in VSCode:
code .
Installing the Fuzzy Search Library
Assuming the fuzzy-search library from m31coding/fuzzy-search is available as an npm package, you can install it directly. If it's not published to npm, you'll need to include it manually or publish it first.
-
Install via npm:
npm install fuzzy-search --save
Note: Replace fuzzy-search with the actual npm package name. If it's not available on npm, consider cloning the repository and including it in your project or publishing it to npm first.
-
If Not on npm:
Clone the repository and include it as a dependency:
git clone https://github.com/m31coding/fuzzy-search.git
Then, you can reference it in your extension's code, or better yet, package it as a local module.
Implementing the Extension Functionality
We'll create a simple command that takes user input, performs a fuzzy search on a predefined list of items, and displays the results.
-
Define the Command:
Open package.json and locate the contributes section. Update the commands array to define a new command.
"contributes": {
"commands": [
{
"command": "fuzzySearchExtension.search",
"title": "Fuzzy Search"
}
]
}
-
Register the Command:
Open src/extension.ts and modify it to register your new command.
import * as vscode from 'vscode';
import * as FuzzySearch from 'fuzzy-search'; // Adjust the import based on the actual library
export function activate(context: vscode.ExtensionContext) {
let disposable = vscode.commands.registerCommand('fuzzySearchExtension.search', async () => {
// Prompt the user for a search query
const query = await vscode.window.showInputBox({
placeHolder: 'Enter search query'
});
if (!query) {
vscode.window.showInformationMessage('Search query was empty.');
return;
}
// Example list to search from
const items = [
'Apple',
'Banana',
'Orange',
'Grapes',
'Pineapple',
'Mango',
'Strawberry',
'Blueberry',
'Watermelon'
];
// Initialize fuzzy search
const searcher = new FuzzySearch(items, [], {
caseSensitive: false,
});
// Perform search
const results = searcher.search(query);
if (results.length === 0) {
vscode.window.showInformationMessage('No matches found.');
} else {
// Display results in a quick pick
const selected = await vscode.window.showQuickPick(results, {
placeHolder: 'Select an item'
});
if (selected) {
vscode.window.showInformationMessage(`You selected: ${selected}`);
}
}
});
context.subscriptions.push(disposable);
}
export function deactivate() {}
Note: Adjust the import statement based on how the fuzzy-search library exports its functionality. For example, it might be a default export or require a different syntax.
-
Ensure TypeScript Compatibility:
If the fuzzy-search library doesn't have type definitions, you might need to add a declaration to avoid TypeScript errors. Create a file named fuzzy-search.d.ts in the src directory:
declare module 'fuzzy-search' {
export default class FuzzySearch {
constructor(
data: string[],
keys?: string[],
options?: {
caseSensitive?: boolean;
sort?: boolean;
tokenize?: boolean;
matchAllTokens?: boolean;
}
);
search(query: string): string[];
}
}
Testing the Extension
-
Compile the Extension:
Since we're using TypeScript, compile the code:
npm run compile
-
Run the Extension in VSCode:
- Press
F5 in VSCode to launch a new Extension Development Host window.
- In the new window, open the Command Palette (
Ctrl+Shift+P or Cmd+Shift+P on macOS).
- Type and select
Fuzzy Search to invoke your command.
- Enter a search query in the input box.
- Choose an item from the displayed results.
-
Debugging:
If something doesn't work as expected, return to your main extension window, review the code, and check the Debug Console for errors.
Packaging and Publishing the Extension
Once you're satisfied with your extension, you can package and publish it to the VSCode Marketplace.
-
Install vsce (VSCode Extension Manager):
npm install -g vsce
-
Create a Publisher:
If you haven't created a publisher yet, follow Microsoft's guide.
-
Package the Extension:
vsce package
This will generate a .vsix file.
-
Publish the Extension:
vsce publish
Ensure you increment the version number in package.json for subsequent releases.
Sample Code Structure
Here's an overview of what your project structure might look like:
fuzzy-search-extension/
├── .vscode/
│ └── launch.json
├── src/
│ ├── extension.ts
│ └── fuzzy-search.d.ts
├── .gitignore
├── package.json
├── README.md
├── tsconfig.json
└── vsc-extension-quickstart.md
Additional Enhancements
Depending on your use case, you might consider the following enhancements:
- Dynamic Data Sources: Instead of a static list, fetch data from the workspace, open files, or external APIs.
- Configurable Options: Allow users to customize fuzzy search options via the extension settings.
- UI Enhancements: Use webviews or tree views to display search results more effectively.
- Performance Optimization: Handle large datasets efficiently to ensure smooth user experience.
Conclusion
By following the steps above, you can create a VSCode extension that leverages the fuzzy-search library to provide enhanced search capabilities within the editor. Customize and expand upon this foundation to suit your specific needs and improve your development workflow.
If you encounter any issues or have further questions, feel free to ask!