Initial commit, working plugin

This commit is contained in:
Karol Krzosa
2026-02-16 13:46:13 +01:00
commit 3359d63c7c
16 changed files with 3824 additions and 0 deletions

5
.gitignore vendored Normal file
View File

@@ -0,0 +1,5 @@
out
dist
node_modules
.vscode-test/
*.vsix

5
.vscode-test.mjs Normal file
View File

@@ -0,0 +1,5 @@
import { defineConfig } from '@vscode/test-cli';
export default defineConfig({
files: 'out/test/**/*.test.js',
});

8
.vscode/extensions.json vendored Normal file
View File

@@ -0,0 +1,8 @@
{
// See http://go.microsoft.com/fwlink/?LinkId=827846
// for the documentation about the extensions.json format
"recommendations": [
"dbaeumer.vscode-eslint",
"ms-vscode.extension-test-runner"
]
}

21
.vscode/launch.json vendored Normal file
View File

@@ -0,0 +1,21 @@
// A launch configuration that compiles the extension and then opens it inside a new window
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
{
"version": "0.2.0",
"configurations": [
{
"name": "Run Extension",
"type": "extensionHost",
"request": "launch",
"args": [
"--extensionDevelopmentPath=${workspaceFolder}"
],
"outFiles": [
"${workspaceFolder}/out/**/*.js"
],
"preLaunchTask": "${defaultBuildTask}"
}
]
}

11
.vscode/settings.json vendored Normal file
View File

@@ -0,0 +1,11 @@
// Place your settings in this file to overwrite default and user settings.
{
"files.exclude": {
"out": false // set this to true to hide the "out" folder with the compiled JS files
},
"search.exclude": {
"out": true // set this to false to include "out" folder in search results
},
// Turn off tsc task auto detection since we have the necessary tasks as npm scripts
"typescript.tsc.autoDetect": "off"
}

20
.vscode/tasks.json vendored Normal file
View File

@@ -0,0 +1,20 @@
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
{
"version": "2.0.0",
"tasks": [
{
"type": "npm",
"script": "watch",
"problemMatcher": "$tsc-watch",
"isBackground": true,
"presentation": {
"reveal": "never"
},
"group": {
"kind": "build",
"isDefault": true
}
}
]
}

11
.vscodeignore Normal file
View File

@@ -0,0 +1,11 @@
.vscode/**
.vscode-test/**
src/**
.gitignore
.yarnrc
vsc-extension-quickstart.md
**/tsconfig.json
**/eslint.config.mjs
**/*.map
**/*.ts
**/.vscode-test.*

9
CHANGELOG.md Normal file
View File

