test('addUniqueDiagnostic adds the diagnostic to the empty diagnostics', () => {
        const diagnostic: FileDiagnostic = {
            filePath: '/1',
            diagnostic: new Diagnostic(new Range(1, 2, 3, 4), 'Hello', undefined)
        };

        const diagnostics = languages.createDiagnosticCollection('rust');

        addUniqueDiagnostic(diagnostic, diagnostics);

        const fileDiagnostics = diagnostics.get(Uri.file('/1'));

        if (!fileDiagnostics) {
            assert.notEqual(fileDiagnostics, undefined);
        } else {
            assert.equal(fileDiagnostics.length, 1);
        }
    });
Example #2
0
	@command('git.openChange')
	async openChange(uri: Uri): Promise<void> {
		const scmResource = resolveGitResource(uri);

		if (scmResource) {
			return await this.open(scmResource);
		}

		if (uri.scheme === 'file') {
			const uriString = uri.toString();
			const resource = this.model.workingTreeGroup.resources.filter(r => r.uri.toString() === uriString)[0]
				|| this.model.indexGroup.resources.filter(r => r.uri.toString() === uriString)[0];

			if (resource) {
				return await this.open(resource);
			}
		}
	}
        it("should call update method of previewManager with correct parameters", sinon.test(function () {
            let checkExtensionTypeStub = this.stub(utilities, "checkExtensionType", function () {
                ExtensionConstants.EXTENSION_TYPE = ExtensionConstants.VSC_EXTENSION;
                return true;
            })

            let previewManagerStub = sinon.createStubInstance(dummyPreviewManager);

            previewManagerController = new PreviewManagerController(utilities, previewManagerStub, previewManagerStub);
            previewManagerController.onEvent();

            sinon.assert.calledOnce(checkExtensionTypeStub);
            expect(previewManagerController.previewManager).to.equal(previewManagerStub);
            sinon.assert.calledOnce(previewManagerStub.generatePreview);
            sinon.assert.calledOnce(previewManagerStub.update);
            sinon.assert.calledWith(previewManagerStub.update,vscode.Uri.parse(ExtensionConstants.PREVIEW_URI))
            
        }))
Example #4
0
export function createTempDocument(content?: string) {

    const uri = Uri.parse(`untitled:${__dirname}.${Math.random()}.tmp`);

    return workspace.openTextDocument(uri)
        .then(document => {
            return window.showTextDocument(document);
        })
        .then(() => {
            if (content) {
                window.activeTextEditor.edit(editBuilder => {
                    editBuilder.insert(new Position(0, 0), content);
                });
            }

            return window.activeTextEditor;
        });
}
Example #5
0
export async function setupWorkspace(
  config: IConfiguration = new Configuration(),
  fileExtension: string = ''
): Promise<any> {
  const filePath = await createRandomFile('', fileExtension);
  const doc = await vscode.workspace.openTextDocument(vscode.Uri.file(filePath));

  await vscode.window.showTextDocument(doc);

  Globals.mockConfiguration = config;
  reloadConfiguration();

  let activeTextEditor = vscode.window.activeTextEditor;
  assert.ok(activeTextEditor);

  activeTextEditor!.options.tabSize = config.tabstop;
  activeTextEditor!.options.insertSpaces = config.expandtab;
}
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);
}
export async function manageIncludes(uri: Uri, opened: boolean) {
  const key = uri.toString()
  if (opened) {
    const include = includes.get(key)
    if (isString(include)) return
    const server = fromUri(uri)
    const obj = await server.findAbapObject(uri)
    if (obj.type !== "PROG/I") includes.set(key, "")
    else {
      let main = ""
      try {
        main = await await server.activator.selectMain(obj)
      } finally {
        includes.set(key, main || "")
        // if(main)
      }
    }
  } else includes.delete(key)
}
Example #8
0
	it("Flutter: New Project can be invoked and creates trigger file", async () => {
		const showInputBox = sb.stub(vs.window, "showInputBox");
		showInputBox.resolves("my_test_flutter_proj");

		const showOpenDialog = sb.stub(vs.window, "showOpenDialog");
		const tempFolder = getRandomTempFolder();
		showOpenDialog.resolves([vs.Uri.file(tempFolder)]);

		// Intercept executeCommand for openFolder so we don't spawn a new instance of Code!
		const executeCommand = sb.stub(vs.commands, "executeCommand").callThrough();
		const openFolder = executeCommand.withArgs("vscode.openFolder", sinon.match.any).resolves();

		await vs.commands.executeCommand("flutter.createProject");

		assert.ok(showInputBox.calledOnce);
		assert.ok(showOpenDialog.calledOnce);
		assert.ok(openFolder.calledOnce);
		assert.ok(fs.existsSync(path.join(tempFolder, "my_test_flutter_proj", FLUTTER_CREATE_PROJECT_TRIGGER_FILE)));
	});
