How to avoid opening a QuickInput when choosing files to compare in a vscode extension? - visual-studio-code

In my case I want to compare two files.
But I don't want the user to select the File in the QuickInput form, i want to choose this directly for him.
vscode.commands.executeCommand("workbench.files.action.compareFileWith", filePath)
This results in
Meaning that filePath is ignored and a QuickInput is displayed instead.
Is there a way to directly select a file programmatically instead of showing the QuickInput first?

While the compareFileWith command probably requires a QuickInput panel to use, you can use the other compare commands to do what you want:
// using the current file for the 'compareWith' file
const currentFileUri = vscode.window.activeTextEditor.document.uri;
// create a Uri from some filePath
const compareWithSelectedUri = vscode.Uri.file('C:\\Users\\Mark\\OneDrive\\Test Bed\\BAR.txt');
await vscode.commands.executeCommand('selectForCompare', currentFileUri)
await vscode.commands.executeCommand('compareFiles', compareWithSelectedUri);
This works in my testing.
Looking at compareFileWith in https://github.com/microsoft/vscode/blob/9b9361cfd1b0678f0bb0b32bf9925b6520bb9926/src/vs/workbench/contrib/files/browser/fileActions.ts I don't think there is any way to avoid the QuickInput opening.
Alternatively, what you are asking for would be "easy" if an open method were supported on TabGroups api like the close methods. You would create a tab of kind TabInputTextDiff with an original uri and a modifieed uri.
When the TabGroups api was being developed there was an open tab method but it was removed prior to release and hasn't seen any love since. See https://github.com/microsoft/vscode/commit/aa69f3d7623c464aba726d12ea0d83428f43e8b9#commitcomment-71831337.
I'll open an issue to see if it will help (and post the link here later).

Related

How can I manually edit the list of recently opened files in VS Code?

I rely heavily on the File: Open Recent… command to open frequently used files, but yesterday my local Google Drive folder got moved to a new location and now I can no longer access any of the files in that folder through the Open Recent panel because the paths don't match.
The fix would be as simple as replacing "/Google Drive/" with "/Google Drive/My Drive/" but I have no idea what file contains the list of files that appears in the recently opened panel.
I'm assuming it's somewhere in ~/Library/Application Support/Code but not sure where.
I was wondering the same thing the other day and found this while searching for a solution, so I took some time to investigate it today.
It's been a a few weeks since you posted, so hopefully this will still be of help to you.
Also, I'm using Windows and I'm not familiar with macOS, but I think it should be easy enough adjust the solution.
Location of settings
Those setting are stored in the following file: %APPDATA%\Code\User\globalStorage\state.vscdb.
The file is an sqlite3 database, which is used as a key-value store.
It has a single table named ItemTable and the relevant key is history.recentlyOpenedPathsList.
The value has the following structure:
{
"entries": [
{
"folderUri": "/path/to/folder",
"label": "...",
"remoteAuthority": "..."
}
]
}
To view the current list, you can run the following command:
sqlite3.exe -readonly "%APPDATA%\Code\User\globalStorage\state.vscdb" "SELECT [value] FROM ItemTable WHERE [key] = 'history.recentlyOpenedPathsList'" | jq ".entries[].label"
Modifying the settings
Specifically, I was interested in changing the way it's displayed (the label), so I'll detail how I did that, but it should be just as easy to update the path.
Here's the Python code I used to make those edits:
import json, sqlite3
# open the db, get the value and parse it
db = sqlite3.connect('C:/Users/<username>/AppData/Roaming/Code/User/globalStorage/state.vscdb')
history_raw = db.execute("SELECT [value] FROM ItemTable WHERE [key] = 'history.recentlyOpenedPathsList'").fetchone()[0]
history = json.loads(history_raw)
# make the changes you'd like
# ...
# stringify and update
history_raw = json.dumps(history)
db.execute(f"UPDATE ItemTable SET [value] = '{history_raw}' WHERE key = 'history.recentlyOpenedPathsList'")
db.commit()
db.close()
Code references
For reference (mostly for my future self), here are the relevant source code areas.
The settings are read here.
The File->Open Recent uses those values as-is (see here).
However when using the Get Started page, the Recents area is populated here. In the Get Started, the label is presented in a slightly different way:
vscode snapshot
The folder name is the link, and the parent folder is the the text beside it.
This is done by the splitName method.
Notes
Before messing around with the settings file, it would be wise to back it up.
I'm not sure how vscode handles and caches the settings, so I think it's best to close all vscode instances before making any changes.
I haven't played around with it too much, so not sure how characters that need to be json-encoded or html-encoded will play out.
Keep in mind that there might be some state saved by other extensions, so if anything weird happens, blame it on that.
For reference, I'm using vscode 1.74.2.
Links
SQLite command-line tools
jq - command-line JSON processor

Word addin, set filename

