export function activate(context: vscode.ExtensionContext) {
    class BrowserContentProvider implements vscode.TextDocumentContentProvider {
        provideTextDocumentContent(uri: vscode.Uri, token: vscode.CancellationToken): string {
            // TODO: detect failure to load page (e.g. google.com) and display error to user.
            return `<iframe src="${uri}" frameBorder="0" style="width: 100%; height: 100%" />`;
        }
    }
    let provider = new BrowserContentProvider();

    // Handle http:// and https://.
    let registrationHTTPS = vscode.workspace.registerTextDocumentContentProvider('https', provider);
    let registrationHTTP = vscode.workspace.registerTextDocumentContentProvider('http', provider);

    // urlIsValid returns true if url is valid; false otherwise.
    // TODO: test more robustly.
    function urlIsValid(url: string): boolean {
        if (url.startsWith("http://") || url.startsWith("https://")) {
            return true;
        }
        return false;
    }

    let disposable = vscode.commands.registerCommand('extension.openURL', () => {
        let opts: vscode.InputBoxOptions = {
            prompt: "URL",
            value: "https://",
            validateInput: (url) => {
                if (urlIsValid(url)) {
                    return null;
                }
                return "Invalid URL.";
            },
        };
        vscode.window.showInputBox(opts).then(
            (url) => {
                if (!urlIsValid(url)) {
                    return;
                }

                let uri = vscode.Uri.parse(url);

                // Determine column to place browser in.
                let col: vscode.ViewColumn;
                let ae = vscode.window.activeTextEditor;
                if (ae != undefined) {
                    col = ae.viewColumn || vscode.ViewColumn.One;
                } else {
                    col = vscode.ViewColumn.One;
                }

                return vscode.commands.executeCommand('vscode.previewHtml', uri, col).then((success) => {
                }, (reason) => {
                    vscode.window.showErrorMessage(reason);
                }
                );
            });
    });

    context.subscriptions.push(disposable);
}
Example #2
0
	test('registerTextDocumentContentProvider, constrains', function() {

		// built-in
		assert.throws(function() {
			workspace.registerTextDocumentContentProvider('untitled', { provideTextDocumentContent() { return null; } });
		});
		// built-in
		assert.throws(function() {
			workspace.registerTextDocumentContentProvider('file', { provideTextDocumentContent() { return null; } });
		});

		// duplicate registration
		let registration = workspace.registerTextDocumentContentProvider('foo', {
			provideTextDocumentContent(uri) {
				return uri.toString();
			}
		});
		assert.throws(function() {
			workspace.registerTextDocumentContentProvider('foo', { provideTextDocumentContent() { return null; } });
		});

		// unregister & register
		registration.dispose();
		registration = workspace.registerTextDocumentContentProvider('foo', { provideTextDocumentContent() { return null; } });
		registration.dispose();

		// missing scheme
		return workspace.openTextDocument(Uri.parse('notThere://foo/far/boo/bar')).then(() => {
			assert.ok(false, 'expected failure')
		}, err => {
			// expected
		})
	});