@@ -0,0 +1,9 @@
# Change Log
All notable changes to the "vsctags" extension will be documented in this file.
Check [Keep a Changelog](http://keepachangelog.com/) for recommendations on how to structure this file.
## [Unreleased]
- Initial release

71
README.md Normal file
View File

@@ -0,0 +1,71 @@
# vsctags README
This is the README for your extension "vsctags". After writing up a brief description, we recommend including the following sections.
## Features
Describe specific features of your extension including screenshots of your extension in action. Image paths are relative to this README file.
For example if there is an image subfolder under your extension project workspace:
\!\[feature X\]\(images/feature-x.png\)
> Tip: Many popular extensions utilize animations. This is an excellent way to show off your extension! We recommend short, focused animations that are easy to follow.
## Requirements
If you have any requirements or dependencies, add a section describing those and how to install and configure them.
## Extension Settings
Include if your extension adds any VS Code settings through the `contributes.configuration` extension point.
For example:
This extension contributes the following settings:
* `myExtension.enable`: Enable/disable this extension.
* `myExtension.thing`: Set to `blah` to do something.
## Known Issues
Calling out known issues can help limit users opening duplicate issues against your extension.
## Release Notes
Users appreciate release notes as you update your extension.
### 1.0.0
Initial release of ...
### 1.0.1
Fixed issue #.
### 1.1.0
Added features X, Y, and Z.
---
## Following extension guidelines
Ensure that you've read through the extensions guidelines and follow the best practices for creating your extension.
* [Extension Guidelines](https://code.visualstudio.com/api/references/extension-guidelines)
## Working with Markdown
You can author your README using Visual Studio Code. Here are some useful editor keyboard shortcuts:
* Split the editor (`Cmd+\` on macOS or `Ctrl+\` on Windows and Linux).
* Toggle preview (`Shift+Cmd+V` on macOS or `Shift+Ctrl+V` on Windows and Linux).
* Press `Ctrl+Space` (Windows, Linux, macOS) to see a list of Markdown snippets.
## For more information
* [Visual Studio Code's Markdown Support](http://code.visualstudio.com/docs/languages/markdown)
* [Markdown Syntax Reference](https://help.github.com/articles/markdown-basics/)
**Enjoy!**

27
eslint.config.mjs Normal file
View File

@@ -0,0 +1,27 @@
import typescriptEslint from "typescript-eslint";
export default [{
files: ["**/*.ts"],
}, {
plugins: {
"@typescript-eslint": typescriptEslint.plugin,
},
languageOptions: {
parser: typescriptEslint.parser,
ecmaVersion: 2022,
sourceType: "module",
},
rules: {
"@typescript-eslint/naming-convention": ["warn", {
selector: "import",
format: ["camelCase", "PascalCase"],
}],
curly: "warn",
eqeqeq: "warn",
"no-throw-literal": "warn",
semi: "warn",
},
}];

3180
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

43
package.json Normal file
View File

@@ -0,0 +1,43 @@
{
"name": "vsctags",
"displayName": "vsctags",
"description": "Very cool project that leverages ctags to implement go to definition waow",
"version": "0.0.1",
"engines": {
"vscode": "^1.109.0"
},
"categories": [
"Other"
],
"extensionKind": ["workspace"],
"activationEvents": [
"onStartupFinished"
],
"main": "./out/extension.js",
"contributes": {
"commands": [
{
"command": "vsctags.reloadTags",
"title": "vsctags: Reload Tags"
}
]
},
"scripts": {
"vscode:prepublish": "npm run compile",
"compile": "tsc -p ./",
"watch": "tsc -watch -p ./",
"pretest": "npm run compile && npm run lint",
"lint": "eslint src",
"test": "vscode-test"
},
"devDependencies": {
"@types/vscode": "^1.109.0",
"@types/mocha": "^10.0.10",
"@types/node": "22.x",
"typescript-eslint": "^8.54.0",
"eslint": "^9.39.2",
"typescript": "^5.9.3",
"@vscode/test-cli": "^0.0.12",
"@vscode/test-electron": "^2.5.2"
}
}

337
src/extension.ts Normal file
View File

@@ -0,0 +1,337 @@
import * as vscode from "vscode";
import * as path from "path";
import * as fs from "fs";
/** A single parsed ctags entry */
interface CtagsEntry {
name: string;
file: string;
pattern: string;
kind: string;
lineNumber: number;
fields: Map<string, string>;
}
function parseCtagsFile(content: string, workspaceRoot: string): CtagsEntry[] {
const entries: CtagsEntry[] = [];
const lines = content.split("\n");
for (const line of lines) {
if (line.startsWith("!_TAG_") || line.trim() === "") {
continue;
}
const firstTab = line.indexOf("\t");
if (firstTab === -1) { continue; }
const secondTab = line.indexOf("\t", firstTab + 1);
if (secondTab === -1) { continue; }
const name = line.substring(0, firstTab);
const file = line.substring(firstTab + 1, secondTab);
const rest = line.substring(secondTab + 1);
let pattern = "";
let kind = "";
let lineNumber = 0;
const fields = new Map<string, string>();
const exCmdEnd = rest.indexOf(';\"');
if (exCmdEnd !== -1) {
pattern = rest.substring(0, exCmdEnd);
const afterExCmd = rest.substring(exCmdEnd + 2);
const parts = afterExCmd.split("\t").filter((s) => s.length > 0);
if (parts.length > 0) { kind = parts[0]; }
for (let i = 1; i < parts.length; i++) {
const colon = parts[i].indexOf(":");
if (colon !== -1) {
fields.set(parts[i].substring(0, colon), parts[i].substring(colon + 1));
}
}
} else {
pattern = rest;
}
const lineField = fields.get("line");
if (lineField) {
lineNumber = Math.max(0, parseInt(lineField, 10) - 1);
} else if (/^\d+$/.test(pattern.trim())) {
lineNumber = Math.max(0, parseInt(pattern.trim(), 10) - 1);
} else {
lineNumber = resolvePatternLineNumber(pattern, file, workspaceRoot);
}
entries.push({ name, file, pattern, kind, lineNumber, fields });
}
return entries;
}
function resolvePatternLineNumber(
pattern: string,
relativeFile: string,
workspaceRoot: string,
): number {
let searchText = pattern;
if (searchText.startsWith("/^")) {
searchText = searchText.substring(2);
} else if (searchText.startsWith("/")) {
searchText = searchText.substring(1);
}
if (searchText.endsWith("$/")) {
searchText = searchText.substring(0, searchText.length - 2);
} else if (searchText.endsWith("/")) {
searchText = searchText.substring(0, searchText.length - 1);
}
searchText = searchText.replace(/\\\//g, "/").replace(/\\\\/g, "\\");
if (searchText.length === 0) {
return 0;
}
const absPath = path.join(workspaceRoot, relativeFile);
try {
const fileContent = fs.readFileSync(absPath, "utf-8");
const fileLines = fileContent.split("\n");
for (let i = 0; i < fileLines.length; i++) {
if (fileLines[i].includes(searchText)) {
return i;
}
}
} catch {
// file not readable
}
return 0;
}
type CtagsIndex = Map<string, CtagsEntry[]>;
function buildIndex(entries: CtagsEntry[]): CtagsIndex {
const index: CtagsIndex = new Map();
for (const entry of entries) {
let list = index.get(entry.name);
if (!list) {
list = [];
index.set(entry.name, list);
}
list.push(entry);
}
return index;
}
function entryToLocation(entry: CtagsEntry, root: string): vscode.Location {
const uri = vscode.Uri.file(path.join(root, entry.file));
const pos = new vscode.Position(entry.lineNumber, 0);
return new vscode.Location(uri, pos);
}
function entryToSymbolKind(kind: string): vscode.SymbolKind {
switch (kind) {
case "f": case "function": case "func":
return vscode.SymbolKind.Function;
case "c": case "class":
return vscode.SymbolKind.Class;
case "m": case "method": case "member":
return vscode.SymbolKind.Method;
case "v": case "variable": case "var":
return vscode.SymbolKind.Variable;
case "s": case "struct": case "structure":
return vscode.SymbolKind.Struct;
case "e": case "enum": case "enumerator":
return vscode.SymbolKind.Enum;
case "i": case "interface":
return vscode.SymbolKind.Interface;
case "n": case "namespace":
return vscode.SymbolKind.Namespace;
case "d": case "macro": case "define":
return vscode.SymbolKind.Constant;
case "t": case "typedef": case "type":
return vscode.SymbolKind.TypeParameter;
case "p": case "property": case "prop":
return vscode.SymbolKind.Property;
case "g": case "enumeration":
return vscode.SymbolKind.Enum;
default:
return vscode.SymbolKind.Variable;
}
}
function getWordAtPosition(
document: vscode.TextDocument,
position: vscode.Position,
): string | undefined {
const range = document.getWordRangeAtPosition(position);
if (!range) { return undefined; }
return document.getText(range);
}
// ---- Extension State ----
let allEntries: CtagsEntry[] = [];
let tagIndex: CtagsIndex = new Map();
let wsRoot = "";
function loadTags(): boolean {
if (!wsRoot) { return false; }
const tagsPath = path.join(wsRoot, "tags");
try {
const content = fs.readFileSync(tagsPath, "utf-8");
allEntries = parseCtagsFile(content, wsRoot);
tagIndex = buildIndex(allEntries);
console.log(`[vsctags] Loaded ${allEntries.length} tags from ${tagsPath}`);
return true;
} catch {
console.log(`[vsctags] No tags file found at ${tagsPath}`);
allEntries = [];
tagIndex = new Map();
return false;
}
}
// ---- Providers ----
class CtagsDefinitionProvider implements vscode.DefinitionProvider {
provideDefinition(
document: vscode.TextDocument,
position: vscode.Position,
): vscode.Location[] | undefined {
const word = getWordAtPosition(document, position);
if (!word) { return undefined; }
const entries = tagIndex.get(word);
if (!entries || entries.length === 0) { return undefined; }
return entries.map((e) => entryToLocation(e, wsRoot));
}
}
class CtagsHoverProvider implements vscode.HoverProvider {
provideHover(
document: vscode.TextDocument,
position: vscode.Position,
): vscode.Hover | undefined {
const word = getWordAtPosition(document, position);
if (!word) { return undefined; }
const entries = tagIndex.get(word);
if (!entries || entries.length === 0) { return undefined; }
const lines: string[] = [];
for (const entry of entries) {
let label = `**${entry.name}**`;
if (entry.kind) { label += ` _(${entry.kind})_`; }
label += ` \u2014 ${entry.file}:${entry.lineNumber + 1}`;
const scope = entry.fields.get("scope") || entry.fields.get("class");
if (scope) { label += ` [${scope}]`; }
lines.push(label);
}
return new vscode.Hover(new vscode.MarkdownString(lines.join("\n\n")));
}
}
class CtagsWorkspaceSymbolProvider implements vscode.WorkspaceSymbolProvider {
provideWorkspaceSymbols(query: string): vscode.SymbolInformation[] {
const results: vscode.SymbolInformation[] = [];
const lowerQuery = query.toLowerCase();
for (const entry of allEntries) {
if (lowerQuery && !entry.name.toLowerCase().includes(lowerQuery)) {
continue;
}
results.push(
new vscode.SymbolInformation(
entry.name,
entryToSymbolKind(entry.kind),
entry.fields.get("scope") || entry.fields.get("class") || "",
entryToLocation(entry, wsRoot),
),
);
if (results.length >= 500) { break; }
}
return results;
}
}
class CtagsDocumentSymbolProvider implements vscode.DocumentSymbolProvider {
provideDocumentSymbols(
document: vscode.TextDocument,
): vscode.SymbolInformation[] {
const relPath = vscode.workspace.asRelativePath(document.uri, false);
const results: vscode.SymbolInformation[] = [];
for (const entry of allEntries) {
if (entry.file === relPath) {
results.push(
new vscode.SymbolInformation(
entry.name,
entryToSymbolKind(entry.kind),
entry.fields.get("scope") || entry.fields.get("class") || "",
entryToLocation(entry, wsRoot),
),
);
}
}
return results;
}
}
class CtagsReferenceProvider implements vscode.ReferenceProvider {
provideReferences(
document: vscode.TextDocument,
position: vscode.Position,
): vscode.Location[] | undefined {
const word = getWordAtPosition(document, position);
if (!word) { return undefined; }
const entries = tagIndex.get(word);
if (!entries || entries.length === 0) { return undefined; }
return entries.map((e) => entryToLocation(e, wsRoot));
}
}
// ---- Activation ----
export function activate(context: vscode.ExtensionContext) {
const folders = vscode.workspace.workspaceFolders;
if (!folders || folders.length === 0) { return; }
wsRoot = folders[0].uri.fsPath;
loadTags();
const allLangs = { scheme: "file" };
context.subscriptions.push(
vscode.languages.registerDefinitionProvider(allLangs, new CtagsDefinitionProvider()),
vscode.languages.registerHoverProvider(allLangs, new CtagsHoverProvider()),
vscode.languages.registerWorkspaceSymbolProvider(new CtagsWorkspaceSymbolProvider()),
vscode.languages.registerDocumentSymbolProvider(allLangs, new CtagsDocumentSymbolProvider()),
vscode.languages.registerReferenceProvider(allLangs, new CtagsReferenceProvider()),
);
// Watch the tags file for changes
const tagsPattern = new vscode.RelativePattern(folders[0], "tags");
const watcher = vscode.workspace.createFileSystemWatcher(tagsPattern);
watcher.onDidChange(() => {
loadTags();
vscode.window.showInformationMessage("[vsctags] Tags file reloaded.");
});
watcher.onDidCreate(() => {
loadTags();
vscode.window.showInformationMessage("[vsctags] Tags file loaded.");
});
watcher.onDidDelete(() => {
allEntries = [];
tagIndex = new Map();
vscode.window.showInformationMessage("[vsctags] Tags file removed.");
});
context.subscriptions.push(watcher);
context.subscriptions.push(
vscode.commands.registerCommand("vsctags.reloadTags", () => {
if (loadTags()) {
vscode.window.showInformationMessage(`[vsctags] Reloaded ${allEntries.length} tags.`);
} else {
vscode.window.showWarningMessage("[vsctags] No tags file found.");
}
}),
);
console.log(`[vsctags] Activated with ${allEntries.length} tags.`);
}
export function deactivate() {}

View File

@@ -0,0 +1,15 @@
import * as assert from 'assert';
// You can import and use all API from the 'vscode' module
// as well as import your extension to test it
import * as vscode from 'vscode';
// import * as myExtension from '../../extension';
suite('Extension Test Suite', () => {
vscode.window.showInformationMessage('Start all tests.');
test('Sample test', () => {
assert.strictEqual(-1, [1, 2, 3].indexOf(5));
assert.strictEqual(-1, [1, 2, 3].indexOf(0));
});
});

17
tsconfig.json Normal file
View File

@@ -0,0 +1,17 @@
{
"compilerOptions": {
"module": "Node16",
"target": "ES2022",
"outDir": "out",
"lib": [
"ES2022"
],
"sourceMap": true,
"rootDir": "src",
"strict": true, /* enable all strict type-checking options */
/* Additional Checks */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
}
}

View File

@@ -0,0 +1,44 @@
# Welcome to your VS Code Extension
## What's in the folder
* This folder contains all of the files necessary for your extension.
* `package.json` - this is the manifest file in which you declare your extension and command.
* The sample plugin registers a command and defines its title and command name. With this information VS Code can show the command in the command palette. It doesnt yet need to load the plugin.
* `src/extension.ts` - this is the main file where you will provide the implementation of your command.
* The file exports one function, `activate`, which is called the very first time your extension is activated (in this case by executing the command). Inside the `activate` function we call `registerCommand`.
* We pass the function containing the implementation of the command as the second parameter to `registerCommand`.
## Get up and running straight away
* Press `F5` to open a new window with your extension loaded.
* Run your command from the command palette by pressing (`Ctrl+Shift+P` or `Cmd+Shift+P` on Mac) and typing `Hello World`.
* Set breakpoints in your code inside `src/extension.ts` to debug your extension.
* Find output from your extension in the debug console.
## Make changes
* You can relaunch the extension from the debug toolbar after changing code in `src/extension.ts`.
* You can also reload (`Ctrl+R` or `Cmd+R` on Mac) the VS Code window with your extension to load your changes.
## Explore the API
* You can open the full set of our API when you open the file `node_modules/@types/vscode/index.d.ts`.
## Run tests
* Install the [Extension Test Runner](https://marketplace.visualstudio.com/items?itemName=ms-vscode.extension-test-runner)
* Run the "watch" task via the **Tasks: Run Task** command. Make sure this is running, or tests might not be discovered.
* Open the Testing view from the activity bar and click the Run Test" button, or use the hotkey `Ctrl/Cmd + ; A`
* See the output of the test result in the Test Results view.
* Make changes to `src/test/extension.test.ts` or create new test files inside the `test` folder.
* The provided test runner will only consider files matching the name pattern `**.test.ts`.
* You can create folders inside the `test` folder to structure your tests any way you want.
## Go further
* [Follow UX guidelines](https://code.visualstudio.com/api/ux-guidelines/overview) to create extensions that seamlessly integrate with VS Code's native interface and patterns.
* Reduce the extension size and improve the startup time by [bundling your extension](https://code.visualstudio.com/api/working-with-extensions/bundling-extension).
* [Publish your extension](https://code.visualstudio.com/api/working-with-extensions/publishing-extension) on the VS Code extension marketplace.
* Automate builds by setting up [Continuous Integration](https://code.visualstudio.com/api/working-with-extensions/continuous-integration).
* Integrate to the [report issue](https://code.visualstudio.com/api/get-started/wrapping-up#issue-reporting) flow to get issue and feature requests reported by users.