If one starts a blank file on Word you can usually see in the top bar a name such as "Document1", "Document2" and so on.
Yet, if you attempt to open a file using the Word JS API like this:
Word.run((context) => {
context.application.createDocument(documentB64).open()
return context.sync()
})
The top bar comes out like this:
No filename is set.
To set a filename/handle(?), I tried using the code given here Office JS - Add customProperty to new document but that didn't help.
My addin is usually used in conjunction with another (VSTO) add-on and that add-on can't work properly with the documents opened by my addin and I believe the lack of a filename (/handle?) explains it to some extent.
Is there something I can do about this?
Thank you
Currently you can't do this because the newly created document is just a temporary file and not saved. can you try to call the following code to make sure the newly created file is saved?
const documentCreated = context.application.createDocument(externalDoc);
documentCreated.save();
documentCreated.open();

Can you get access to a pages front matter (or other data) in a eleventy (11ty) plugin

I'm creating (would like to create) an eleventy (11ty) plugin that can automatically generate Open Graph images based on a pages data. So in the template:
---
generate_og_image: true
image_text: "text which will be baked into the image"
og_image_filename: some_file_name.jpg
---
#some markdown
...
I can process each file in my .eleventy.js file via plugin using:
module.exports = function (eleventyConfig) {
eleventyConfig.addLinter("og-image-generator", function(content, inputPath, outputPath) {
title = HOW_TO_ACCESS_TEMPLATE_FRONT_MATTER
createImage(title)
});
}
But only have access to the content, inputPath and outputPath of the template.
How can I access the front matter data associated with the Template? Or is there a better way to go about this?
Answering my own question. As #moritzlost mentioned it is not possible directly. I found this workaround.
eleventyComputed allows you to dynamically assign values to keys. It also allows you to call a custom shortcode.
You can pass whatever properties you like from the template into the shortcode. In this case ogImageName the image name, ogImageTemplate a template or background image and text which is the text to be written on that background.
You can even pass in other keys from your front matter and process them as you go.
---
layout: _main.njk
title: "Some title here"
eleventyComputed:
ogImageName: "{% ogCreateImage { ogImageName: title | slug, ogImageTemplate: 'page-blank.png', text: title } %}"
---
Then in .eleventy.js or a plugin:
eleventyConfig.addShortcode("ogCreateImage", function(props) {
const imageName = props.ogImageName
const imageTemplate = props.ogImageTemplate
const imageText = props.text
console.log('-----------------ogCreateImage-----------------');
console.log(`filename: ${imageName}`);
console.log(`using template: ${imageTemplate}`);
console.log(`with the text : ${imageText}`);
// call the image creation code — return filename with extension
const imageNameWithExtension = createOGImage(imageName, imageTemplate, imageText)
return imageNameWithExtension
});
Returning the final filename which you can use in your template.
I've also come across this problem. I don't think what you're trying to do is possible at the moment. There are not many ways for a plugin to hook into the build step directly:
Transforms
Linters
Events
I think events would be the best solution. However, events also don't receive enough information to process a template in a structured way. I've opened an issue regarding this on Github. For your use-case, you'd need to get structured page data in this hook as well. Or eleventy would need to provide a build hook for each page. I suggest opening a new feature-request issue or adding a comment with your use-case to my issue above so those hooks can be implemented.
Other solutions
Another solution that requires a bit more setup for the users of your plugin would be to add your functionality as a filter instead of an automatic script that's applied to every template. This means that the users of your plugin would need to add their own template which passes the relevant data to your filter. Of course this also gives more fine-control to the user, which may be beneficial.
I use a similar approach for my site processwire.dev:
A special template loops over all posts and generates an HTML file which is used as a template for the generated preview images. This template is processed by eleventy. (source)
After the build step: I start a local server in the directory with the generated HTML files, open them using puppeteer and programmatically take a screenshot which is saved alongside the HTML templates. The HTML templates are then deleted.
This is integrated into the build step with a custom script that is executed after the eleventy build.
I've published the script used to take screenshots with Puppeteer as an NPM package (generate-preview-images), though it's very much still in alpha. But you can check the source code on Github to see how it works, maybe it helps with your plugin.

In a VS Code extension, how can I be notified when the user cuts/copies/or pastes?