Example #3
0
export function activate(context: ExtensionContext) {
    
    let version = "5.20161.151";
    let previewUri: Uri;
    let csvProvider = new csv.CsvDocumentContentProvider(version);
    let csvSubscription = workspace.registerTextDocumentContentProvider('csv-preview', csvProvider);
    let excelProvider = new excel.ExcelDocumentContentProvider(version);
    let excelSubscription = workspace.registerTextDocumentContentProvider('excel-preview', excelProvider);
    
    workspace.onDidChangeTextDocument((e: TextDocumentChangeEvent) => {
        if (e.document === window.activeTextEditor.document) {
            csvProvider.update(previewUri);
        }
    });
    
    let csvCommand = commands.registerCommand('csv.preview', () => {
        let file = window.activeTextEditor.document.fileName;
        if (file.startsWith("/")) {
            file = file.substring(1);
        }
        previewUri = Uri.parse(`csv-preview://preview/${file}`);
        return commands.executeCommand('vscode.previewHtml', previewUri, ViewColumn.One).then((success) => {
        }, (reason) => {
            window.showErrorMessage(reason);
        });
    });
    
    let excelCommand = commands.registerCommand('excel.preview', () => {
        var files = workspace.findFiles('**/*.xls*', '**/node_modules/**').then((value: Uri[]) => {
            var path = workspace.rootPath;
            var uris = value.map(function (u) {
                return u.path.slice(path.length + 1);
            });
            if (!path.startsWith("/")) {
                path = "/" + path;
            }
            window.showQuickPick(uris).then(sel => {
                excelProvider.setPath(sel);
                previewUri = Uri.parse(`excel-preview://preview${path}/${sel}`);
                return commands.executeCommand('vscode.previewHtml', previewUri, ViewColumn.One).then((success) => {
                }, (reason) => {
                    window.showErrorMessage(reason);
                });                
            });
        });
    });
    
    context.subscriptions.push(csvCommand, csvSubscription);
    context.subscriptions.push(excelCommand, excelSubscription);
}
Example #4
0
function registerPreviewing(context: vscode.ExtensionContext) {
    let previewUri = vscode.Uri.parse('songtools-preview://authority/songtools-preview')
    let songToolsPreviewProvider = new SongToolsPreviewContentProvider();
    context.subscriptions.push(vscode.workspace.registerTextDocumentContentProvider(previewUri.scheme, songToolsPreviewProvider));

    let previewDocument = function(document: vscode.TextDocument) {
        if (document === vscode.window.activeTextEditor.document) {
            songToolsPreviewProvider.update(previewUri);
        }
    }
    
    vscode.workspace.onDidChangeTextDocument((e: vscode.TextDocumentChangeEvent) => {
        previewDocument(e.document);
    });
    vscode.window.onDidChangeActiveTextEditor((e: vscode.TextEditor) => {
        previewDocument(e.document);
    });
    
    vscode.commands.registerCommand('songtools.showPreview', () => {
        return vscode.commands.executeCommand('vscode.previewHtml', previewUri, vscode.ViewColumn.Two).then((success) => {
        }, (error) => {
            vscode.window.showErrorMessage(error);
        });
    });
}
Example #5
0
export async function activateLanguageServer(context: vscode.ExtensionContext) {
    const r = RLanguage.language;
    // The server is implemented in C#
    const commandOptions = { stdio: "pipe" };
    const serverModule = context.extensionPath + "/server/Microsoft.R.LanguageServer.dll";

    // If the extension is launched in debug mode then the debug server options are used
    // Otherwise the run options are used
    const serverOptions: languageClient.ServerOptions = {
        debug: { command: "dotnet", args: [serverModule, "--debug"], options: commandOptions },
        run: { command: "dotnet", args: [serverModule], options: commandOptions },
    };

    // Options to control the language client
    const clientOptions: languageClient.LanguageClientOptions = {
        // Register the server for R documents
        documentSelector: [r],
        synchronize: {
            configurationSection: r,
        },
    };

    // Create the language client and start the client.
    client = new languageClient.LanguageClient(r, "R Tools", serverOptions, clientOptions);
    context.subscriptions.push(client.start());

    await client.onReady();

    rEngine = new REngine(client);
    const resultsView = new ResultsView();
    context.subscriptions.push(vscode.workspace.registerTextDocumentContentProvider("r", resultsView));

    commands = new Commands(rEngine, resultsView);
    context.subscriptions.push(...commands.activateCommandsProvider());
}
Example #6
0
	test('api-command: vscode.diff', function () {

		let registration = workspace.registerTextDocumentContentProvider('sc', {
			provideTextDocumentContent(uri) {
				return `content of URI <b>${uri.toString()}</b>#${Math.random()}`;
			}
		});


		let a = commands.executeCommand('vscode.diff', Uri.parse('sc:a'), Uri.parse('sc:b'), 'DIFF').then(value => {
			assert.ok(value === void 0);
			registration.dispose();
		});

		let b = commands.executeCommand('vscode.diff', Uri.parse('sc:a'), Uri.parse('sc:b')).then(value => {
			assert.ok(value === void 0);
			registration.dispose();
		});

		let c = commands.executeCommand('vscode.diff', Uri.parse('sc:a'), Uri.parse('sc:b'), 'Title', { selection: new Range(new Position(1, 1), new Position(1, 2)) }).then(value => {
			assert.ok(value === void 0);
			registration.dispose();
		});

		let d = commands.executeCommand('vscode.diff').then(() => assert.ok(false), () => assert.ok(true));
		let e = commands.executeCommand('vscode.diff', 1, 2, 3).then(() => assert.ok(false), () => assert.ok(true));

		return Promise.all([a, b, c, d, e]);
	});
