vscode extension for auto complete inside html script tag

I’m creating a vscode extension that adds some custom autofill capabilities to the script tags inside an html file. It’s based on this example from vscodes extension tutorial page.

I took that example and changed it to look at script tags. So overall the flow of the extension is something like:

  1. A user goes to an .html file, the extension starts
  2. When the user starts typing and vscode generates autocomplete items, it calls provideCompletionItem from my extension
  3. My extension checks if the document is currently located inside a script tag before continuing
  4. Create a virtual document which replaces everything in the file with spaces except for script tag content
  5. Append ;class ExampleClass{method1(){}}; to the end of the virtual document string
  6. Run the default behavior for getting the autocompletion list in the virtual document

The current result of this is when you go to a script tag and start typing, ExampleClass will show up like I want. However when you type ExampleClass.| (‘|’ represents where the cursor is) it only displays the default completion elements. It also produces an error:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>[Extension Host] Unexpected resource embedded-content://js/path/to/file.html.js
</code>
<code>[Extension Host] Unexpected resource embedded-content://js/path/to/file.html.js </code>
[Extension Host] Unexpected resource embedded-content://js/path/to/file.html.js

Before this error pops up it isn’t running the registerTextDocumentContentProvider which returns the virtual content when given a virtual URI. Presumably this means I’m missing some special case for when some path saved in the CompletionItem is accessed but I can’t figure out exactly what that is.

Here is some of the relevant code:

the function that creates virtual file content:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> // the above code is unchanged from the vscode example
let content = documentText
.split('n')
.map(line => {
return ' '.repeat(line.length);
}).join('n');
regions.forEach(r => {
if (r.languageId === languageId) { // languageId == javascript
content = content.slice(0, r.start) + documentText.slice(r.start, r.end) + content.slice(r.end);
}
});
let inject = ';class ExampleClass{method1(){}};';
return content + inject; // does not run on error
}
</code>
<code> // the above code is unchanged from the vscode example let content = documentText .split('n') .map(line => { return ' '.repeat(line.length); }).join('n'); regions.forEach(r => { if (r.languageId === languageId) { // languageId == javascript content = content.slice(0, r.start) + documentText.slice(r.start, r.end) + content.slice(r.end); } }); let inject = ';class ExampleClass{method1(){}};'; return content + inject; // does not run on error } </code>
    // the above code is unchanged from the vscode example

    let content = documentText
        .split('n')
        .map(line => {
            return ' '.repeat(line.length);
        }).join('n');

    regions.forEach(r => {
        if (r.languageId === languageId) { // languageId == javascript
            content = content.slice(0, r.start) + documentText.slice(r.start, r.end) + content.slice(r.end);
        }
    });

    let inject = ';class ExampleClass{method1(){}};';

    return content + inject; // does not run on error
}

serves up the virtual documents:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const virtualDocumentContents = new Map<string, string>();
workspace.registerTextDocumentContentProvider('embedded-content', {
provideTextDocumentContent: uri => {
console.log('get virt file'); // in the case of the error this never logs
// Remove leading `/` and ending `.js` to get original URI
const originalUri = uri.path.slice(1).slice(0, -3);
const decodedUri = decodeURIComponent(originalUri);
if (!virtualDocumentContents.has(decodedUri)) console.warn(`no such virtual file ${decodedUri}`); // this warning never goes off
return virtualDocumentContents.get(decodedUri);
}
});
</code>
<code>const virtualDocumentContents = new Map<string, string>(); workspace.registerTextDocumentContentProvider('embedded-content', { provideTextDocumentContent: uri => { console.log('get virt file'); // in the case of the error this never logs // Remove leading `/` and ending `.js` to get original URI const originalUri = uri.path.slice(1).slice(0, -3); const decodedUri = decodeURIComponent(originalUri); if (!virtualDocumentContents.has(decodedUri)) console.warn(`no such virtual file ${decodedUri}`); // this warning never goes off return virtualDocumentContents.get(decodedUri); } }); </code>
const virtualDocumentContents = new Map<string, string>();

workspace.registerTextDocumentContentProvider('embedded-content', {
    provideTextDocumentContent: uri => {
        console.log('get virt file'); // in the case of the error this never logs
        // Remove leading `/` and ending `.js` to get original URI
        const originalUri = uri.path.slice(1).slice(0, -3);
        const decodedUri = decodeURIComponent(originalUri);
        if (!virtualDocumentContents.has(decodedUri)) console.warn(`no such virtual file ${decodedUri}`); // this warning never goes off
        return virtualDocumentContents.get(decodedUri);
    }
});

Provide CompletionItems

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const clientOptions: LanguageClientOptions = {
documentSelector: [{ scheme: 'file', language: 'html' }],
middleware: {
provideCompletionItem: async (document, position, context, token, next) => {
console.log('auto completion...'); // does not run on error
if (!isInsideScriptRegion(htmlLanguageService, document.getText(), document.offsetAt(position))) {
return await next(document, position, context, token);
}
const originalUri = document.uri.toString(true);
const virtContent = getVirtualContent(htmlLanguageService, document.getText(), 'javascript');
virtualDocumentContents.set(originalUri, virtContent);
const vdocUriString = `embedded-content://js/${encodeURIComponent(
originalUri
)}.js`;
const vdocUri = Uri.parse(vdocUriString);
const compArr = await commands.executeCommand<CompletionList>(
'vscode.executeCompletionItemProvider',
vdocUri,
position,
context.triggerCharacter
);
env.clipboard.writeText(virtContent); // for debugging, this of course also does not run when the error occurs
console.log('write board');
return compArr;
}
}
}
</code>
<code>const clientOptions: LanguageClientOptions = { documentSelector: [{ scheme: 'file', language: 'html' }], middleware: { provideCompletionItem: async (document, position, context, token, next) => { console.log('auto completion...'); // does not run on error if (!isInsideScriptRegion(htmlLanguageService, document.getText(), document.offsetAt(position))) { return await next(document, position, context, token); } const originalUri = document.uri.toString(true); const virtContent = getVirtualContent(htmlLanguageService, document.getText(), 'javascript'); virtualDocumentContents.set(originalUri, virtContent); const vdocUriString = `embedded-content://js/${encodeURIComponent( originalUri )}.js`; const vdocUri = Uri.parse(vdocUriString); const compArr = await commands.executeCommand<CompletionList>( 'vscode.executeCompletionItemProvider', vdocUri, position, context.triggerCharacter ); env.clipboard.writeText(virtContent); // for debugging, this of course also does not run when the error occurs console.log('write board'); return compArr; } } } </code>
const clientOptions: LanguageClientOptions = {
    documentSelector: [{ scheme: 'file', language: 'html' }],
    middleware: {
        provideCompletionItem: async (document, position, context, token, next) => {
            console.log('auto completion...'); // does not run on error

            if (!isInsideScriptRegion(htmlLanguageService, document.getText(), document.offsetAt(position))) {
                return await next(document, position, context, token);
            }

            const originalUri = document.uri.toString(true);
            
            const virtContent = getVirtualContent(htmlLanguageService, document.getText(), 'javascript');
            virtualDocumentContents.set(originalUri, virtContent);

            const vdocUriString = `embedded-content://js/${encodeURIComponent(
                originalUri
            )}.js`;
            const vdocUri = Uri.parse(vdocUriString);

            const compArr = await commands.executeCommand<CompletionList>(
                'vscode.executeCompletionItemProvider',
                vdocUri,
                position,
                context.triggerCharacter
            );

            env.clipboard.writeText(virtContent); // for debugging, this of course also does not run when the error occurs
            console.log('write board');

            return compArr;
        }
    }
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật