From 338062016cc2d0adeaeede3de8982469e53c0f64 Mon Sep 17 00:00:00 2001 From: Peter Zaback Date: Fri, 19 Apr 2024 14:29:30 -0500 Subject: [PATCH] Reformat markdown code blocks Currently, user-selected code blocks are formatted with range in file (rif) info on the same line as the triple backticks, which means that when exported to markdown they don't have the language info needed on that line for syntax highlighting. This update moves the rif info to the following line as a comment in the language of the file and with the language info in the correct place. Before: ```example.ts (3-6) function fib(n) { if (n <= 1) return n; return fib(n - 2) + fib(n - 1); } ``` After: ```ts // example.ts (3-6) function fib(n) { if (n <= 1) return n; return fib(n - 2) + fib(n - 1); } ``` --- core/commands/slash/share.ts | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/core/commands/slash/share.ts b/core/commands/slash/share.ts index c13d1d9fb..08e91f654 100644 --- a/core/commands/slash/share.ts +++ b/core/commands/slash/share.ts @@ -2,6 +2,7 @@ import path from "path"; import * as fs from "fs"; import { homedir } from "os"; import { SlashCommand } from "../.."; +import { languageForFilepath } from "../../autocomplete/constructPrompt"; import { stripImages } from "../../llm/countTokens"; // If useful elsewhere, helper funcs should move to core/util/index.ts or similar @@ -21,6 +22,16 @@ function asBasicISOString(date: Date): string { return isoString.replace(/[-:]|(\.\d+Z)/g, ""); } +function reformatCodeBlocks(msgText: string): string { + const codeBlockRegex = /```(.*?\.(\w+)\s*.*)\n/g; + + return msgText.replace(codeBlockRegex, (match, metadata, extension) => { + const filename = metadata.split(" ")[0]; + const lang = languageForFilepath(filename); + return `\`\`\`${extension}\n${lang.comment} ${metadata}\n`; + }); +} + const ShareSlashCommand: SlashCommand = { name: "share", description: "Export the current chat session to markdown", @@ -30,9 +41,17 @@ const ShareSlashCommand: SlashCommand = { let content = `This is a session transcript from [Continue](https://continue.dev) on ${now.toLocaleString()}.`; for (const msg of history) { + let msgText = msg.content; + msgText = stripImages(msg.content); + + // if (msg.role === "user" && msgText.search("```") !== -1) { + if (msg.role === "user" && msgText.search("```") > -1) { + msgText = reformatCodeBlocks(msgText); + } + content += `\n\n## ${ msg.role === "user" ? "User" : "Assistant" - }\n\n${stripImages(msg.content)}`; + }\n\n${msgText}`; } let outputDir: string = params?.outputDir;