Example #7
0
export function activate(context: ExtensionContext) 
{
	const provider = new ContentProvider();

	const providerRegistrations = Disposable.from(
		workspace.registerTextDocumentContentProvider(ContentProvider.scheme, provider)
	);
    
	const commandRegistration = commands.registerTextEditorCommand('editor.printFunctions', editor => {
        return provider.newDocument(editor);
	});

    let contextMenuSwitchSort = commands.registerCommand('contextmenu.switchSort', () => {
        provider.updateDocument(true);
    });
    
    let contextMenuRefresh = commands.registerCommand('contextmenu.refresh', () => {
        provider.updateDocument(false);
    });
        
	context.subscriptions.push(
		provider,
        commandRegistration,
        contextMenuSwitchSort,
        contextMenuRefresh,
        providerRegistrations
    );
}
Example #8
0
export function activate(ctx: vsc.ExtensionContext) {
    console.log('activate extension');
    // expose global and workspace state to the entire extension
    GlobalState = ctx.globalState;
    WorkspaceState = ctx.workspaceState;
    
	// register palette commands
    ctx.subscriptions.push(
        vsc.commands.registerTextEditorCommand('xmlTools.minifyXml', TextEditorCommands.minifyXml),
        vsc.commands.registerTextEditorCommand('xmlTools.evaluateXPath', TextEditorCommands.evaluateXPath),
        vsc.commands.registerTextEditorCommand('xmlTools.executeXQuery', TextEditorCommands.executeXQuery),
        vsc.commands.registerTextEditorCommand('xmlTools.viewXmlTree', TextEditorCommands.viewXmlTree)
    );
	
	// register language feature providers
    ctx.subscriptions.push(
        vsc.languages.registerDocumentFormattingEditProvider(LANG_XML, new XmlFormattingEditProvider()),
        vsc.languages.registerDocumentRangeFormattingEditProvider(LANG_XML, new XmlFormattingEditProvider()),
        
        vsc.languages.registerCompletionItemProvider(LANG_XQUERY, new XQueryCompletionItemProvider(), ':', '$')
    );
    
    // register workspace feature providers
    ctx.subscriptions.push(
        vsc.workspace.registerTextDocumentContentProvider(XmlTreeDocumentContentProvider.SCHEME, new XmlTreeDocumentContentProvider())
    );
    
    // listen to editor events (for linting)
    ctx.subscriptions.push(
        vsc.window.onDidChangeActiveTextEditor(_handleChangeActiveTextEditor),
        vsc.window.onDidChangeTextEditorSelection(_handleChangeTextEditorSelection)
    );
}
Example #9
0
export function activate(context: vscode.ExtensionContext) {
    cljConnection.setCljContext(context);
    context.subscriptions.push(nreplController);
    cljConnection.disconnect(false);
    var config = vscode.workspace.getConfiguration('clojureVSCode');
    if (config.autoStartNRepl) {
        cljConnection.startNRepl();
    }

    maybeActivateFormatOnSave();

    const testResultDataProvidier = buildTestProvider();

    vscode.commands.registerCommand('clojureVSCode.manuallyConnectToNRepl', cljConnection.manuallyConnect);
    vscode.commands.registerCommand('clojureVSCode.stopDisconnectNRepl', cljConnection.disconnect);
    vscode.commands.registerCommand('clojureVSCode.startNRepl', cljConnection.startNRepl);

    const evaluationResultChannel = vscode.window.createOutputChannel('Evaluation results');
    vscode.commands.registerCommand('clojureVSCode.eval', () => clojureEval(evaluationResultChannel));
    vscode.commands.registerCommand('clojureVSCode.evalAndShowResult', () => clojureEvalAndShowResult(evaluationResultChannel));

    vscode.commands.registerCommand('clojureVSCode.testNamespace', () => testNamespace(evaluationResultChannel, testResultDataProvidier));
    vscode.commands.registerCommand('clojureVSCode.runAllTests', () => runAllTests(evaluationResultChannel, testResultDataProvidier));
    vscode.window.registerTreeDataProvider('clojure', testResultDataProvidier);

    vscode.commands.registerTextEditorCommand('clojureVSCode.formatFile', formatFile);

    context.subscriptions.push(vscode.languages.registerCompletionItemProvider(CLOJURE_MODE, new ClojureCompletionItemProvider(), '.', '/'));
    context.subscriptions.push(vscode.languages.registerDefinitionProvider(CLOJURE_MODE, new ClojureDefinitionProvider()));
    context.subscriptions.push(vscode.languages.registerHoverProvider(CLOJURE_MODE, new ClojureHoverProvider()));
    context.subscriptions.push(vscode.languages.registerSignatureHelpProvider(CLOJURE_MODE, new ClojureSignatureProvider(), ' ', '\n'));

    vscode.workspace.registerTextDocumentContentProvider('jar', new JarContentProvider());
    vscode.languages.setLanguageConfiguration(CLOJURE_MODE.language, ClojureLanguageConfiguration);
}
Example #10
0
export function activate(context: vscode.ExtensionContext) {
    let registration = vscode.workspace.registerTextDocumentContentProvider('markdown', {
        provideTextDocumentContent(uri) {
            return new Promise((approve, reject) => {
                fs.readFile(uri.fsPath, (error, buffer) => {
                    if (error) {
                        return reject(error);
                    }
                    
                    const res = md.render(buffer.toString());

                    const baseCss = `<link rel="stylesheet" type="text/css" href="${path.join(__dirname, '..', '..', 'media', 'markdown.css')}" >`;
                    const codeCss = `<link rel="stylesheet" type="text/css" href="${path.join(__dirname, '..', '..', 'media', 'tomorrow.css')}" >`;

                    approve(baseCss + codeCss + res);
                });
            });
        }
    });

    let d1 = vscode.commands.registerCommand('extension.previewMarkdown', () => openPreview());
    let d2 = vscode.commands.registerCommand('extension.previewMarkdownSide', () => openPreview(true));

    context.subscriptions.push(d1, d2, registration);
}
Example #11
0
function* handleOpenTandem() {
  yield take(OPEN_TANDEM_EXECUTED);

  let state: ExtensionState = yield select();
  var textDocumentContentProvider = {
    provideTextDocumentContent(uri) {
      return `
        <html>
          <head>
            <title>Tandem</title>
          </head>
          <body>
            <iframe src="${getIndexUrl(state)}" style="position:absolute;left:0;top:0;width:100vw; height: 100%; border: none;"></iframe>
          </body>
        </html>
      `;
    },
  };

  state.context.subscriptions.push(
    vscode.workspace.registerTextDocumentContentProvider(
      PREVIEW_NAME,
      textDocumentContentProvider)
  );

  while(true) {
    yield call(vscode.commands.executeCommand,
      "vscode.previewHtml",
      PREVIEW_URI,
      vscode.ViewColumn.Two,
      "Tandem"
    );
    yield take(OPEN_TANDEM_EXECUTED);
  }
}
Example #12
0
	test('editor, onDidChangeTextEditorViewColumn (close editor)', () => {

		let actualEvent: TextEditorViewColumnChangeEvent;

		let registration1 = workspace.registerTextDocumentContentProvider('bikes', {
			provideTextDocumentContent() {
				return 'mountainbiking,roadcycling';
			}
		});

		return Promise.all([
			workspace.openTextDocument(Uri.parse('bikes://testing/one')).then(doc => window.showTextDocument(doc, ViewColumn.One)),
			workspace.openTextDocument(Uri.parse('bikes://testing/two')).then(doc => window.showTextDocument(doc, ViewColumn.Two))
		]).then(async editors => {

			let [one, two] = editors;

			await new Promise(resolve => {
				let registration2 = window.onDidChangeTextEditorViewColumn(event => {
					actualEvent = event;
					registration2.dispose();
					resolve();
				});
				// close editor 1, wait a little for the event to bubble
				one.hide();
			});
			assert.ok(actualEvent);
			assert.ok(actualEvent.textEditor === two);
			assert.ok(actualEvent.viewColumn === two.viewColumn);

			registration1.dispose();
		});
	});
