vscode Editable Virtual Documents in Extensions - visual-studio-code

I am trying to use vscode to write an extension which interacts with my backend service.
The problem I am having is that my "documents" that I want to edit are actually nested JSON documents. The top level document I am managing looks something like this for instance:
{
'filename': 'My JSON info.exp',
'filecontent': '{"this": "that"}'
}
I'd like to open and edit these files in vscode.
Using Virtual Documents I got to the point where I could open a document from a custom tree, and display the filecontent in a document named with the filename. Worked perfectly until I tried to edit the document content.
I'd like to provide an editor for just the filecontent, then handle things like saves myself using my API.
I looked into the FileSystem Provider, but it doesn't look like what I am looking for as the uris have to actually exist... I think?
Any hints or suggestions?

I'm trying to do something similar with Joplin - opening, editing and saving notes via a REST API.
I'm not as far along as you, but it was my understanding from scanning through the docs that Virtual Documents were read-only. Because of that, I'm dropping my content into a TextDocument so it can be edited; I am super curious if there's a way to override a document's onSave() to do what we're both after.
Below is what I'm doing to open the text document; if you could share any insights into your progress (or better yet code) that'd be awesome.
async openNote(item: Omit<FolderOrNote, 'item'> & { item: JoplinListNote }) {
console.log('openNote: ', item.id, await
noteApi.get(item.id, [
'id',
'parent_id',
'title',
'is_todo',
'todo_completed',
'body'
]).then (
note => {
vscode.workspace.openTextDocument( {
content: note.body,
language: 'markdown'
} ).then(
doc => vscode.window.showTextDocument( doc )
);
}
)
)
}
Edit:
Digging around some more it looks like maybe a CustomEditor is needed. A CustomEditor requires the extension to implement things like loading and saving into the model because VS Code is unaware of how to deal with the raw data. There is also a CustomTextEditor but that appears to be tied to the local filesystem.
There's a YouTube video here that talks about it in detail:
https://youtu.be/Dekn2MHy9Os?t=1147
Here's the sample code:
https://github.com/microsoft/vscode-extension-samples/tree/main/custom-editor-sample

Related

VsCode Extension custom CompletionItem disables built-in Intellisense