Example #9
0
export async function openOrCreateConfigFile(
	isTypeScriptProject: boolean,
	rootPath: string,
	config: TypeScriptServiceConfiguration
): Promise<vscode.TextEditor | null> {
	const configFile = vscode.Uri.file(path.join(rootPath, isTypeScriptProject ? 'tsconfig.json' : 'jsconfig.json'));
	const col = vscode.window.activeTextEditor ? vscode.window.activeTextEditor.viewColumn : undefined;
	try {
		const doc = await vscode.workspace.openTextDocument(configFile);
		return vscode.window.showTextDocument(doc, col);
	} catch {
		const doc = await vscode.workspace.openTextDocument(configFile.with({ scheme: 'untitled' }));
		const editor = await vscode.window.showTextDocument(doc, col);
		if (editor.document.getText().length === 0) {
			await editor.insertSnippet(inferredProjectConfigSnippet(config));
		}
		return editor;
	}
}
Example #10
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();
			});
		});
	});
function getIgnorePathForFile(
    filePath: string,
    ignorePath: string
): string | null {
    // Configuration `prettier.ignorePath` is set to `null`
    if (!ignorePath) {
        return null;
    }
    if (!existsSync(ignorePath)) {
        addToOutput(`Wrong prettier.ignorePath provided in your settings. The path (${ignorePath}) does not exist.`);
        return null;
    }
    if (workspace.workspaceFolders) {
        const folder = workspace.getWorkspaceFolder(Uri.file(filePath));
        return folder ? getPath(ignorePath, folder.uri.fsPath) : null;
    }

    return null;
}
Example #12
0
 launchDef.promise.then(() => {
     if (!Array.isArray(workspace.workspaceFolders) || workspace.workspaceFolders.length === 0) {
         throw new Error('Please open a workspace');
     }
     let workspaceFolder = workspace.getWorkspaceFolder(Uri.file(rootDirectory));
     if (!workspaceFolder) {
         workspaceFolder = workspace.workspaceFolders[0];
     }
     return debug.startDebugging(workspaceFolder, {
         "name": "Debug Unit Test",
         "type": "python",
         "request": "attach",
         "localRoot": rootDirectory,
         "remoteRoot": rootDirectory,
         "port": pythonSettings.unitTest.debugPort,
         "secret": "my_secret",
         "host": "localhost"
     });
 }).catch(reason => {
Example #13
0
export function openOrCreateConfigFile(
	isTypeScriptProject: boolean,
	rootPath: string
): Thenable<vscode.TextEditor | null> {
	const configFile = vscode.Uri.file(path.join(rootPath, isTypeScriptProject ? 'tsconfig.json' : 'jsconfig.json'));
	const col = vscode.window.activeTextEditor ? vscode.window.activeTextEditor.viewColumn : undefined;
	return vscode.workspace.openTextDocument(configFile)
		.then(doc => {
			return vscode.window.showTextDocument(doc, col);
		}, async () => {
			const doc = await vscode.workspace.openTextDocument(configFile.with({ scheme: 'untitled' }));
			const editor = await vscode.window.showTextDocument(doc, col);
			if (editor.document.getText().length === 0) {
				await editor.insertSnippet(emptyConfig);
				return editor;
			}
			return editor;
		});
}
Example #14
0
				jsonValidation.forEach(jv => {
					let {fileMatch, url} = jv;
					if (fileMatch && url) {
						if (url[0] === '.' && url[1] === '/') {
							url = Uri.file(path.join(extension.extensionPath, url)).toString();
						}
						if (fileMatch[0] === '%') {
							fileMatch = fileMatch.replace(/%APP_SETTINGS_HOME%/, '/User');
						} else if (fileMatch.charAt(0) !== '/' && !fileMatch.match(/\w+:\/\//)) {
							fileMatch = '/' + fileMatch;
						}
						let association = associations[fileMatch];
						if (!association) {
							association = [];
							associations[fileMatch] = association;
						}
						association.push(url);
					}
				});
 return new Promise((resolve, reject) => {
     let definition: vscode.Location | null = null;
     const fileUri: vscode.Uri = vscode.Uri.file(doc.fileName);
     const range: vscode.Range = doc.getWordRangeAtPosition(pos);
     const symbol: string = doc.getText(range);
     // console.log(`Providing definition for symbol '${symbol}'`);
     let possibleVarStart: vscode.Position = new vscode.Position(range.start.line, range.start.character - 1);
     let possibleVarRange: vscode.Range = new vscode.Range(possibleVarStart, range.end);
     let possibleVar: string = doc.getText(possibleVarRange);
     const lines: string[] = doc.getText().split("\n");
     if (varFirstChar.has(possibleVar.charAt(0))) {
         // console.log(`Variable detected: ${possibleVar}`);
         let currentRuleRange: vscode.Range = GetRuleRange(lines, pos);
         // console.log(`Curr rule range: ${currentRuleRange.start.line+1} -> ${currentRuleRange.end.line+1}`);
         for (let lineNo = currentRuleRange.start.line; lineNo < currentRuleRange.end.line; lineNo++) {
             let character: number = lines[lineNo].indexOf(`$${symbol} =`);
             if (character != -1) {
                 // console.log(`Found defintion of '${possibleVar}' on line ${lineNo + 1} at character ${character + 1}`);
                 // gotta add one because VSCode won't recognize the '$' as part of the symbol
                 let defPosition: vscode.Position = new vscode.Position(lineNo, character + 1);
                 definition = new vscode.Location(fileUri, defPosition);
                 break;
             }
         }
     }
     else {
         for (let lineNo = 0; lineNo < pos.line; lineNo++) {
             let character: number = lines[lineNo].indexOf(symbol);
             if (character != -1 && lines[lineNo].startsWith("rule")) {
                 // console.log(`Found ${symbol} on line ${lineNo} at character ${character}`);
                 let defPosition: vscode.Position = new vscode.Position(lineNo, character);
                 definition = new vscode.Location(fileUri, defPosition);
                 break;
             }
         }
     }
     if (definition != null) {
         resolve(definition);
     }
     else {
         reject();
     }
 });
  private async generateWorkflows(workflowType: string, filePath: Uri | undefined): Promise<void> {
    const workspaceDir: Uri = Uri.parse(getWorkspaceRoot());
    const dirPath: string = workspaceDir.fsPath + '/build/contracts/';

    if (filePath) {
      const fileName = path.basename(filePath.fsPath);
      const contractName = fileName.Remove(fileName.length - 4);
      const compiledContractPath = dirPath + contractName + '.json';
      let picks: QuickPickItem[];

      if (workflowType === 'Service') {
          picks = [
          { label: 'Logic App' },
          { label: 'Flow App' },
          { label: 'Azure Function' },
        ];
      } else {
        picks = [
          { label: 'Logic App' },
          { label: 'Flow App' },
        ];
      }

      const serviceTypeSelection: string = (await showQuickPick(picks, { })).label;
      const serviceType: int = this.getServiceTypeFromString(serviceTypeSelection);
      const contractAddress: string = await showInputBox({ value: 'contract address' });
      const [subscriptionItem, resourceGroupItem] = await this.selectSubscriptionAndResourceGroup();
      readJson(compiledContractPath, {encoding: 'utf8'},
        async (err2: Error, contents: any) => await this.handleContractJsonFile(
          err2,
          contents,
          dirPath,
          contractAddress,
          subscriptionItem,
          resourceGroupItem,
          workflowType,
          serviceType,
        ));
    } else {
      readdir(dirPath, (err: Error, files: string[]) =>
        this.iterateFilesInDirectory(err, files, dirPath, workflowType));
    }
  }
Example #17
0
export async function overviewCmdHandler(context: vscode.ExtensionContext) {
  if (overviewView) {
    overviewView.reveal();
    return;
  }

  overviewView = vscode.window.createWebviewPanel(
    'java.overview',
    'Java Overview',
    vscode.ViewColumn.One,
    {
      enableScripts: true,
      enableCommandUris: true,
      retainContextWhenHidden: true
    }
  );

  overviewView.iconPath = vscode.Uri.file(path.join(context.extensionPath, 'logo.lowres.png'));
  let buffer = await readFile(require.resolve('./assets/index.html'));
  overviewView.webview.html = buffer.toString();

  overviewView.onDidDispose(() => {
    overviewView = undefined;
  });

  const installedExtensions = vscode.extensions.all.map(ext => ext.id.toLowerCase());
  overviewView.webview.postMessage({
    command: 'hideInstalledExtensions',
    installedExtensions: installedExtensions
  });

  overviewView.webview.postMessage({
    command: 'setOverviewVisibility',
    visibility: context.globalState.get(KEY_SHOW_WHEN_USING_JAVA)
  });

  overviewView.webview.onDidReceiveMessage((e) => {
    if (e.command === 'setOverviewVisibility') {
      context.globalState.update(KEY_SHOW_WHEN_USING_JAVA, e.visibility);
    }
  });
}
    deserialize(input): DataProviderVSC {

        super.deserialize(input);
        if (input.name) {
            this.name = input.name;
        }
        if (input.displayName) {
            this.displayName = input.displayName;
        }
        if (input.keywords) {
            this.tags = input.keywords;
        }
        if (input.galleryBanner) {
            this.galleryBanner.color = input.galleryBanner.color;
            this.galleryBanner.theme = input.galleryBanner.theme;
        }
        if (input.icon) {
            let rootPath: string = vscode.workspace.rootPath;
            this.imagePath = vscode.Uri.file(`${rootPath}/${input.icon}`).toString();
        }
        if (input.license) {
            this.license = input.license;
        }
        if (input.repository) {
            if (input.repository.url) {
                this.repository = input.repository.url;
            }
        }
        if (input.homepage) {
            this.homepage = input.homepage;
        }
        if (input.bugs) {
            if (input.bugs.url) {
                this.bugs = input.bugs.url;
            }
        }
        if (input.preview) {
            this.preview = input.preview;
        }
        this.readMePath = "readme.md";
        return this;
    }
Example #19
0
		return this._server.makeRequest<V2.RunCodeActionResponse>(V2.RunCodeAction, req).then(response => {

			if (response && Array.isArray(response.Changes)) {

				let edit = new WorkspaceEdit();

				for (let change of response.Changes) {
					let uri = Uri.file(change.FileName);
					let edits: TextEdit[] = [];
					for (let textChange of change.Changes) {
						edits.push(TextEdit.replace(toRange2(textChange), textChange.NewText));
					}

					edit.set(uri, edits);
				}

				return workspace.applyEdit(edit);
			}

		}, (error) => {
 const exportKeys = vscode.commands.registerCommand('i18nTag.exportKeys', async (context) => {
     await readConfig()
     outputChannel.appendLine(`exporting keys from ${srcPath}...`)
     outputChannel.show(true)
     spin(true)
     try {
         const tmpl = await exportTranslationKeys({ rootPath: srcPath, filePath: '.', filter: filter, logger: logger, preprocessor: preprocessor, postprocessor: postprocessor, babylonConfig: babylonConfig })
         templatesJson = (typeof tmpl === 'object')?JSON.stringify(tmpl, null, indention || 2):tmpl
         const uri = vscode.Uri.parse('i18n-schema:templates.json')
         emitter.fire(uri)
         const file = await vscode.workspace.openTextDocument(uri)
         await vscode.window.showTextDocument(file, vscode.ViewColumn.Two, true)
         spin(false)
     } catch(err) {
         spin(false)
         await vscode.window.showErrorMessage(err)
         outputChannel.appendLine(err.message)
         outputChannel.show(true)
     }
 })
Example #21
0
export function activate(context: vsc.ExtensionContext) {
  if (vsc.workspace.rootPath) {
    let cp = path.resolve(vsc.workspace.rootPath, 'classpath.txt');
    scan(vsc.Uri.file(cp));

    let fsw = vsc.workspace.createFileSystemWatcher(cp);
    fsw.onDidCreate(scan);
    fsw.onDidChange(scan);
    fsw.onDidDelete(scan);
    context.subscriptions.push(fsw);

    context.subscriptions.push(vsc.languages.setLanguageConfiguration('properties', {
      wordPattern: /(-?\d*\.\d\w*)|([^\`\~\!\@\#\%\^\&\*\(\)\=\+\[\{\]\}\\\|\;\:\'\"\,\<\>\/\?\s]+)/g
    }));

    let server = new Server();
    context.subscriptions.push(vsc.languages.registerCompletionItemProvider(['properties'], server));
    context.subscriptions.push(vsc.languages.registerHoverProvider(['properties'], server));
  }
}
    private addReference(searchResult: any, results: vscode.Location[]): any {
        if (searchResult) {
            let bucket = new Array<any>();
            for (let index = 0; index < searchResult.length; index++) {
                let element = searchResult[index];
                let result = {"path": element.filename,
                    "line": element.line,
                    "description": element.name,
                    "label": element.filename
                };
                let colStr = element.character;
                let referenceResource = vscode.Uri.file(result.path);
                let range = new vscode.Range(
                                result.line, +colStr, result.line , +colStr + element.call.length
                            );
                    results.push(new vscode.Location(referenceResource, range));

            }
        }
    }
	function assertFormatter(content: string, expected: string, done) {
		vscode.workspace.openTextDocument(vscode.Uri.parse("untitled:/foo/new.js")).then(document => {
			vscode.window.showTextDocument(document).then(textEditor => {
				textEditor.edit(editBuilder => {
					var lastLineLength = document.lineAt(document.lineCount - 1).text.length;
					editBuilder.replace(new vscode.Range(new vscode.Position(0, 0), new vscode.Position(textEditor.document.lineCount - 1, lastLineLength)), content);
				}).then(() => {
					try {
						var result = myExtension.format(document, null, { insertSpaces: true, tabSize: 4 });
						assert.equal(result.length, 1);
						assert.equal(result[0].newText, expected);
						done();				
					} catch (e) {
						done(e);
					}

				}, err => done(err))
			}, err => done(err))
		}, err => done(err))
	}
Example #24
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();
		});
	});
Example #25
0
	@command('git.openFileFromUri')
	async openFileFromUri(uri?: Uri): Promise<void> {
		const resource = this.getSCMResource(uri);
		let uriToOpen: Uri | undefined;

		if (resource) {
			uriToOpen = resource.resourceUri;
		} else if (uri && uri.scheme === 'git') {
			const { path } = fromGitUri(uri);
			uriToOpen = Uri.file(path);
		} else if (uri && uri.scheme === 'file') {
			uriToOpen = uri;
		}

		if (!uriToOpen) {
			return;
		}

		return await commands.executeCommand<void>('vscode.open', uriToOpen);
	}
Example #26
0
 async reloadP(): Promise<string[]> {
     await this.start();
     const res = await this.ghci.sendCommand([
         ':set +c',
         `:load ${[... this.files.values()].map(x => `*${x}`).join(' ')}`
     ]);
     const modules = await this.ghci.sendCommand(':show modules');
     const mmap = new Map<string, string>();
     for (const line of modules) {
         const res = /^([^ ]+)\s+\( (.+), interpreted \)$/.exec(line);
         if (res) {
             mmap.set(vscode.Uri.file(res[2]).fsPath, res[1]);
         }
     }
     await this.ghci.sendCommand(`:module ${
         [... this.files]
             .filter(m => mmap.has(m))
             .map(m => `*${mmap.get(m)}`).join(' ')
     }`);
     return res;
 }
Example #27
0
	test('openTextDocument, untitled closes on save', function() {
		const path = join(workspace.rootPath, './newfile.txt');

		return workspace.openTextDocument(Uri.parse('untitled://' + path)).then(doc => {
			assert.equal(doc.uri.scheme, 'untitled');
			assert.ok(doc.isDirty);

			let closed: TextDocument;
			let d0 = workspace.onDidCloseTextDocument(e => closed = e);

			return doc.save().then(() => {
				assert.ok(closed === doc);
				assert.ok(!doc.isDirty);
				assert.ok(fs.existsSync(path));

				d0.dispose();

				return deleteFile(Uri.file(join(workspace.rootPath, './newfile.txt')));
			});
		});
	});
    test("Check provider", async () => {
        // Open a C++ file to start the language server.
        let path: string = vscode.workspace.workspaceFolders[0].uri.fsPath + "/main.cpp";
        let uri: vscode.Uri = vscode.Uri.file(path);

        let testHook: apit.CppToolsTestHook = cpptools.getTestHook();
        let testResult: any = new Promise<void>((resolve, reject) => {
            disposables.push(testHook.StatusChanged(status => {
                if (status === apit.Status.IntelliSenseReady) {
                    let expected: api.SourceFileConfigurationItem[] = [ {uri: uri.toString(), configuration: defaultConfig} ];
                    assert.deepEqual(lastResult, expected);
                    resolve();
                }
            }));
            setTimeout(() => { reject(new Error("timeout")); }, 2500);
        });
        disposables.push(testHook);

        await vscode.workspace.openTextDocument(path);
        await testResult;
    });
Example #29
0
    static getFormattedPath(
        fileNameOrUri: string | Uri,
        options: { relativeTo?: string; separator?: string; suffix?: string } = {}
    ): string {
        const { relativeTo, separator = Strings.pad(GlyphChars.Dot, 2, 2), suffix = emptyStr } = options;

        let fileName: string;
        if (fileNameOrUri instanceof Uri) {
            if (fileNameOrUri instanceof GitUri) return fileNameOrUri.getFormattedPath(options);

            fileName = fileNameOrUri.fsPath;
        }
        else {
            fileName = fileNameOrUri;
        }

        const directory = GitUri.getDirectory(fileName, relativeTo);
        return !directory
            ? `${paths.basename(fileName)}${suffix}`
            : `${paths.basename(fileName)}${suffix}${separator}${directory}`;
    }
Example #30
0
	context.subscriptions.push(vscode.commands.registerCommand('_markdown.openDocumentLink', (args: OpenDocumentLinkArgs) => {
		const tryRevealLine = (editor: vscode.TextEditor) => {
			if (editor && args.fragment) {
				const toc = new TableOfContentsProvider(engine, editor.document);
				const line = toc.lookup(args.fragment);
				if (!isNaN(line)) {
					return editor.revealRange(
						new vscode.Range(line, 0, line, 0),
						vscode.TextEditorRevealType.AtTop);
				}
			}
		};
		if (vscode.window.activeTextEditor && isMarkdownFile(vscode.window.activeTextEditor.document) && vscode.window.activeTextEditor.document.uri.fsPath === args.path) {
			return tryRevealLine(vscode.window.activeTextEditor);
		} else {
			const resource = vscode.Uri.file(args.path);
			vscode.workspace.openTextDocument(resource)
				.then(vscode.window.showTextDocument)
				.then(tryRevealLine, _ => vscode.commands.executeCommand('vscode.open', resource));
		}
	}));