Example #13
0
export function activate(context: ExtensionContext) {
	// The server is implemented in node
	let serverModule = context.asAbsolutePath(path.join('server', 'server.js'));
	// The debug options for the server
	let debugOptions = { execArgv: ["--nolazy", "--debug=6004"] };

	// If the extension is launched in debug mode then the debug server options are used
	// Otherwise the run options are used
	let serverOptions: ServerOptions = {
		run: { module: serverModule, transport: TransportKind.ipc },
		debug: { module: serverModule, transport: TransportKind.ipc, options: debugOptions }
	}

	// Options to control the language client
	let clientOptions: LanguageClientOptions = {
		// Register the server for plain text documents
		documentSelector: ['lua'],
		synchronize: {
			// Synchronize the setting section 'languageServerExample' to the server
			configurationSection: 'languageServerExample',
			// Notify the server about file changes to '.clientrc files contain in the workspace
			fileEvents: workspace.createFileSystemWatcher('**/.clientrc')
		}
	}

	// Create the language client and start the client.
	let disposable = new LanguageClient('Language Server Example', serverOptions, clientOptions).start();

	// Push the disposable to the context's subscriptions so that the 
	// client can be deactivated on extension deactivation
	context.subscriptions.push(disposable);

	
	let sel: vscode.DocumentSelector = { language: 'json', pattern: '**/launch.json' };
	context.subscriptions.push(vscode.languages.registerCompletionItemProvider('json', new ComPortAutoCompleteProvider(), ':'));


	const provider = new DeviceInfoContentProvider();
	context.subscriptions.push(workspace.registerTextDocumentContentProvider(DeviceInfoContentProvider.uri.scheme, provider));
	context.subscriptions.push(provider);


	let mcuCommands: NodeMcuCommands = new NodeMcuCommands(context);
	let fsListVisible: boolean = false;

	mcuCommands.onDidListFiles((files: string) => { fsListVisible = true; provider.onFileList(files); });
	mcuCommands.onError((error: string) => { fsListVisible = false; provider.onMessage(error); });
	mcuCommands.onProgressMessage((message: string) => { fsListVisible = false; provider.onMessage(message); });
	mcuCommands.onDidLoadSystemInfo((sysInfo: string) => { fsListVisible = false; provider.onSystemInfo(sysInfo); });
	mcuCommands.onDidReboot(() => { fsListVisible = false; provider.onReboot(); });
	mcuCommands.onFSChanged(() => { if (fsListVisible) { vscode.commands.executeCommand('nodemcu.listFiles'); }});

	context.subscriptions.push(commands.registerCommand('nodemcu.showToolbox', () => {
		provider.onMessage("Select action from the menu above.");
		showNodeMCUToolbox();
	}));
}
 init(viewColumn: number, context: vscode.ExtensionContext, previewUri: vscode.Uri) {
     let proceed = this.checkDocumentIsHTML(true);
     if (proceed) {
         let previewManager = new PreviewManager();
         let registration = vscode.workspace.registerTextDocumentContentProvider('HTMLPreview', previewManager.htmlDocumentContentProvider);
         return vscode.commands.executeCommand('vscode.previewHtml', previewUri, viewColumn).then((success) => {
         });
     }
 }
