Skip to content

Commit

Permalink
feat: optimize smart-paste prompt and add actions for tmp file
Browse files Browse the repository at this point in the history
  • Loading branch information
2214962083 committed Jul 29, 2024
1 parent 0144cce commit 9a57c03
Show file tree
Hide file tree
Showing 32 changed files with 617 additions and 150 deletions.
15 changes: 15 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,21 @@
{
"command": "aide.smartPaste",
"title": "%command.smartPaste%"
},
{
"command": "aide.copyFileText",
"title": "%command.copyFileText%",
"enablement": "false"
},
{
"command": "aide.quickCloseFileWithoutSave",
"title": "%command.quickCloseFileWithoutSave%",
"enablement": "false"
},
{
"command": "aide.replaceFile",
"title": "%command.replaceFile%",
"enablement": "false"
}
],
"menus": {
Expand Down
5 changes: 5 additions & 0 deletions package.nls.en.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
"command.codeViewerHelper": "✨ Aide: Code Viewer Helper",
"command.renameVariable": "✨ Aide: Rename Variable",
"command.smartPaste": "✨ Aide: Smart Paste",
"command.copyFileText": "Copy text",
"command.quickCloseFileWithoutSave": "Quick close",
"command.replaceFile": "Replace original file",
"config.title": "Aide Configuration",
"config.openaiKey.description": "OpenAI Key, [click to view online documentation](https://aide.nicepkg.cn/guide/configuration/openai-key)",
"config.openaiModel.description": "OpenAI Model, [click to view online documentation](https://aide.nicepkg.cn/guide/configuration/openai-model)",
Expand Down Expand Up @@ -37,6 +40,7 @@
"error.noContext": "Context not initialized",
"error.emptyClipboard": "Clipboard is empty",
"error.xclipNotFound": "xclip is not installed. Please install it using your package manager (e.g., sudo apt-get install xclip)",
"error.fileNotFound": "File not found",
"info.copied": "File contents have been copied to clipboard",
"info.customLanguage": "Custom language",
"info.noAiSuggestionsVariableName": "AI thinks your variable name is already good",
Expand All @@ -46,6 +50,7 @@
"info.continue": "Continue",
"info.cancel": "Cancel",
"info.commandCopiedToClipboard": "AI command has been copied to clipboard",
"info.fileReplaceSuccess": "File has been replaced successfully",
"input.array.promptEnding": "Enter comma separated values",
"input.json.promptEnding": "Enter JSON formatted value",
"input.aiCommand.prompt": "Enter question for AI command",
Expand Down
5 changes: 5 additions & 0 deletions package.nls.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
"command.codeViewerHelper": "✨ Aide: Code Viewer Helper",
"command.renameVariable": "✨ Aide: Rename Variable",
"command.smartPaste": "✨ Aide: Smart Paste",
"command.copyFileText": "Copy text",
"command.quickCloseFileWithoutSave": "Quick close",
"command.replaceFile": "Replace original file",
"config.title": "Aide Configuration",
"config.openaiKey.description": "OpenAI Key, [click to view online documentation](https://aide.nicepkg.cn/guide/configuration/openai-key)",
"config.openaiModel.description": "OpenAI Model, [click to view online documentation](https://aide.nicepkg.cn/guide/configuration/openai-model)",
Expand Down Expand Up @@ -37,6 +40,7 @@
"error.noContext": "Context not initialized",
"error.emptyClipboard": "Clipboard is empty",
"error.xclipNotFound": "xclip is not installed. Please install it using your package manager (e.g., sudo apt-get install xclip)",
"error.fileNotFound": "File not found",
"info.copied": "File contents have been copied to clipboard",
"info.customLanguage": "Custom language",
"info.noAiSuggestionsVariableName": "AI thinks your variable name is already good",
Expand All @@ -46,6 +50,7 @@
"info.continue": "Continue",
"info.cancel": "Cancel",
"info.commandCopiedToClipboard": "AI command has been copied to clipboard",
"info.fileReplaceSuccess": "File has been replaced successfully",
"input.array.promptEnding": "Enter comma separated values",
"input.json.promptEnding": "Enter JSON formatted value",
"input.aiCommand.prompt": "Enter question for AI command",
Expand Down
5 changes: 5 additions & 0 deletions package.nls.zh-cn.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
"command.codeViewerHelper": "✨ Aide: 代码查看器助手",
"command.renameVariable": "✨ Aide: 重命名变量",
"command.smartPaste": "✨ Aide: 智能粘贴",
"command.copyFileText": "复制全文",
"command.quickCloseFileWithoutSave": "快速关闭",
"command.replaceFile": "替换原文件",
"config.title": "Aide 配置",
"config.openaiKey.description": "OpenAI Key, [点击查看在线文档](https://aide.nicepkg.cn/zh/guide/configuration/openai-key)",
"config.openaiModel.description": "OpenAI Model, [点击查看在线文档](https://aide.nicepkg.cn/zh/guide/configuration/openai-model)",
Expand Down Expand Up @@ -37,6 +40,7 @@
"error.noContext": "上下文未初始化",
"error.emptyClipboard": "剪贴板为空",
"error.xclipNotFound": "xclip 未安装。请使用你的包管理器安装它 (例如,sudo apt-get install xclip)",
"error.fileNotFound": "文件未找到",
"info.copied": "文件内容已复制到剪贴板",
"info.customLanguage": "自定义语言",
"info.noAiSuggestionsVariableName": " AI 觉得你这个变量名字已经很好了",
Expand All @@ -46,6 +50,7 @@
"info.continue": "继续",
"info.cancel": "取消",
"info.commandCopiedToClipboard": "AI 命令已复制到剪贴板",
"info.fileReplaceSuccess": "文件已成功替换",
"input.array.promptEnding": "输入逗号分隔的值",
"input.json.promptEnding": "输入 JSON 格式的值",
"input.aiCommand.prompt": "输入 AI 命令的问题",
Expand Down
12 changes: 12 additions & 0 deletions src/commands/copy-file-text.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { t } from '@/i18n'
import * as vscode from 'vscode'

export const handleCopyFileText = async (uri?: vscode.Uri) => {
const targetUri = uri || vscode.window.activeTextEditor?.document.uri

if (!targetUri) throw new Error(t('error.noActiveEditor'))

const document = await vscode.workspace.openTextDocument(targetUri)
await vscode.env.clipboard.writeText(document.getText())
vscode.window.showInformationMessage(t('info.copied'))
}
28 changes: 26 additions & 2 deletions src/commands/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,13 @@ import { handleAskAI } from './ask-ai'
import { handleCodeConvert } from './code-convert'
import { handleCodeViewerHelper } from './code-viewer-helper'
import { handleCopyAsPrompt } from './copy-as-prompt'
import { handleCopyFileText } from './copy-file-text'
import { handleQuickCloseFileWithoutSave } from './quick-close-file-without-save'
import { handleRenameVariable } from './rename-variable'
import { handleReplaceFile } from './replace-file'
import { handleSmartPaste } from './smart-paste'

export const registerCommands = (context: vscode.ExtensionContext) => {
export const registerCommands = async (context: vscode.ExtensionContext) => {
const copyDisposable = vscode.commands.registerCommand(
'aide.copyAsPrompt',
commandErrorCatcher(handleCopyAsPrompt)
Expand Down Expand Up @@ -38,12 +41,33 @@ export const registerCommands = (context: vscode.ExtensionContext) => {
commandErrorCatcher(handleSmartPaste)
)

// private command
const copyFileTextDisposable = vscode.commands.registerCommand(
'aide.copyFileText',
commandErrorCatcher(handleCopyFileText)
)

// private command
const quickCloseFileWithoutSaveDisposable = vscode.commands.registerCommand(
'aide.quickCloseFileWithoutSave',
commandErrorCatcher(handleQuickCloseFileWithoutSave)
)

// private command
const replaceFileDisposable = vscode.commands.registerCommand(
'aide.replaceFile',
commandErrorCatcher(handleReplaceFile)
)

context.subscriptions.push(
copyDisposable,
askAIDisposable,
codeConvertDisposable,
codeViewerHelperDisposable,
renameVariableDisposable,
smartPasteDisposable
smartPasteDisposable,
copyFileTextDisposable,
quickCloseFileWithoutSaveDisposable,
replaceFileDisposable
)
}
31 changes: 31 additions & 0 deletions src/commands/quick-close-file-without-save.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { t } from '@/i18n'
import * as vscode from 'vscode'

export const handleQuickCloseFileWithoutSave = async (uri?: vscode.Uri) => {
const targetUri = uri || vscode.window.activeTextEditor?.document.uri
if (!targetUri) throw new Error(t('error.noActiveEditor'))

const targetEditor = vscode.window.visibleTextEditors.find(
editor => editor.document.uri.toString() === targetUri.toString()
)

let documentToClose: vscode.TextDocument | undefined

if (targetEditor) {
documentToClose = targetEditor.document
} else {
documentToClose = vscode.workspace.textDocuments.find(
doc => doc.uri.toString() === targetUri.toString()
)
}

if (!documentToClose) throw new Error(t('error.noActiveEditor'))

await vscode.window.showTextDocument(documentToClose)

const command = documentToClose.isDirty
? 'workbench.action.revertAndCloseActiveEditor'
: 'workbench.action.closeActiveEditor'

await vscode.commands.executeCommand(command)
}
33 changes: 33 additions & 0 deletions src/commands/replace-file.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { VsCodeFS } from '@/file-utils/vscode-fs'
import { t } from '@/i18n'
import * as vscode from 'vscode'

/**
* Handles the replacement of a file with another file.
*
* @param fromFileUri - The file will not removed, but its content will be replaced.
* @param toFileUri - The file will be removed.
* @throws An error if either `fromFileUri` or `toFileUri` is not provided.
*/
export const handleReplaceFile = async (
fromFileUri: vscode.Uri,
toFileUri: vscode.Uri
) => {
if (!fromFileUri || !toFileUri) throw new Error(t('error.fileNotFound'))

const toFileDocument = await vscode.workspace.openTextDocument(toFileUri)

await VsCodeFS.writeFile(fromFileUri.fsPath, toFileDocument.getText(), 'utf8')

vscode.window.showInformationMessage(t('info.fileReplaceSuccess'))

// close the toFileUri
await vscode.commands.executeCommand(
'aide.quickCloseFileWithoutSave',
toFileUri
)

// if fromFileUri is not opened, open it
const fromFileDocument = await vscode.workspace.openTextDocument(fromFileUri)
await vscode.window.showTextDocument(fromFileDocument)
}
104 changes: 48 additions & 56 deletions src/commands/smart-paste.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,6 @@ const buildConvertChatMessages = async ({
// build clipboard content prompt
const clipboardContentPrompt = clipboardImg
? `
1. Clipboard content:
${
clipboardContent
? `
Expand All @@ -76,78 +75,71 @@ const buildConvertChatMessages = async ({
: 'No Clipboard Content'
}
BTW, I copied an image, please automatically recognize and convert it into code based on the image content.
BTW, I copied an image, please automatically recognize and convert it into code based on the image content.
**Guidelines for UI Conversion**:
- Match colors, sizes, text, and layout exactly as in the image.
- Extract page text and data into variables for easy maintenance.
- Split UI components to make the code modular and maintainable.
- Do not add comments in the code such as "<!-- Add other navigation links as needed -->" and "<!-- ... other news items ... -->" in place of writing the full code. WRITE THE FULL CODE.
- Make sure to always get the layout right (if things are arranged in a row in the screenshot, they should be in a row in the app as well)
- **For images, use placeholder images from \`https://placehold.co\`** and include a detailed description of the image in the alt text so that an image generation AI can generate the image later.
**Guidelines for UI Code Generate:**
- **Modular Design**: Break down the UI into small, reusable components. Each component should focus on a single responsibility.
- **Avoid Hardcoding**: Do not hard-code any UI data. Instead, use variables or props to pass data into components. This makes the components reusable and the code more maintainable.
- **Data and State Management**: Extract page text, styles, and data into variables, constants, or state as appropriate. Ensure that data is not embedded directly in the UI code.
- **Use Props and State**: Design components to accept props for data and configuration, allowing them to be reused in different contexts.
- **Maintainable and Readable Code**: Write clear, concise, and well-commented code. Ensure that the code is easy to understand and modify in the future.
`
: `
1. Clipboard content:
\`\`\`
${clipboardContent}
\`\`\`
`

// some prompt comes from https://github.com/abi/screenshot-to-code/blob/main/backend/prompts/claude_prompts.py
// thanks to the author
const prompt = `
I will provide the content of the current file, as well as the content of several most useful files related to the currently edited file, to you.
I would like you to automatically recognize the programming language of the current file's code and the code from the clipboard, then convert the code from the clipboard into the current file's programming language.
The converted code should be inserted at the location marked with ${locationMark}.
Please note that the converted code should be valid code without any syntax errors when I insert it into the location marked.
**You should try to guess the my intention and the desired conversion style as much as possible.**
Example 1:
- If I copied Tailwind CSS template code and pasted it into Flutter code, you should automatically recognize this as Tailwind CSS code and convert it to Flutter code.
Example 2:
- If I copied Tailwind CSS template code and pasted it into vue style tag, you should automatically convert it as css/less/sass(which I use) code for me to insert into the style tag.
Example 3:
- If I copied JSON data and pasted it into a TypeScript \`types XXX = {}\` statement, you should automatically recognize this as JSON data and convert it to a TypeScript type.
I'm providing the content of the current file and the content of several related files. Your task is to recognize the programming language of the current file and the content from the clipboard, then convert the clipboard content into the programming language and context of the current file.
Example 4:
- If I copied an image and pasted it into a jsx/vue template,
you should read the ui elements in the image and automatically convert them to the corresponding jsx/vue code,
the class name style should be consistent with the current file, and you also need follow the following rules:
- Make sure the app looks exactly like the screenshot.
- Do not leave out smaller UI elements. Make sure to include every single thing in the screenshot.
- Pay close attention to background color, text color, font size, font family, padding, margin, border, etc. Match the colors and sizes exactly.
- In particular, pay attention to background color and overall color scheme.
- Use the exact text from the screenshot.
- Do not add comments in the code such as "<!-- Add other navigation links as needed -->" and "<!-- ... other news items ... -->" in place of writing the full code. WRITE THE FULL CODE.
- Make sure to always get the layout right (if things are arranged in a row in the screenshot, they should be in a row in the app as well)
- **For images, use placeholder images from \`https://placehold.co\`** and include a detailed description of the image in the alt text so that an image generation AI can generate the image later.
**Important Instructions**:
1. **Language Detection & Conversion**:
- Detect the language of the current file and the clipboard content.
- Convert the clipboard content into the appropriate language and style for the current file's context.
2. **Code Integration**:
- The converted code should be valid and without syntax errors.
- Insert the converted code at the marked location: ${locationMark}.
Important:
- **In short, you are always very smart to guess my intention based on the position where I paste, and then automatically convert the code.**
3. **Understanding Intent**:
- Understand the likely intent behind the pasted content and match the desired conversion style.
If there is no text content in the clipboard, I will tell you \`No Clipboard Content.\`
**Examples**:
- **Tailwind CSS to Flutter**: Convert Tailwind CSS code to Flutter code when pasted into Flutter files.
- **JSON to TypeScript**: Convert JSON data to a TypeScript type when pasted into a TypeScript file.
- **Image to JSX/Vue/Other GUI**: Convert UI elements from an image into JSX/Vue/Other GUI code, maintaining the style and layout accurately. Use placeholder images and include detailed alt text descriptions.
You should not respond with anything other than the converted code.
**General Rules**:
- Be smart in guessing the intended usage based on the paste location.
- Use ${vscode.env.language} for comments if needed.
- **Only provide the converted code without any markdown syntax or additional text.**
You should always use my mother tongue ${vscode.env.language} to add comments if the code requires comments.
**Input Details**:
1. Clipboard Content:
${clipboardContentPrompt}
**Do not include any markdown syntax or wrap the code in a markdown code block.**
2. Current File:
File: ${currentFileRelativePath}
\`\`\`
${currentFileContent}
\`\`\`
Here are the details:
3. Reference Files:
${referenceFileContent}
${clipboardContentPrompt}
2. Current file content:
File: ${currentFileRelativePath}
\`\`\`
${currentFileContent}
\`\`\`
3. Reference files content:
${referenceFileContent}
**In short, you are always very smart to guess my intention based on the position where I paste, and then automatically convert the code.**
Please convert the clipboard content to match the programming language and context of the current file, I will insert the converted code at the specified location.
**Please do not reply with any text other than the code, and do not use markdown syntax**
`
**Final Reminder**:
Convert the clipboard content to match the programming language and context of the current file. **Only provide the converted code.**
`

const messages: BaseMessage[] = []

Expand Down
Loading

0 comments on commit 9a57c03

Please sign in to comment.