I am working on a VsCode extension in that I want to provide custom snippets for code completion.
I know about the option of using snippet json files directly, however those have the limitation of not being able to utilize the CompletionItemKind property that determines the icon next to the completion suggestion in the pop-up.
My issue:
If I implement a simple CompletionItemProvider like this:
context.subscriptions.push(
vscode.languages.registerCompletionItemProvider(
{scheme:"file",language:"MyLang"},
{
provideCompletionItems(document: vscode.TextDocument, position: vscode.Position) {
let item = new vscode.CompletionItem('test');
item.documentation = 'my test function';
item.kind = vscode.CompletionItemKind.Function;
return [item];
}
}
)
)
then the original VsCode IntelliSense text suggestions are not shown anymore, only my own. Should I just return a kind of an empty response, like
provideCompletionItems(document: vscode.TextDocument, position: vscode.Position) {
return [null|[]|undefined];
}
the suggestions appear again as they should. It seems to me that instead of merging the results of the built-in IntelliSense and my own provider, the built-in ones get simply overridden.
Question:
How can I keep the built-in IntelliSense suggestions while applying my own CompletionItems?
VsCode Version: v1.68.1 Ubuntu
I seem to have found the answer for my problem, so I will answer my question.
Multiple providers can be registered for a language. In that case providers are sorted
by their {#link languages.match score} and groups of equal score are sequentially asked for
completion items. The process stops when one or many providers of a group return a
result.
My provider seems to provide results that are just higher scored than those of IntelliSense.
Since I didn't provide any trigger characters, my CompletionItems were comteping directly with the words found by the built-in system by every single pressed key and won.My solution is to simply parse and register the words in my TextDocument myself and extend my provider results by them. I could probably just as well create and register a new CompletionItemProvider for them if I wanted to, however I decided to have a different structure for my project.

VSCode: obtain editor content in Language Server

I'm trying to develop a Language Server to a new language in VS Code and I'm using the Microsoft sample as reference (https://github.com/microsoft/vscode-extension-samples/tree/master/lsp-sample).
In their sample the autocompletion is done in this chunk of code:
connection.onCompletion(
(_textDocumentPosition: TextDocumentPositionParams): CompletionItem[] => {
// The pass parameter contains the position of the text document in
// which code complete got requested. For the example we ignore this
// info and always provide the same completion items.
return [
{
label: 'TypeScript',
kind: CompletionItemKind.Text,
data: 1
},
{
label: 'JavaScript',
kind: CompletionItemKind.Text,
data: 2
}
];
}
);
As the comment says, it's a dumb autocompletion system, since it always provides the same suggestions.
I can see that there's an input parameter of type TextDocumentPositionParams and this type has the following interface:
export interface TextDocumentPositionParams {
/**
* The text document.
*/
textDocument: TextDocumentIdentifier;
/**
* The position inside the text document.
*/
position: Position;
}
It has the cursor position and a TextDocumentIdentifier but the last only has a uri property.
I want to create an intelligent autocomplete system, based on the type of the object of the word in the cursor position.
This sample is very limited and I'm kinda lost here. I guess I could read the file in the uri property and based on the cursor position I could figure out which items I should suggest. But how about when the file is not saved? If I read the file I would read the data that is on disk, and not what is currently shown in the editor.
What's the best approach to do that?
The Language Server Protocol supports text synchronization, see TextDocumentSyncOptions in ServerCapabilities and the corresponding methods (textDocument/didChange, didChange, didClose...). A Language Server will usually keep a copy of all open documents in memory.
The sample you linked actually makes use of this, but the synchronization itself is abstracted away into the TextDocuments class from vscode-languageserver. As a result server.ts doesn't have to do much more than this:
let documents: TextDocuments = new TextDocuments();
[...]
documents.listen(connection);
You can then simply use documents.get(uri).getText() to obtain the text shown in the editor.

How do I customize wintersmith paginator?

I've been setting up a site with Wintersmith and am loving it for the most part, but I cannot wrap my head around some of the under-the-hood mechanics. I started with the "blog" skeleton that adds the paginator.coffee plugin.
The question requires some details, so up top, what I'm trying to accomplish:
Any files (markdown, html, json metadata) will be picked up either in /contents/article/<file> or /contents/articles/<subdir>/<file>
Output files are at /articles/YYYY/MM/DD/title-slug/
/blog.html lists all articles, paginated.
Files just under /contents (not in articles) are not treated as blog posts. Markdown and JSON metadata are still processed, but no permalinked URLs, not included in blog listings, file/directory structure is more directly copied over.
So, I solved #1 with this suggestion: How can I have articles in Wintersmith not in their own subdirectory? So far, great, and #3 is working -- the paginated listing includes all posts. #4 has not been an issue, it's the default behavior.
On #2 I found this solution: http://andrewphilipclark.com/2013/11/08/removing-the-boilerplate-from-wintersmith-blog-posts/ . As the author mentions, his solution was (sort of) subsequently incorporated into Wintersmith master, so I tried just setting the filenameTemplate accordingly. Unfortunately this applies to all content, not just that under /articles, so the rest of my site gets hosed (breaks #4). So then I tried the author's approach, adding a blogpost.coffee plugin using his code. This generates all the files out of /contents/articles into the correct permalink URLs, however the paginator now for some reason will no longer see files directly under /articles (point #1).
I've tried a lot of permutations and hacking. Tried changing the order of which plugin gets loaded first. Tried having PaginatorPage extend BlogpostPage instead of Page. Tried a lot of things. I finally realize, even after inspecting many of the core classes in Wintersmith source, that I do not understand what is happening.
Specifically, I cannot figure out how contents['articles']._.pages and .directories are set, which seems relevant. Nor do I understand what that underscore is.
Ultimately, Jade/CoffeeScript/Markdown are a great combo for minimizing coding and enhancing clarity except when you want to understand what's happening under the hood and you don't know these languages. It took me a bit to get the basics of Jade and CoffeeScript (Markdown is trivial of course) enough to follow what's happening. When I've had to dig into the wintersmith source, it gets deeper. I confess I'm also a node.js newbie, but I think the big issue here is just a magic framework. It would be helpful, for instance, if some of the core "plugins" were included in the skeleton site as opposed to buried in node_modules, just so curious hackers could see more quickly how things interconnect. More verbose docs would of course be helpful too. It's one thing to understand conceptually content trees, generators, views, templates, etc., but understanding the code flow and relations at runtime? I'm lost.
Any help is appreciated. As I said, I'm loving Wintersmith, just wish I could dispel magic.
Because coffee script is rubbish, this is extremely hard to do. However, if you want to, you can destroy the paginator.coffee and replace it with a simple javascript script that does a similar thing:
module.exports = function (env, callback) {
function Page() {
var rtn = new env.plugins.Page();
rtn.getFilename = function() {
return 'index.html';
},
rtn.getView = function() {
return function(env, locals, contents, templates, callback) {
var error = null;
var context = {};
env.utils.extend(context, locals);
var buffer = new Buffer(templates['index.jade'].fn(context));
callback(error, buffer);
};
};
return rtn;
};
/** Generates a custom index page */
function gen(contents, callback) {
var p = Page();
var pages = {'index.page': p};
var error = null;
callback(error, pages);
};
env.registerGenerator('magic', gen);
callback();
};
Notice that due to 'coffee script magic', there are a number of hoops to jump through here, such as making sure you return a buffer from getView(), and 'manually' overriding rather than using the obscure coffee script extension semantics.
Wintersmith is extremely picky about how it handles these functions. If callbacks are not invoked, for the returned value is not a Stream or Buffer, generated files will appear in the content summary, but not be rendered to disk during a build. Enable verbose logging and check of 'skipping foo' messages to detect this.

Search inside word docs and across other websites

Is there a way to configure lucene.net in Orchard to search the content of word docs in a dir under the Orchard root. And is there a way to have it index another website as well.
If you can somehow add the content as contentitems in Orchard, you can use a trick with the OnIndexing method inside a ContentHandler.
Something like this should do it:
public class WordDocumentContentHandler: ContentHandler {
public WordDocumentContentHandler() {
OnIndexing<ContentPart>((context, part) => {
// Detect if the part has the field containing the URL to the document
// and analyze it here.
});
}
}

Programmatically adding an article to Joomla

I am very new to Joomla (frankly just started exploring the possibility of using Joomla) and need help with programmatically adding articles to Joomla backend tables (please see details below). Also along the same lines, I would like to understand how should values for the columns:
parent_id
lft
rgt
level
be generated for the table jos_assets (#__assets) and what is their functional role (eg are they “pointers/indexes” analogous to, say, an os inode to uniquely indentify a file or are they more functional attributes such as identifying the category, subcategory etc)
It might help to use the following SIMPLIFIED example to illustrate what I am trying to do. Say we have a program that collects various key information such as names of the authors of web articles, the subject type of the articles, the date of articles as well as a link to the article. I want to be able to extend this program to programmatically store this information in Joomla. Currently this information is stored in a custom table and the user, through a custom php web page, can use search criteria say by author name, over a certain range of dates to find the article(s) of interest. The result of this search is then displayed along with a hyperlink to the actual article. The articles are stored locally on the web server and are not external links. The portion of the hyperlink stored in the custom table includes the relative path of the physical document (relative to the web root), so for example:
Author date type html_file
Tom 08-14-2011 WEB /tech/11200/ar_324.html
Jim 05-20-2010 IND /tech/42350/ar_985.html
etc.
With all the advantages that Joomla offers over writing custom php search and presentation pages as well as trending etc, we would really like to switch to it. It seems that among other tables for example that #__assets and #__content can be populated programmatically to populate Joomla from our existing php program (which is used to compile the data) and then use Joomla.
Any examples, suggestions and help is greatly appreciated
Kindest regards
Gar
Just an initial note: Joomla 1.6/1.7 are pretty similar. 1.5 not so much. I'll assume 1.6/1.7, as that's what I'd recommend as a base for a new project.
First up, you'll need to be running with access to the Joomla framework. You could do this through a Component, or a module, or a cron that bootstraps it or whatever. I won't go though how to do that.
But once you do that, creating an article is reasonably simple.
<?php
require_once JPATH_ADMINISTRATOR . '/components/com_content/models/article.php';
$new_article = new ContentModelArticle();
$data = array(
'catid' => CATEGORY_ID,
'title' => 'SOME TITLE',
'introtext' => 'SOME TEXT',
'fulltext' => 'SOME TEXT',
'state' => 1,
);
$new_article->save($data);
The actual list of fields will be a bit longer than that (required fields etc), but you should get sane error messages etc from the Joomla framework which illuminate that.
So in summary:
Load up the Joomla framework so you have access to the DB, components, models, etc
Include the com_content article class, which will handle validation, saving to the database etc for you
Create an article instance with the required fields filled in as appropriate
Call save()
Now that I think about it, that'll probably work in 1.5...
Found a better way to do this without any errors Create a Joomla! Article Programatically
$table = JTable::getInstance('Content', 'JTable', array());
$data = array(
'catid' => 1,
'title' => 'SOME TITLE',
'introtext' => 'SOME TEXT',
'fulltext' => 'SOME TEXT',
'state' => 1,
);
// Bind data
if (!$table->bind($data))
{
$this->setError($table->getError());
return false;
}
// Check the data.
if (!$table->check())
{
$this->setError($table->getError());
return false;
}
// Store the data.
if (!$table->store())
{
$this->setError($table->getError());
return false;
}