export function activate(context: ExtensionContext) {
    const windowService = new WindowService();
    const workspaceService = new WorkspaceService();
    const provider = new CoffeeScriptPreviewContentProvider(windowService);
    const csPreview = new CoffeeScriptPreview(provider, workspaceService, windowService);
    const providerRegistration = workspace.registerTextDocumentContentProvider("coffeescript-preview", provider);
    const commandRegistration = commands.registerCommand("extension.coffeescript-preview", csPreview.previewDocument, csPreview);
    const pluginStartup = csPreview.start();
    context.subscriptions.push(commandRegistration, providerRegistration, pluginStartup);
}
export function activate(context: vscode.ExtensionContext) {

    // Use the console to output diagnostic information (console.log) and errors (console.error)
    // This line of code will only be executed once when your extension is activated
    console.log('Congratulations, your extension "vscode-weather-forecase" is now active!');

    vscode.workspace.registerTextDocumentContentProvider('weather', {provideTextDocumentContent(uri: vscode.Uri): Thenable<string> {
        return new Promise((resolve, reject) => {
            try {
                http.get({
                    'host': 'wttr.in',
                    'path': uri.path.replace(/ /g, '_'),
                    'headers': {
                        'User-Agent': 'curl/7.43.0'
                    }
                }, function(response) {
                    // Continuously update stream with data
                    var body = '';
                    response.on('data', function(d) {
                        body += d;
                    });
                    response.on('end', function() {
                        var result = 'Via http://wttr.in' + uri.path + '\r\n\r\n';
                        result += stripColorCode(body);
                        resolve(result);
                    });
                    response.on('error', function(error) {
                        reject(error); 
                    });
                });
            } catch (ex) {
                reject(ex);
            }
        });
    }});
    // The command has been defined in the package.json file
    // Now provide the implementation of the command with  registerCommand
    // The commandId parameter must match the command field in package.json
    let disposable = vscode.commands.registerCommand('weather.forecast', () => {
        vscode.window.showInputBox({
            prompt: 'Input City Name (empty if for current location)',
            placeHolder: 'E.g.: "Seattle,WA", "Paris", "Tokyo,Japan"'
        }).then((city) => {
            if (city != undefined) {
                vscode.workspace.openTextDocument(vscode.Uri.parse('weather://weather/' + city)).then((document) => {    
                    vscode.window.showTextDocument(document); 
                }, (error) => {
                    vscode.window.showErrorMessage(error);
                });
            }
        });
    });

    context.subscriptions.push(disposable);
}
function init(viewColumn: number, context: vscode.ExtensionContext, previewUri: vscode.Uri) {
    let utilities = new Utilities();
    let proceed = utilities.checkFileType();
    if (proceed) {
        let previewManagerController = new PreviewManagerController();
        context.subscriptions.push(previewManagerController);
        let registration = vscode.workspace.registerTextDocumentContentProvider('details-preview', previewManagerController.previewManager);
        return vscode.commands.executeCommand('vscode.previewHtml', previewUri, viewColumn).then((success) => {
        });
    }
}
export function activate(context: vscode.ExtensionContext) {
    // Provides the content for the previewHtml pane.
    context.subscriptions.push(
      vscode.workspace.registerTextDocumentContentProvider('stobot', stobotContent)
    );

    // Registers a handler for the 'startBot' command defined in package.json.
    let disposable = vscode.commands.registerCommand('stobot.startBot', () => {
        vscode.commands.executeCommand('vscode.previewHtml', 'stobot://stobot', vscode.ViewColumn.Two, 'Stack Overflow Bot');
    });

    context.subscriptions.push(disposable);
};
Example #19
0
	test('registerTextDocumentContentProvider, simple', function() {

		let registration = workspace.registerTextDocumentContentProvider('foo', {
			provideTextDocumentContent(uri) {
				return uri.toString();
			}
		});

		const uri = Uri.parse('foo://testing/virtual.js');
		return workspace.openTextDocument(uri).then(doc => {
			assert.equal(doc.getText(), uri.toString());
			assert.equal(doc.isDirty, false);
			assert.equal(doc.uri.toString(), uri.toString());
			registration.dispose();
		});
	});
