Path: blob/main/extensions/copilot/src/extension/prompt/node/editGeneration.ts
13399 views
/*---------------------------------------------------------------------------------------------1* Copyright (c) Microsoft Corporation. All rights reserved.2* Licensed under the MIT License. See License.txt in the project root for license information.3*--------------------------------------------------------------------------------------------*/45import type * as vscode from 'vscode';6import { Range, TextEdit } from '../../../vscodeTypes';78export type Lines = readonly string[];910export type LineRange = { readonly firstLineIndex: number; readonly endLineIndex: number };1112export class LinesEdit {13constructor(public readonly firstLineIndex: number, readonly endLineIndex: number, public readonly lines: Lines, public readonly prefix = '', public readonly suffix = '\n') {14}15toTextEdit(): TextEdit {16const text = this.lines.length > 0 ? (this.prefix + this.lines.join('\n') + this.suffix) : '';17return TextEdit.replace(new Range(this.firstLineIndex, 0, this.endLineIndex, 0), text);18}19apply(lines: Lines): Lines {20const before = lines.slice(0, this.firstLineIndex);21const after = lines.slice(this.endLineIndex);22return before.concat(this.lines, after);23}24static insert(line: number, lines: Lines) {25return new LinesEdit(line, line, lines);26}27static replace(firstLineIndex: number, endLineIndex: number, lines: Lines, isLastLine = false) {28if (isLastLine) {29return new LinesEdit(firstLineIndex, endLineIndex, lines, '', '');30}31return new LinesEdit(firstLineIndex, endLineIndex, lines);32}33}3435export namespace Lines {36export function fromString(code: string): Lines {37if (code.length === 0) {38return [];39}40return code.split(/\r\n|\r|\n/g);41}42export function fromDocument(doc: vscode.TextDocument): Lines {43if (doc.lineCount === 0) {44return [];45}46const result: string[] = [];47for (let i = 0; i < doc.lineCount; i++) {48result.push(doc.lineAt(i).text);49}50return result;51}52}5354export function isLines(lines: any): lines is Lines {55return Array.isArray(lines) && typeof lines[0] === 'string';56}5758export const enum EditStrategy {59/**60* In case we have no hints (no code markers and no diffing heuristics)61* about the edits to generate, we can use a default strategy.62*/63FallbackToInsertAboveRange = 1,64/**65* In case we have no hints (no code markers and no diffing heuristics)66* about the edits to generate, we can use a default strategy.67*/68FallbackToReplaceRange = 2,69/**70* In case we have no hints (no code markers and no diffing heuristics)71* about the edits to generate, we can use a default strategy.72*/73FallbackToInsertBelowRange = 3,74/**75* Code Generation: always insert at the cursor location.76*/77ForceInsertion = 478}7980export function trimLeadingWhitespace(str: string): string {81return str.replace(/^\s+/g, '');82}83848586