For my extension I need to know when a cut/copy/paste happens and be able to get the text associated with those operations. I can probably get the text from the editor if I know when they happen.
I cannot find a listener for these operations. I suppose I can look for ctrl-x, ctrl-c, and ctrl-v keyboard inputs but some users may use the edit menu and not use the keyboard.
Is there a way to be notified when these operations happen either from the keyboard or the edit menu?
Original asker here...
I came up with a solution that involves overriding the default cut/copy/paste actions in the editor. Here is the code for 'copy' in extension.js (I am using js not ts):
//override the editor.action.clipboardCopyAction with our own
var clipboardCopyDisposable = vscode.commands.registerTextEditorCommand('editor.action.clipboardCopyAction', overriddenClipboardCopyAction);
context.subscriptions.push(clipboardCopyDisposable);
/*
* Function that overrides the default copy behavior. We get the selection and use it, dispose of this registered
* command (returning to the default editor.action.clipboardCopyAction), invoke the default one, and then re-register it after the default completes
*/
function overriddenClipboardCopyAction(textEditor, edit, params) {
//debug
console.log("---COPY TEST---");
//use the selected text that is being copied here
getCurrentSelectionEvents(); //not shown for brevity
//dispose of the overridden editor.action.clipboardCopyAction- back to default copy behavior
clipboardCopyDisposable.dispose();
//execute the default editor.action.clipboardCopyAction to copy
vscode.commands.executeCommand("editor.action.clipboardCopyAction").then(function(){
console.log("After Copy");
//add the overridden editor.action.clipboardCopyAction back
clipboardCopyDisposable = vscode.commands.registerTextEditorCommand('editor.action.clipboardCopyAction', overriddenClipboardCopyAction);
context.subscriptions.push(clipboardCopyDisposable);
});
}
This definitely doesn't feel like the best solution... however it does seem to work. Any comments/suggestions? Are there any issues that repeatedly registering and unregistering will cause?
There is no api to access the clipboard directly but some extensions override the default copy and paste shortcuts to customize the copy paste behavior. Here are two examples:
https://github.com/aefernandes/vscode-clipboard-history-extension/blob/master/src/clipboard.ts
https://github.com/stef-levesque/vscode-multiclip/blob/master/src/extension.ts
As you note, that approach will not work when copying using the context menu however. For supporting that as well, you could try intercepting the editor.action.clipboardCopyAction command. See how the Vim extension intercepts the type command for an example of this: https://github.com/VSCodeVim/Vim/blob/aa8d9549ac0d31b393a9346788f9a9a93187c222/extension.ts#L208
There is a proposed api in v1.68 for intercepting and modifying pastes. Since it is proposed for now you can only test it in the Insiders Build.
See copy/paste proposed extension api:
The new documentPaste API proposal lets extensions hook into copy
and paste inside text editors. This can be used to modify the text
that is inserted on paste. Your extension can also store metadata when
text copy and use this metadata when pasting (for example for bringing
along imports when pasting between two code files).
The document paste extension
sample
shows this API in action: <-long code example in the release notes->
Here is the actual (brief) api: proposed documentPaste api
See also using a proposed api

Joomla template parameters and params.ini - file becomes unwritable after save

I am using wamp on Win XP SP3 and creating a Joomla template with changeable parameters.
initially the message is
The parameter file \templates\ssc_2010\params.ini is
writable!
once I make changes everything works as expected, except now i get the message:
The parameter file \templates\ssc_2010\params.ini is
unwritable!
One solution is to brows to the directory, right click the file, select properties, and uncheck read-only. Again the file is writable but once I modify the parameters again it becomes read only again. I'm quite lazy and would like to prevent this from happening again, I've notice this happening in past projects, but now I have to work a lot with parameters so it becomes quite boring doing manual labor like that :P
There is a bug in Joomla 1.5 that causes the message to be displayed.
A security feature was added that makes the template files unwritable until just before save, where they are made writable, saved, then made unwritable again.
Try to make a change, then go back and check the preview. You will see that the change was actually made.
If you want to fix the annoying unwritable message, add the following code to
administrator/components/controller.php around line 179, just after setting the FTP credentials:
$file = $client->path.DS.'templates'.DS.$template.DS.'params.ini';
// Try to make the params file writeable
if (!$ftp['enabled'] && JPath::isOwner($file) && !JPath::setPermissions($file, '0755')) {
JError::raiseNotice('SOME_ERROR_CODE', JText::_('Could not make the template parameter file writable'));
}
This will make the file writable during the edit load process, and before the file's status is posted in the template.
Then for security, in case the edit screen is closed without saving, search for the following lines:
require_once (JPATH_COMPONENT.DS.'admin.templates.html.php');
TemplatesView::editTemplate($row, $lists, $params, $option, $client, $ftp, $template);
and paste the following code just AFTER these lines but before the closing brace:
// Try to make the params file unwriteable
if (!$ftp['enabled'] && JPath::isOwner($file) && !JPath::setPermissions($file, '0555')) {
JError::raiseNotice('SOME_ERROR_CODE', JText::_('Could not make the template parameter file unwritable'));
}
That will make the file unwritable again.
This is the same code that is used in the saveTemplate() function. We are just doing it again before we display the status of the file on the edit screen. If the process fails because of your web server's configuration, you will get warning messages, BEFORE you've made a bunch of changes to your template. :)
P.S. Remember to save a copy of this file separately, so that you can redo the changes when you upgrade Joomla! (if they haven't fixed this themselves yet.)
This sounds like a user rights problem within Windows - have a look a the security permissions for the directory in which the file you are editing is located, and check that the user "IUSR_xxx" (where xxx is the name of your computer) has full control.
If this doesn't work, then can you tell us what version of Windows you are running as this may help...
Matt