Example #20
0
	test('api-command: vscode.previewHtml', async function () {

		let registration = workspace.registerTextDocumentContentProvider('speciale', {
			provideTextDocumentContent(uri) {
				return `content of URI <b>${uri.toString()}</b>`;
			}
		});

		let virtualDocumentUri = Uri.parse('speciale://authority/path');
		let title = 'A title';

		const success = await commands.executeCommand('vscode.previewHtml', virtualDocumentUri, ViewColumn.Three, title);
		assert.ok(success);
		registration.dispose();

	});
Example #21
0
	test('api-command: workbench.html.preview', function() {

		let registration = workspace.registerTextDocumentContentProvider('speciale', {
			provideTextDocumentContent(uri) {
				return `content of URI <b>${uri.toString()}</b>`;
			}
		});

		let virtualDocumentUri = Uri.parse('speciale://authority/path')

		return commands.executeCommand('vscode.previewHtml', virtualDocumentUri).then(success => {
			assert.ok(success);
			registration.dispose();
		});

	})
Example #22
0
	test('registerTextDocumentContentProvider, show virtual document', function() {

		let registration = workspace.registerTextDocumentContentProvider('foo', {
			provideTextDocumentContent(uri) {
				return 'I am virtual';
			}
		});

		return workspace.openTextDocument(Uri.parse('foo://something/path')).then(doc => {
			return window.showTextDocument(doc).then(editor => {

				assert.ok(editor.document === doc);
				assert.equal(editor.document.getText(), 'I am virtual');
				registration.dispose();
			})
		});
	});
