Full Code of chrmarti/vscode-regex for AI

main 61b0b2f11c2d cached
12 files
26.3 KB
6.3k tokens
5 symbols
1 requests
Download .txt
Repository: chrmarti/vscode-regex
Branch: main
Commit: 61b0b2f11c2d
Files: 12
Total size: 26.3 KB

Directory structure:
gitextract_a12zpu6_/

├── .github/
│   └── assignment.yml
├── .gitignore
├── .vscode/
│   ├── launch.json
│   ├── settings.json
│   └── tasks.json
├── .vscodeignore
├── LICENSE
├── README.md
├── package.json
├── src/
│   ├── chat.ts
│   └── extension.ts
└── tsconfig.json

================================================
FILE CONTENTS
================================================

================================================
FILE: .github/assignment.yml
================================================
{
    perform: true,
    assignees: [ chrmarti ]
}


================================================
FILE: .gitignore
================================================
out
node_modules
*.vsix

================================================
FILE: .vscode/launch.json
================================================
// 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}/dist/**/*.js"
			],
			"preLaunchTask": "${defaultBuildTask}"
		},
	]
}


================================================
FILE: .vscode/settings.json
================================================
// 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"
}

================================================
FILE: .vscode/tasks.json
================================================
// 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
			}
		}
	]
}


================================================
FILE: .vscodeignore
================================================
.vscode/**
.github/**
out/test/**
test/**
src/**
**/*.map
.gitignore
tsconfig.json


================================================
FILE: LICENSE
================================================
Copyright (c) Microsoft Corporation

All rights reserved.

MIT License

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy,
modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

================================================
FILE: README.md
================================================
## Features

Shows the current regular expression's matches in a side-by-side document. This can be turned on/off with `Ctrl+Alt+M` (`⌥⌘M`).

Global and multiline options can be added for evaluation with a side-by-side document through a status bar entry. This can be useful when the side-by-side document has multiple examples to match.

![Regex Previewer in Action](images/in_action.gif)

## Release Notes

### 0.6.0

