File size: 1,832 Bytes
4e7644b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import type { editor as MonacoEditor } from "monaco-editor";
import { getLanguage } from "./getLanguage";

type CopyMode = "whole-file" | "lines-only" | "with-code";

const stripTrailingNewlines = (value: string) => value.replace(/\n+$/, "");

export function getEditorLanguage(path: string): string {
  return getLanguage(path);
}

export function visibleEditorPath(path: string): string {
  return path.includes("::") ? path.slice(path.indexOf("::") + 2) : path;
}

export function detectCopyMode(
  selection: {
    startLineNumber: number;
    startColumn: number;
    endLineNumber: number;
    endColumn: number;
  },
  model: MonacoEditor.ITextModel,
): {
  mode: CopyMode;
  code: string;
  startLine: number;
  endLine: number;
} {
  const code = model.getValueInRange(selection);
  const startLine = selection.startLineNumber;
  let endLine = selection.endLineNumber;
  if (endLine > startLine && selection.endColumn === 1) {
    endLine -= 1;
  }

  const lines: string[] = [];
  for (let line = startLine; line <= endLine; line += 1) {
    lines.push(model.getLineContent(line));
  }
  if (stripTrailingNewlines(code) === lines.join("\n")) {
    return { mode: "lines-only", code, startLine, endLine };
  }

  return { mode: "with-code", code, startLine, endLine };
}

export function formatSelectionForChat(
  filePath: string,
  code: string,
  startLine: number,
  endLine: number,
  mode: CopyMode,
): string {
  const displayPath = visibleEditorPath(filePath);
  if (mode === "whole-file") {
    return displayPath;
  }
  const lineRange =
    startLine === endLine ? `${startLine}` : `${startLine}-${endLine}`;
  if (mode === "lines-only") {
    return `${displayPath}:${lineRange}`;
  }
  const language = getEditorLanguage(filePath);
  return `${displayPath}:${lineRange}\n\`\`\`${language}\n${code}\n\`\`\``;
}