Example #23
0
export function activate(context: vscode.ExtensionContext) {
    let previewUri = vscode.Uri.parse('html-preview://html-preview');
    
    class MyTextDocumentContentProvider implements vscode.TextDocumentContentProvider {
        
        public provideTextDocumentContent(uri: vscode.Uri): string {
            return this.displayHtml();
        }
        
        private displayHtml() {
            var renderer = new marked.Renderer();
 
            renderer.heading = function (text, level) {
            
                return '<h' + level + '>' + text + '</h' + level + '>';
            };

             let editor = vscode.window.activeTextEditor;
            if (editor.document.languageId === 'markdown') {
                let text = editor.document.getText();
                let htmlText = encode(marked(text, {renderer:renderer}));
                
                return htmlText; 
            }
            else {
                return null;
            }
            
            
        }
    }
    
    let provider = new MyTextDocumentContentProvider();
    let registration = vscode.workspace.registerTextDocumentContentProvider('html-preview', provider);

    let disposable = vscode.commands.registerCommand('extension.previewHtml', () => {
        return vscode.commands.executeCommand('vscode.previewHtml', previewUri, vscode.ViewColumn.Two).then((success) => {
        }, (reason) => {
            vscode.window.showErrorMessage(reason);
        });
	});

	context.subscriptions.push(disposable);
}
Example #24
0
	test('editor, onDidChangeTextEditorViewColumn (move editor group)', () => {

		let actualEvents: TextEditorViewColumnChangeEvent[] = [];

		let registration1 = workspace.registerTextDocumentContentProvider('bikes', {
			provideTextDocumentContent() {
				return 'mountainbiking,roadcycling';
			}
		});

		return Promise.all([
			workspace.openTextDocument(Uri.parse('bikes://testing/one')).then(doc => window.showTextDocument(doc, ViewColumn.One)),
			workspace.openTextDocument(Uri.parse('bikes://testing/two')).then(doc => window.showTextDocument(doc, ViewColumn.Two))
		]).then(editors => {

			let [, two] = editors;
			two.show();

			return new Promise(resolve => {

				let registration2 = window.onDidChangeTextEditorViewColumn(event => {
					actualEvents.push(event);

					if (actualEvents.length === 2) {
						registration2.dispose();
						resolve();
					}
				});

				// move active editor group left
				return commands.executeCommand('workbench.action.moveActiveEditorGroupLeft');

			}).then(() => {
				assert.equal(actualEvents.length, 2);

				for (let i = 0; i < actualEvents.length; i++) {
					const event = actualEvents[i];
					assert.equal(event.viewColumn, event.textEditor.viewColumn);
				}

				registration1.dispose();
			});
		});
	});
Example #25
0
	test('registerTextDocumentContentProvider, change event', function() {

		let callCount = 0;
		let listeners: Function[] = [];
		let registration = workspace.registerTextDocumentContentProvider('foo', {
			onDidChange(callback, thisArg, disposables) {
				let actual = thisArg ? callback.bind(thisArg) : callback;
				listeners.push(actual);
				let subscription = new Disposable(() => {
					const idx = listeners.indexOf(actual);
					listeners.splice(idx, 1);
				});
				if (Array.isArray(disposables)) {
					disposables.push(subscription);
				}
				return subscription;
			},
			provideTextDocumentContent(uri) {
				return 'call' + (callCount++);
			}
		});

		const uri = Uri.parse('foo://testing/path2');

		return workspace.openTextDocument(uri).then(doc => {

			assert.equal(callCount, 1);
			assert.equal(doc.getText(), 'call0');

			return new Promise((resolve, reject) => {

				workspace.onDidChangeTextDocument(event => {
					assert.ok(event.document === doc);
					assert.equal(event.document.getText(), 'call1');
					resolve();
				});

				listeners.forEach(l => l(doc.uri));

				registration.dispose();
			});
		});
	});
export function activate(context: ExtensionContext) {

    const contentProvider = new ContentProvider();

    // register content provider for scheme `references`
    const providerRegistration = workspace.registerTextDocumentContentProvider(ContentProvider.scheme, contentProvider);

    // register command that crafts an uri with the `references` scheme,
    // open the dynamic document, and shows it in the next editor
    const commandRegistration = commands.registerTextEditorCommand('editor.printReferences', editor => {
        const uri = encodeLocation(editor.document.uri, editor.selection.active);
        return workspace.openTextDocument(uri).then(doc => window.showTextDocument(doc, editor.viewColumn + 1));
    });

    context.subscriptions.push(
        contentProvider,
        commandRegistration,
        providerRegistration
    );
}
Example #27
0
	test('registerTextDocumentContentProvider, open/open document', function() {

		let callCount = 0;
		let registration = workspace.registerTextDocumentContentProvider('foo', {
			provideTextDocumentContent(uri) {
				callCount += 1;
				return 'I am virtual';
			}
		});

		const uri = Uri.parse('foo://testing/path');

		return Promise.all([workspace.openTextDocument(uri), workspace.openTextDocument(uri)]).then(docs => {
			let [first, second] = docs;
			assert.ok(first === second);
			assert.ok(workspace.textDocuments.some(doc => doc.uri.toString() === uri.toString()));
			assert.equal(callCount, 1);
			registration.dispose();
		});
	});