- Add support for `d` flag in TypeScript/JavaScript (PR by [@wszgrcy](https://github.com/wszgrcy))

### 0.5.0

- Add chat participant

### 0.4.0

- Also publish as web extension

### 0.3.0

- Add React support (PR by [@galangel](https://github.com/galangel))
- Add Vue support (PR by [@jombard](https://github.com/jombard))
- Code cleanup

### 0.2.0

- Add PHP support (PR by [@ergunsh](https://github.com/ergunsh))
- Add setting to disable the code lens (PR by [@ergunsh](https://github.com/ergunsh))
- Add more sample text (PR by [@mscolnick](https://github.com/mscolnick))

### 0.1.0

- Status bar item to toggle adding global and multiline flags for evaluation with example text.
- Bugfixes

### 0.0.8

- Add Haxe support (PR by [@Gama11](https://github.com/Gama11))

### 0.0.7

- Several bugfixes
- Catch up with latest release

### 0.0.6

- Single toggle action to turn Regex matching on/off

### 0.0.5

- Make it work on Windows again...

### 0.0.4

- Allow any editor to show matches
- Avoid storing sample file in installation directory
- More bugfixes

### 0.0.3

- More bugfixes, make it work on Windows.
- Add icon

### 0.0.2

Bugfixes.

### 0.0.1

Initial release.

## License

[MIT](LICENSE)


================================================
FILE: package.json
================================================
{
  "name": "regex",
  "displayName": "Regex Previewer",
  "description": "Regex matches previewer for JavaScript, TypeScript, PHP and Haxe in Visual Studio Code.",
  "version": "0.6.0",
  "publisher": "chrmarti",
  "repository": {
    "type": "git",
    "url": "https://github.com/chrmarti/vscode-regex.git"
  },
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/chrmarti/vscode-regex/issues"
  },
  "keywords": [
    "regex",
    "regular expression",
    "regexp",
    "test"
  ],
  "icon": "images/icon.png",
  "engines": {
    "vscode": "^1.92.0"
  },
  "categories": [
    "Other",
    "Chat",
    "AI"
  ],
  "activationEvents": [
    "onLanguage:javascript",
    "onLanguage:javascriptreact",
    "onLanguage:typescript",
    "onLanguage:typescriptreact",
    "onLanguage:vue",
    "onLanguage:php",
    "onLanguage:haxe"
  ],
  "main": "./out/extension",
  "browser": "./out/extension",
  "contributes": {
    "configuration": {
      "type": "object",
      "title": "Regex Previewer Configuration",
      "properties": {
        "regex-previewer.enableCodeLens": {
          "scope": "resource",
          "type": "boolean",
          "default": true,
          "description": "Enables code lens for Regex Previewer"
        }
      }
    },
    "commands": [
      {
        "command": "extension.toggleRegexPreview",
        "title": "Toggle Regex Preview In Side-By-Side Editors"
      }
    ],
    "keybindings": [
      {
        "command": "extension.toggleRegexPreview",
        "key": "ctrl+alt+m",
        "mac": "cmd+alt+m"
      }
    ],
    "chatParticipants": [
      {
        "id": "regex.chatParticipant",
        "fullName": "Regex",
        "name": "regex",
        "description": "Talk to me about regexes!",
        "isSticky": true,
        "commands": [
          {
            "name": "new",
            "description": "Create a new regex from a description",
            "disambiguation": [
              {
                "category": "regex_new",
                "description": "The user wants to create a new regex from a description.",
                "examples": [
                  "Create a new regex matching something",
                  "New regex matching something",
                  "Build a regex for something"
                ]
              }
            ]
          },
          {
            "name": "new-from",
            "description": "Create a new regex from a sample",
            "disambiguation": [
              {
                "category": "regex_new-from",
                "description": "The user wants to create a new regex from a sample.",
                "examples": [
                  "Create a new regex that matches this",
                  "New regex from sample",
                  "Build a regex for this"
                ]
              }
            ]
          }
        ],
        "disambiguation": [
          {
            "category": "regex",
            "description": "The user wants to understand a regex.",
            "examples": [
              "Explain this regex",
              "What does this regex do?",
              "How does this regex work?"
            ]
          }
        ]
      }
    ]
  },
  "scripts": {
    "vscode:prepublish": "yarn run compile",
    "compile": "tsc -p ./",
    "watch": "tsc -watch -p ./",
    "package": "vsce package",
    "publish": "vsce publish"
  },
  "devDependencies": {
    "@types/vscode": "^1.92.0",
    "typescript": "^5.6.2"
  }
}

================================================
FILE: src/chat.ts
================================================
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See LICENSE in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
import * as vscode from 'vscode';

const REGEX_PARTICIPANT_ID = 'regex.chatParticipant';

const MODEL_SELECTOR: vscode.LanguageModelChatSelector = { vendor: 'copilot', family: 'gpt-4o' };

export function registerChatParticipant(context: vscode.ExtensionContext) {

    const handler: vscode.ChatRequestHandler = async (request: vscode.ChatRequest, context: vscode.ChatContext, stream: vscode.ChatResponseStream, token: vscode.CancellationToken): Promise<void> => {
        try {
            let [model] = await vscode.lm.selectChatModels(MODEL_SELECTOR);
            if (!model) {
                [model] = await vscode.lm.selectChatModels();
                if (!model) {
                    stream.markdown('No language model available.');
                    return;
                }
            }
            const messages = [];
            if (!request.command) {
                for (let i = context.history.length - 1; i >= 0; i--) {
                    const turn = context.history[i];
                    if (turn.participant !== REGEX_PARTICIPANT_ID) {
                        break;
                    }
                    if (turn instanceof vscode.ChatRequestTurn) {
                        if (turn.command || i === 0 || context.history[i - 1].participant !== REGEX_PARTICIPANT_ID) {
                            messages.push(...getInitialPrompt(turn).reverse());
                            break;
                        }
                        messages.push(vscode.LanguageModelChatMessage.User(turn.prompt));
                    } else if (turn instanceof vscode.ChatResponseTurn) {
                        for (const part of turn.response) {
                            if (part instanceof vscode.ChatResponseMarkdownPart) {
                                messages.push(vscode.LanguageModelChatMessage.Assistant(part.value.value));
                            }
                        }
                    }
                }
                messages.reverse();
            }
            if (!messages.length) {
                messages.push(...getInitialPrompt(request));
            } else {
                messages.push(vscode.LanguageModelChatMessage.User(request.prompt));
            }

            const chatResponse = await model.sendRequest(messages, {}, token);
            for await (const fragment of chatResponse.text) {
                stream.markdown(fragment);
            }
        } catch (err) {
            if (err instanceof vscode.LanguageModelError) {
                stream.markdown(`${err.message} (${err.code})`);
            } else {
                throw err;
            }
        }
    };

    function getInitialPrompt({ prompt, command }: { prompt: string; command?: string }) {
        const languageId = vscode.window.activeTextEditor?.document.languageId
            || vscode.window.visibleTextEditors[0]?.document.languageId
            || vscode.workspace.textDocuments[0]?.languageId
            || 'javascript';
        const languageName = languageIdToNameMapping[languageId] || languageId;

        if (command === 'new') {
            return [
                vscode.LanguageModelChatMessage.User('You are an expert in regular expressions! Your job is to create regular expressions based on descriptions of what has to match.'),
                vscode.LanguageModelChatMessage.User(`Create a ${languageName} regular expression that matches text with the following description: ${prompt}`),
            ];
        }
        if (command === 'new-from') {
            return [
                vscode.LanguageModelChatMessage.User('You are an expert in regular expressions! Your job is to create regular expressions based on text samples that have to match.'),
                vscode.LanguageModelChatMessage.User(`Create a ${languageName} regular expression that matches the following samples: ${prompt}`),
            ];
        }
        return [
            vscode.LanguageModelChatMessage.User(`You are an expert in regular expressions! Your job is to assist with regular expressions in ${languageName}.`),
            vscode.LanguageModelChatMessage.User(prompt),
        ]
    }

    const regex = vscode.chat.createChatParticipant(REGEX_PARTICIPANT_ID, handler);
    regex.iconPath = vscode.Uri.joinPath(context.extensionUri, 'images', 'icon.png');

    context.subscriptions.push(
        regex,
    );
}

const languageIdToNameMapping: { [id: string]: string } = {
    'javascript': 'JavaScript',
    'javascriptreact': 'JavaScript React',
    'typescript': 'TypeScript',
    'typescriptreact': 'TypeScript React',
    'vue': 'Vue',
    'php': 'PHP',
    'haxe': 'Haxe',
    'python': 'Python',
    'java': 'Java',
    'csharp': 'C#',
    'cpp': 'C++',
    'ruby': 'Ruby',
    'go': 'Go',
    'rust': 'Rust',
    'swift': 'Swift',
    'kotlin': 'Kotlin',
    'scala': 'Scala',
    'perl': 'Perl',
    'html': 'HTML',
    'css': 'CSS',
    'markdown': 'Markdown',
    'json': 'JSON',
    'xml': 'XML',
    'sql': 'SQL',
};


================================================
FILE: src/extension.ts
================================================
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See LICENSE in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
'use strict';

import * as vscode from 'vscode';
import { registerChatParticipant } from './chat';

declare type IntervalToken = object;
declare function setInterval(fn: () => void, delay: number): IntervalToken;
declare function clearInterval(token: IntervalToken): void;

export function activate(context: vscode.ExtensionContext) {
    registerChatParticipant(context);

    const regexRegex = /(^|\s|[()={},:?;])(\/((?:\\\/|\[[^\]]*\]|[^/])+)\/([gimuyd]*))(\s|[()={},:?;]|$)/g;
    const phpRegexRegex = /(^|\s|[()={},:?;])['|"](\/((?:\\\/|\[[^\]]*\]|[^/])+)\/([gimuy]*))['|"](\s|[()={},:?;]|$)/g;
    const haxeRegexRegex = /(^|\s|[()={},:?;])(~\/((?:\\\/|\[[^\]]*\]|[^/])+)\/([gimsu]*))(\s|[.()={},:?;]|$)/g;
    const regexHighlight = vscode.window.createTextEditorDecorationType({ backgroundColor: 'rgba(100,100,100,.35)' });
    const matchHighlight = vscode.window.createTextEditorDecorationType({ backgroundColor: 'rgba(255,255,0,.35)' });

    const matchesFileContent = `Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit
esse cillum dolore eu fugiat nulla pariatur. Excepteur sint
occaecat cupidatat non proident, sunt in culpa qui officia
deserunt mollit anim id est laborum.

abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ
0123456789 _+-.,!@#$%^&*();\/|<>"'
12345 -98.7 3.141 .6180 9,000 +42
555.123.4567	+1-(800)-555-2468
foo@demo.net	bar.ba@test.co.uk
www.demo.com	http://foo.co.uk/
https://marketplace.visualstudio.com/items?itemName=chrmarti.regex
https://github.com/chrmarti/vscode-regex
`;
    const languages = ['javascript', 'javascriptreact', 'typescript', 'typescriptreact', 'vue', 'php', 'haxe'];

    const decorators = new Map<vscode.TextEditor, RegexMatchDecorator>();

    context.subscriptions.push(vscode.commands.registerCommand('extension.toggleRegexPreview', toggleRegexPreview));

    languages.forEach(language => {
        context.subscriptions.push(vscode.languages.registerCodeLensProvider(language, { provideCodeLenses }));
    });

    context.subscriptions.push(vscode.window.onDidChangeActiveTextEditor(() => updateDecorators(findRegexEditor())));

    const interval = setInterval(() => updateDecorators(), 5000);
    context.subscriptions.push({ dispose: () => clearInterval(interval) });

    function provideCodeLenses(document: vscode.TextDocument, token: vscode.CancellationToken) {
        const config = vscode.workspace.getConfiguration('regex-previewer', document.uri);
        if (!config.enableCodeLens) return;

        const matches = findRegexes(document);
        return matches.map(match => new vscode.CodeLens(match.range, {
            title: 'Test Regex...',
            command: 'extension.toggleRegexPreview',
            arguments: [ match ]
        }));
    }

    let addGMEnabled = false;
    const toggleGM = vscode.window.createStatusBarItem();
    toggleGM.command = 'regexpreview.toggleGM';
    context.subscriptions.push(toggleGM);
    context.subscriptions.push(vscode.commands.registerCommand('regexpreview.toggleGM', () => {
        addGMEnabled = !addGMEnabled;
        updateToggleGM();
        for (const decorator of decorators.values()) {
            decorator.update();
        }
    }))
    function updateToggleGM() {
        toggleGM.text = addGMEnabled ? 'Adding /gm' : 'Not adding /gm';
        toggleGM.tooltip = addGMEnabled ? 'Click to stop adding global and multiline (/gm) options to regexes for evaluation with example text.' : 'Click to add global and multiline (/gm) options to regexes for evaluation with example text.'
    }
    updateToggleGM();
    function addGM(regex: RegExp) {
        if (!addGMEnabled || (regex.global && regex.multiline)) {
            return regex;
        }

        let flags = regex.flags;
        if (!regex.global) {
            flags += 'g';
        }
        if (!regex.multiline) {
            flags += 'm';
        }
        return new RegExp(regex.source, flags);
    }

    let enabled = false;
    function toggleRegexPreview(initialRegexMatch?: RegexMatch) {
        enabled = !enabled || !!initialRegexMatch && !!initialRegexMatch.regex;
        toggleGM[enabled ? 'show' : 'hide']();
        if (enabled) {
            const visibleEditors = getVisibleTextEditors();
            if (visibleEditors.length === 1) {
                return openLoremIpsum(visibleEditors[0].viewColumn! + 1, initialRegexMatch);
            } else {
                updateDecorators(findRegexEditor(), initialRegexMatch);
            }
        } else {
            decorators.forEach(decorator => decorator.dispose());
        }
    }

    function openLoremIpsum(column: number, initialRegexMatch?: RegexMatch) {
        return vscode.workspace.openTextDocument({ language: 'text', content: matchesFileContent })
            .then(document => {
                return vscode.window.showTextDocument(document, column, true);
            }).then(editor => {
                updateDecorators(findRegexEditor(), initialRegexMatch);
            }).then(undefined, reason => {
                vscode.window.showErrorMessage(reason);
            });
    }

    function updateDecorators(regexEditor?: vscode.TextEditor, initialRegexMatch?: RegexMatch) {
        if (!enabled) {
            return;
        }

        // TODO: figure out why originEditor.document is sometimes a different object
        if (regexEditor && initialRegexMatch && initialRegexMatch.document && initialRegexMatch.document.uri.toString() === regexEditor.document.uri.toString()) {
            initialRegexMatch.document = regexEditor.document;
        }

        const remove = new Map(decorators);
        getVisibleTextEditors().forEach(editor => {
            remove.delete(editor);
            applyDecorator(editor, regexEditor, initialRegexMatch);
        });
        remove.forEach(decorator => decorator.dispose());
    }

    function getVisibleTextEditors() {
        return vscode.window.visibleTextEditors.filter(editor => typeof editor.viewColumn === 'number');
    }

    function applyDecorator(matchEditor: vscode.TextEditor, initialRegexEditor?: vscode.TextEditor, initialRegexMatch?: RegexMatch) {
        let decorator = decorators.get(matchEditor);
        const newDecorator = !decorator;
        if (newDecorator) {
            decorator = new RegexMatchDecorator(matchEditor);
            context.subscriptions.push(decorator);
            decorators.set(matchEditor, decorator);
        }
        if (newDecorator || initialRegexEditor || initialRegexMatch) {
            decorator!.apply(initialRegexEditor, initialRegexMatch);
        }
    }

    function discardDecorator(matchEditor: vscode.TextEditor) {
        decorators.delete(matchEditor);
    }

    interface RegexMatch {

        document: vscode.TextDocument;

        regex: RegExp;

        range: vscode.Range;

    }

    interface Match {

        range: vscode.Range;
    }

    class RegexMatchDecorator {

        private stableRegexEditor?: vscode.TextEditor;
        private stableRegexMatch?: RegexMatch;
        private disposables: vscode.Disposable[] = [];

        constructor(private matchEditor: vscode.TextEditor) {

            this.disposables.push(vscode.workspace.onDidCloseTextDocument(e => {
                if (this.stableRegexEditor && e === this.stableRegexEditor.document) {
                    this.stableRegexEditor = undefined;
                    this.stableRegexMatch = undefined;
                    matchEditor.setDecorations(matchHighlight, []);
                } else if (e === matchEditor.document) {
                    this.dispose();
                }
            }));

            this.disposables.push(vscode.workspace.onDidChangeTextDocument(e => {
                if ((this.stableRegexEditor && e.document === this.stableRegexEditor.document) || e.document === matchEditor.document) {
                    this.update();
                }
            }));

            this.disposables.push(vscode.window.onDidChangeTextEditorSelection(e => {
                if (this.stableRegexEditor && e.textEditor === this.stableRegexEditor) {
                    this.stableRegexMatch = undefined;
                    this.update();
                }
            }));

            this.disposables.push(vscode.window.onDidChangeActiveTextEditor(e => {
                this.update();
            }));

            this.disposables.push({ dispose: () => {
                matchEditor.setDecorations(matchHighlight, []);
                matchEditor.setDecorations(regexHighlight, []);
            }});
        }

        public apply(stableRegexEditor?: vscode.TextEditor, stableRegexMatch?: RegexMatch) {
            this.stableRegexEditor = stableRegexEditor;
            this.stableRegexMatch = stableRegexMatch;
            this.update();
        }

        public dispose() {
            discardDecorator(this.matchEditor);
            this.disposables.forEach(disposable => {
                disposable.dispose();
            });
        }

        public update() {
            const regexEditor = this.stableRegexEditor = findRegexEditor() || this.stableRegexEditor;
            let regex = regexEditor && findRegexAtCaret(regexEditor);
            if (this.stableRegexMatch) {
                if (regex || !regexEditor || regexEditor.document !== this.stableRegexMatch.document) {
                    this.stableRegexMatch = undefined;
                } else {
                    regex = this.stableRegexMatch;
                }
            }
            const matches = regex && regexEditor !== this.matchEditor ? findMatches(regex, this.matchEditor.document) : [];
            this.matchEditor.setDecorations(matchHighlight, matches.map(match => match.range));

            if (regexEditor) {
                regexEditor.setDecorations(regexHighlight, (this.stableRegexMatch || regexEditor !== vscode.window.activeTextEditor) && regex ? [ regex.range ] : []);
            }
        }
    }

    function findRegexEditor() {
        const activeEditor = vscode.window.activeTextEditor;
        if (!activeEditor || languages.indexOf(activeEditor.document.languageId) === -1) {
            return undefined;
        }
        return activeEditor;
    }

    function findRegexAtCaret(editor: vscode.TextEditor): RegexMatch | undefined {
        const anchor = editor.selection.anchor;
        const line = editor.document.lineAt(anchor);
        const text = line.text.substr(0, 1000);

        let match: RegExpExecArray | null;
        let regex = getRegexRegex(editor.document.languageId);
        regex.lastIndex = 0;
        while ((match = regex.exec(text)) && (match.index + match[1].length + match[2].length < anchor.character));
        if (match && match.index + match[1].length <= anchor.character) {
            return createRegexMatch(editor.document, anchor.line, match);
        }
    }

    function findRegexes(document: vscode.TextDocument) {
        const matches: RegexMatch[] = [];
        for (let i = 0; i < document.lineCount; i++) {
            const line = document.lineAt(i);
            let match: RegExpExecArray | null;
            let regex = getRegexRegex(document.languageId);
            regex.lastIndex = 0;
            const text = line.text.substr(0, 1000);
            while ((match = regex.exec(text))) {
                const result = createRegexMatch(document, i, match);
                if (result) {
                    matches.push(result);
                }
            }
        }
        return matches;
    }

    function getRegexRegex(languageId: String) {
        if (languageId == 'haxe') {
            return haxeRegexRegex;
        } else if (languageId == 'php') {
            return phpRegexRegex;
        }
        return regexRegex;
    }

    function createRegexMatch(document: vscode.TextDocument, line: number, match: RegExpExecArray) {
        const regex = createRegex(match[3], match[4]);
        if (regex) {
            return {
                document: document,
                regex: regex,
                range: new vscode.Range(line, match.index + match[1].length, line, match.index + match[1].length + match[2].length)
            };
        }
    }

    function createRegex(pattern: string, flags: string) {
            try {
                return new RegExp(pattern, flags);
            } catch (e) {
                // discard
            }
    }

    function findMatches(regexMatch: RegexMatch, document: vscode.TextDocument) {
        const text = document.getText();
        const matches: Match[] = [];
        const regex = addGM(regexMatch.regex);
        let match: RegExpExecArray | null;
        while ((regex.global || !matches.length) && (match = regex.exec(text))) {
            matches.push({
                range: new vscode.Range(document.positionAt(match.index), document.positionAt(match.index + match[0].length))
            });
            // Handle empty matches (fixes #4)
            if (regex.lastIndex === match.index) {
                regex.lastIndex++;
            }
        }
        return matches;
    }
}


================================================
FILE: tsconfig.json
================================================
{
	"compilerOptions": {
		"module": "commonjs",
		"target": "ES2022",
		"lib": [
			"ES2022"
		],
		"outDir": "out",
		"sourceMap": true,
		"rootDir": "src",
		"strict": true
	},
	"exclude": [
		"node_modules"
	]
}
Download .txt
gitextract_a12zpu6_/

├── .github/
│   └── assignment.yml
├── .gitignore
├── .vscode/
│   ├── launch.json
│   ├── settings.json
│   └── tasks.json
├── .vscodeignore
├── LICENSE
├── README.md
├── package.json
├── src/
│   ├── chat.ts
│   └── extension.ts
└── tsconfig.json
Download .txt
SYMBOL INDEX (5 symbols across 2 files)

FILE: src/chat.ts
  constant REGEX_PARTICIPANT_ID (line 7) | const REGEX_PARTICIPANT_ID = 'regex.chatParticipant';
  constant MODEL_SELECTOR (line 9) | const MODEL_SELECTOR: vscode.LanguageModelChatSelector = { vendor: 'copi...
  function registerChatParticipant (line 11) | function registerChatParticipant(context: vscode.ExtensionContext) {

FILE: src/extension.ts
  type IntervalToken (line 10) | type IntervalToken = object;
  function activate (line 14) | function activate(context: vscode.ExtensionContext) {
Condensed preview — 12 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (29K chars).
[
  {
    "path": ".github/assignment.yml",
    "chars": 51,
    "preview": "{\n    perform: true,\n    assignees: [ chrmarti ]\n}\n"
  },
  {
    "path": ".gitignore",
    "chars": 23,
    "preview": "out\nnode_modules\n*.vsix"
  },
  {
    "path": ".vscode/launch.json",
    "chars": 593,
    "preview": "// A launch configuration that compiles the extension and then opens it inside a new window\n// Use IntelliSense to learn"
  },
  {
    "path": ".vscode/settings.json",
    "chars": 444,
    "preview": "// Place your settings in this file to overwrite default and user settings.\n{\n    \"files.exclude\": {\n        \"out\": fals"
  },
  {
    "path": ".vscode/tasks.json",
    "chars": 366,
    "preview": "// See https://go.microsoft.com/fwlink/?LinkId=733558\n// for the documentation about the tasks.json format\n{\n\t\"version\":"
  },
  {
    "path": ".vscodeignore",
    "chars": 83,
    "preview": ".vscode/**\n.github/**\nout/test/**\ntest/**\nsrc/**\n**/*.map\n.gitignore\ntsconfig.json\n"
  },
  {
    "path": "LICENSE",
    "chars": 1110,
    "preview": "Copyright (c) Microsoft Corporation\r\n\r\nAll rights reserved.\r\n\r\nMIT License\r\n\r\nPermission is hereby granted, free of char"
  },
  {
    "path": "README.md",
    "chars": 1626,
    "preview": "## Features\n\nShows the current regular expression's matches in a side-by-side document. This can be turned on/off with `"
  },
  {
    "path": "package.json",
    "chars": 3483,
    "preview": "{\n  \"name\": \"regex\",\n  \"displayName\": \"Regex Previewer\",\n  \"description\": \"Regex matches previewer for JavaScript, TypeS"
  },
  {
    "path": "src/chat.ts",
    "chars": 5349,
    "preview": "/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Micros"
  },
  {
    "path": "src/extension.ts",
    "chars": 13630,
    "preview": "/*---------------------------------------------------------------------------------------------\n *  Copyright (c) Micros"
  },
  {
    "path": "tsconfig.json",
    "chars": 214,
    "preview": "{\n\t\"compilerOptions\": {\n\t\t\"module\": \"commonjs\",\n\t\t\"target\": \"ES2022\",\n\t\t\"lib\": [\n\t\t\t\"ES2022\"\n\t\t],\n\t\t\"outDir\": \"out\",\n\t\t\""
  }
]

About this extraction

This page contains the full source code of the chrmarti/vscode-regex GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 12 files (26.3 KB), approximately 6.3k tokens, and a symbol index with 5 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!