export function activate(context: vscode.ExtensionContext) {
    const id: string = '30E6F79F-8885-4955-91BB-3FA8ED71ECF8';
    const name: string = 'Escaped Html';
    const previewUri: vscode.Uri = htmlEsc.createPreviewUri(name, id);

    const provider = new htmlEsc.HtmlEscapeTextDocumentContentProvider();

    context.subscriptions.push(
        vscode.workspace.registerTextDocumentContentProvider(htmlEsc.HtmlEscapeTextDocumentContentProvider.scheme, provider));

    context.subscriptions.push(vscode.commands.registerCommand('extension.showHtmlEscape', async () => {
        let previewDocument = await vscode.workspace.openTextDocument(previewUri);
        let previewEditorShowOptions: vscode.TextDocumentShowOptions = {
            viewColumn: vscode.ViewColumn.Beside, 
            preview: true,
            preserveFocus: true,
            selection: new vscode.Selection(new vscode.Position(0, 0), new vscode.Position(0, 0))
        };

        await vscode.window.showTextDocument(previewDocument, previewEditorShowOptions);

        let activeTextEditor = vscode.window.activeTextEditor;
        if (activeTextEditor && activeTextEditor.document.uri.scheme != htmlEsc.HtmlEscapeTextDocumentContentProvider.scheme) {
            provider.show(previewUri, activeTextEditor.document.uri, activeTextEditor.selections);
        }
    }));

    vscode.window.onDidChangeActiveTextEditor(async activeTextEditor => {
        if (activeTextEditor && activeTextEditor.document.uri.scheme != htmlEsc.HtmlEscapeTextDocumentContentProvider.scheme) {
            provider.show(previewUri, activeTextEditor.document.uri, activeTextEditor.selections);
        }
    }, this, context.subscriptions);

    vscode.window.onDidChangeTextEditorSelection(async event => {
        let editor = event.textEditor;
        if (editor && editor.document.uri.scheme != htmlEsc.HtmlEscapeTextDocumentContentProvider.scheme) {
            provider.show(previewUri, editor.document.uri, event.selections);
        }
    }, this, context.subscriptions);
}
Example #29
0
export function activate(context: vscode.ExtensionContext) {
	context.subscriptions.push(vscode.workspace.registerTextDocumentContentProvider("debugmemory", new MemoryContentProvider()));
	context.subscriptions.push(vscode.commands.registerCommand("code-debug.examineMemoryLocation", examineMemory));
	context.subscriptions.push(vscode.commands.registerCommand("code-debug.getFileNameNoExt", () => {
		if (!vscode.window.activeTextEditor || !vscode.window.activeTextEditor.document || !vscode.window.activeTextEditor.document.fileName) {
			vscode.window.showErrorMessage("No editor with valid file name active");
			return;
		}
		const fileName = vscode.window.activeTextEditor.document.fileName;
		const ext = path.extname(fileName);
		return fileName.substr(0, fileName.length - ext.length);
	}));
	context.subscriptions.push(vscode.commands.registerCommand("code-debug.getFileBasenameNoExt", () => {
		if (!vscode.window.activeTextEditor || !vscode.window.activeTextEditor.document || !vscode.window.activeTextEditor.document.fileName) {
			vscode.window.showErrorMessage("No editor with valid file name active");
			return;
		}
		const fileName = path.basename(vscode.window.activeTextEditor.document.fileName);
		const ext = path.extname(fileName);
		return fileName.substr(0, fileName.length - ext.length);
	}));
}
Example #30
0
    let openfile = vscode.commands.registerCommand('svgviewer.openfile', async function (uri) {
        if (!(uri instanceof vscode.Uri)) {
            return;
        }
        let document = await vscode.workspace.openTextDocument(uri);
        if (checkNoSvg(document, false)) {
            vscode.window.showWarningMessage("Selected file is not an SVG document - no properties to preview.");
            return;
        }

        let fName = vscode.workspace.asRelativePath(document.fileName);
        let fileUriProvider = fileUriProviders.get(fName);
        if (fileUriProvider == undefined) {
            let fileUri = getSvgUri(uri);
            let fileProvider = new SvgFileContentProvider(context, fileUri, document.fileName);
            let fileRegistration = vscode.workspace.registerTextDocumentContentProvider('svg-preview', fileProvider);
            fileUriProvider = { uri: fileUri, provider: fileProvider, registration: fileRegistration };
            fileUriProviders.set(fName, fileUriProvider);
        } else {
            fileUriProvider.provider.update(fileUriProvider.uri);
        }
        return openPreview(fileUriProvider.uri, fName);
    });