vscode#Position TypeScript Examples

The following examples show how to use vscode#Position. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: decoration-utils.ts    From vscode-code-review with MIT License 7 votes vote down vote up
/**
   * Highlight a matching review comment with an icon next to the start of the selection on the right
   *
   * @param csvEntries The selection to highlight
   * @param editor The editor to work on
   * @return all highlighting decorations
   */
  commentIconDecoration(csvEntries: CsvEntry[], editor: TextEditor): void {
    const decorationOptions: DecorationOptions[] = [];

    // build decoration options for each comment block
    csvEntries.forEach((entry) => {
      // iterate over multi-selections
      rangesFromStringDefinition(entry.lines).forEach((range: Range) => {
        decorationOptions.push({
          range: new Range(
            new Position(range.start.line, EDITOR_MAX_LETTER),
            new Position(range.start.line, EDITOR_MAX_LETTER),
          ),
        });
      });
    });
    editor.setDecorations(this.commentDecorationType, decorationOptions);
  }
Example #2
Source File: text-utils.ts    From vscode-stories with MIT License 7 votes vote down vote up
insertTextChunk = (
  textChunks: string[],
  position: Position,
  textToInsert: string
) => {
  const parts = textToInsert.split("\n");
  const text = textChunks[position.line] || "";
  if (parts.length === 1) {
    textChunks[position.line] =
      text.slice(0, position.character) +
      textToInsert +
      text.slice(position.character + 1);
    return;
  }

  // console.log(textChunks, position, textToInsert);
  // console.log(
  //   textChunks.slice(0, position.line - 2),
  //   text.slice(0, position.character) + parts[0],
  //   parts.slice(1, parts.length - 1),
  //   parts[parts.length - 1] + text.slice(position.character + 1),
  //   textChunks.slice(position.line + 1)
  // );

  textChunks.splice(
    0,
    textChunks.length,
    ...textChunks.slice(0, position.line - 2),
    text.slice(0, position.character) + parts[0],
    ...parts.slice(1, parts.length - 1),
    parts[parts.length - 1] + text.slice(position.character),
    ...textChunks.slice(position.line + 1)
  );
  // console.log(textChunks);
}
Example #3
Source File: DoComment.ts    From vscode-alxmldocumentation with MIT License 6 votes vote down vote up
/**
     * Write XML Documentation string to current editor.
     */
    public async WriteDocString() {
        // Analyze current AL Object.
        let alObject: ALObject | null = await ALSyntaxUtil.GetALObject(this.activeEditor.document);
        if ((alObject === null) || (alObject === undefined)) {
            return;
        }

        let docString: string = '';

        const activeLineNo: number = this.vsCodeApi.GetActiveLine();
        if (activeLineNo < alObject.LineNo) {
            // use object definition
            docString = ALDocCommentUtil.GetObjectDocumentation(alObject);
        } else {
            // find procedure
            let alProcedure: ALProcedure | undefined = alObject.Procedures?.find(alProcedure => (alProcedure.LineNo > activeLineNo));
            if ((!alProcedure) || (alProcedure.ALDocumentation.Exists)) {
                return;
            }
            docString = ALDocCommentUtil.GetProcedureDocumentation(alProcedure);
        }

        docString = docString.replace('///',''); // delete leading '///'.

        const position: Position = this.vsCodeApi.GetActivePosition();
        this.activeEditor.insertSnippet(new SnippetString(docString), this.vsCodeApi.ShiftPositionChar(position, 1));
    }
Example #4
Source File: ahkHoverProvider.ts    From vscode-autohotkey with MIT License 6 votes vote down vote up
public async provideHover(document: TextDocument, position: Position, token: CancellationToken) {

        const context = this.buildContext(document, position)

        const snippetHover = this.tryGetSnippetHover(context)
        if (snippetHover) {
            return snippetHover;
        }

        const method = await Parser.getMethodByName(document, context.word)
        if (method) {
            const markdonw = new MarkdownString("", true).appendCodeblock(method.full)
            if (method.comment) {
                markdonw.appendText(method.comment)
            }
            return new Hover(markdonw)
        }

        return null
    }
Example #5
Source File: element-completion-item-povider.ts    From element-ui-helper with MIT License 6 votes vote down vote up
/**
   * 匹配标签
   * @param reg 匹配模式
   * @param txt 匹配文本
   * @param line 当前行
   */
  matchTag(reg: RegExp, txt: string, line: number): TagObject | string | undefined {
    let match: RegExpExecArray | null
    let arr: TagObject[] = []

    if (/<\/?[-\w]+[^<>]*>[\s\w]*<?\s*[\w-]*$/.test(txt) || (this._position.line === line && (/^\s*[^<]+\s*>[^</>]*$/.test(txt) || /[^<>]*<$/.test(txt[txt.length - 1])))) {
      return 'break'
    }
    while ((match = reg.exec(txt))) {
      arr.push({
        text: match[1],
        offset: this._document.offsetAt(new Position(line, match.index))
      })
    }
    return arr.pop()
  }
Example #6
Source File: spProviders.ts    From sourcepawn-vscode with MIT License 6 votes vote down vote up
public async provideReferences(
    document: TextDocument,
    position: Position,
    context: ReferenceContext,
    token: CancellationToken
  ): Promise<Location[]> {
    return referencesProvider(
      this.itemsRepository,
      position,
      document,
      context,
      token
    );
  }
Example #7
Source File: lexDefinition.ts    From yash with MIT License 6 votes vote down vote up
export function doLEXFindDefinition(document: TextDocument, position: Position, lexDocument: LexDocument): Definition | null {
    const offset = document.offsetAt(position);
    const node = lexDocument.getEmbeddedCode(offset);
    if (node) {
        return null;
    }

    const word = document.getText(document.getWordRangeAtPosition(position));
    var symbol: ISymbol | undefined = lexDocument.defines[word] || lexDocument.states[word];
    let location: Location | null = null;
    if (symbol) {
        location = new Location(document.uri, new Range(document.positionAt(symbol.definition[0]), document.positionAt(symbol.definition[1])));
    }
    return location;
}
Example #8
Source File: formatting.ts    From twee3-language-tools with MIT License 6 votes vote down vote up
function getContext(editor: TextEditor, cursorPos: Position, startPattern: string, endPattern: string): string {
    let startPositionCharacter = cursorPos.character - startPattern.length;
    let endPositionCharacter = cursorPos.character + endPattern.length;

    if (startPositionCharacter < 0) {
        startPositionCharacter = 0;
    }

    let leftText = editor.document.getText(new Range(cursorPos.line, startPositionCharacter, cursorPos.line, cursorPos.character));
    let rightText = editor.document.getText(new Range(cursorPos.line, cursorPos.character, cursorPos.line, endPositionCharacter));

    if (rightText === endPattern) {
        if (leftText === startPattern) {
            return `${startPattern}|${endPattern}`;
        } else {
            return `${startPattern}text|${endPattern}`;
        }
    }
    return '|';
}
Example #9
Source File: editor-utils.ts    From vscode-code-review with MIT License 6 votes vote down vote up
clearSelection = (editor: TextEditor): void => {
  if (hasSelection(editor)) {
    editor.selections = [new Selection(new Position(0, 0), new Position(0, 0))];
  }
}
Example #10
Source File: counterExamplesView.ts    From ide-vscode with MIT License 6 votes vote down vote up
private static createDecorator(counterExample: ICounterExampleItem): DecorationOptions {
    const contentText = Object.entries(counterExample.variables)
      .map(([ name, value ]) => `${name} = ${value}`)
      .join(' ');
    // TODO earlier versions showed a warning that there are references present.
    const line = counterExample.position.line;
    return {
      range: new Range(
        new Position(line, counterExample.position.character + 1),
        new Position(line, Number.MAX_VALUE)
      ),
      renderOptions: {
        after: { contentText }
      }
    };
  }
Example #11
Source File: WSUtilsV2.ts    From dendron with GNU Affero General Public License v3.0 6 votes vote down vote up
async trySelectRevealNonNoteAnchor(
    editor: TextEditor,
    anchor: DNoteAnchorBasic
  ): Promise<void> {
    let position: Position | undefined;
    switch (anchor.type) {
      case "line":
        // Line anchors are direct line numbers from the start
        position = new Position(anchor.line - 1 /* line 1 is index 0 */, 0);
        break;
      case "block":
        // We don't parse non note files for anchors, so read the document and find where the anchor is
        position = editor?.document.positionAt(
          editor?.document.getText().indexOf(AnchorUtils.anchor2string(anchor))
        );
        break;
      default:
        // not supported for non-note files
        position = undefined;
    }
    if (position) {
      // if we did find the anchor, then select and scroll to it
      editor.selection = new Selection(position, position);
      editor.revealRange(editor.selection);
    }
  }
Example #12
Source File: gopExtraInfo.ts    From vscode-goplus with Apache License 2.0 6 votes vote down vote up
public provideHover(document: TextDocument, position: Position, token: CancellationToken): Thenable<Hover> {
		if (!this.goPlusConfig) {
			this.goPlusConfig = getGoPlusConfig(document.uri);
		}
		let goPlusConfig = this.goPlusConfig;

		// Temporary fix to fall back to godoc if guru is the set docsTool
		if (goPlusConfig['docsTool'] === 'guru') {
			goPlusConfig = Object.assign({}, goPlusConfig, { docsTool: 'godoc' });
		}
		return definitionLocation(document, position, goPlusConfig, true, token).then(
			(definitionInfo) => {
				if (definitionInfo == null) {
					return null;
				}
				const lines = definitionInfo.declarationlines
					.filter((line) => line !== '')
					.map((line) => line.replace(/\t/g, '    '));
				let text;
				text = lines.join('\n').replace(/\n+$/, '');
				const hoverTexts = new vscode.MarkdownString();
				hoverTexts.appendCodeblock(text, 'go');
				if (definitionInfo.doc != null) {
					hoverTexts.appendMarkdown(definitionInfo.doc);
				}
				const hover = new Hover(hoverTexts);
				return hover;
			},
			() => {
				return null;
			}
		);
	}
Example #13
Source File: CodeLinkFeature.ts    From vscode-drawio with GNU General Public License v3.0 6 votes vote down vote up
public serialize(relativeTo: Uri): Data {
		function toPosition(pos: Position): PositionData {
			return {
				col: pos.character,
				line: pos.line,
			};
		}

		let rangeObj = {};
		if (this.range) {
			rangeObj = {
				start: toPosition(this.range.start),
				end: toPosition(this.range.end),
			};
		} else if (this.symbol) {
			rangeObj = {
				symbol: this.symbol,
			};
		}

		if (this.uri) {
			return <Data>{
				path: path
					.relative(relativeTo.fsPath, this.uri.fsPath)
					.replace(/\\/g, "/"),
				...rangeObj,
			};
		} else {
			return <Data>{
				...rangeObj,
			};
		}
	}
Example #14
Source File: macroAutocompletionProvider.ts    From vscode-dbt-power-user with MIT License 6 votes vote down vote up
provideCompletionItems(
    document: TextDocument,
    position: Position,
    token: CancellationToken,
    context: CompletionContext
  ): ProviderResult<CompletionItem[] | CompletionList<CompletionItem>> {
    const range = document.getWordRangeAtPosition(position);
    if (range && isEnclosedWithinCodeBlock(document, range)) {
      return this.getAutoCompleteItems(document.uri);
    }
    return undefined;
  }
Example #15
Source File: new-trongate-module.command.ts    From trongate-vscode with MIT License 6 votes vote down vote up
// Helper Function to open the controller file and place curosr at good position
function openEditorAndPutCursorAtGoodPosition(
  targetDirectory,
  moduleName,
  isViewTemplate
) {
  const validatedModuleName = validateModuleName(moduleName);
  const upperModuleName = makeFirstLetterGoUpper(validatedModuleName);
  const controllerLocation = `${targetDirectory}/${validatedModuleName}/controllers/${upperModuleName}.php`;
  var setting: vscode.Uri = Uri.file(controllerLocation);
  setting = setting.fsPath;
  workspace.openTextDocument(setting).then((document) =>
    window.showTextDocument(document).then((e) => {
      e.selections =
        isViewTemplate === "no"
          ? [new Selection(new Position(0, 5), new Position(0, 5))]
          : [new Selection(new Position(0, 5), new Position(0, 5))];
    })
  );
}
Example #16
Source File: AbbreviationHoverProvider.ts    From vscode-lean4 with Apache License 2.0 6 votes vote down vote up
provideHover(document: TextDocument, pos: Position): Hover | undefined {
		const context = document.lineAt(pos.line).text.substr(pos.character);
		const symbolsAtCursor = this.abbreviations.findSymbolsIn(context);
		const allAbbrevs = symbolsAtCursor.map((symbol) => ({
			symbol,
			abbrevs: this.abbreviations.getAllAbbreviations(symbol),
		}));

		if (
			allAbbrevs.length === 0 ||
			allAbbrevs.every((a) => a.abbrevs.length === 0)
		) {
			return undefined;
		}

		const leader = this.config.abbreviationCharacter.get();

		const hoverMarkdown = allAbbrevs
			.map(
				({ symbol, abbrevs }) =>
					`Type ${symbol} using ${abbrevs
						.map((a) => '`' + leader + a + '`')
						.join(' or ')}`
			)
			.join('\n\n');

		const maxSymbolLength = Math.max(
			...allAbbrevs.map((a) => a.symbol.length)
		);
		const hoverRange = new Range(pos, pos.translate(0, maxSymbolLength));

		return new Hover(hoverMarkdown, hoverRange);
	}
Example #17
Source File: commands.ts    From vscode-cadence with Apache License 2.0 6 votes vote down vote up
refreshCodeLenses = (): void => {
  window.visibleTextEditors.forEach((editor) => {
    if (editor.document.lineCount !== 0) {
      return
    }
    // NOTE: We add a space to the end of the last line to force
    // Codelens to refresh.
    const lineCount = editor.document.lineCount
    const lastLine = editor.document.lineAt(lineCount - 1)
    editor.edit((edit) => {
      if (lastLine.isEmptyOrWhitespace) {
        edit.insert(new Position(lineCount - 1, 0), ' ')
        edit.delete(new Range(lineCount - 1, 0, lineCount - 1, 1000))
      } else {
        edit.insert(new Position(lineCount - 1, 1000), '\n')
      }
    }).then(() => {}, () => {})
  })
}
Example #18
Source File: externalUtils.ts    From joplin-utils with MIT License 6 votes vote down vote up
mathEnvCheck = (doc: TextDocument, pos: Position): string => {
  const lineTextBefore = doc.lineAt(pos.line).text.substring(0, pos.character)
  const lineTextAfter = doc.lineAt(pos.line).text.substring(pos.character)

  if (
    /(^|[^\$])\$(|[^ \$].*)\\\w*$/.test(lineTextBefore) &&
    lineTextAfter.includes('$')
  ) {
    // Inline math
    return 'inline'
  } else {
    const textBefore = doc.getText(new Range(new Position(0, 0), pos))
    const textAfter = doc.getText().substr(doc.offsetAt(pos))
    let matches
    if (
      (matches = textBefore.match(/\$\$/g)) !== null &&
      matches.length % 2 !== 0 &&
      textAfter.includes('$$')
    ) {
      // $$ ... $$
      return 'display'
    } else {
      return ''
    }
  }
}
Example #19
Source File: hoverProvider.ts    From vscode-stripe with MIT License 6 votes vote down vote up
async provideHover(
    document: TextDocument,
    position: Position,
    token: CancellationToken,
  ): Promise<Hover | undefined> {
    const languageClient: LanguageClient | undefined = await getActiveJavaLanguageClient();

    if (!languageClient) {
      return undefined;
    }

    if (javaServerMode === ServerMode.STANDARD) {
      if (!this.delegateProvider) {
        this.delegateProvider = createClientHoverProvider(languageClient);
      }
      return this.delegateProvider.provideHover(document, position, token);
    } else {
      const params = {
        textDocument: languageClient.code2ProtocolConverter.asTextDocumentIdentifier(document),
        position: languageClient.code2ProtocolConverter.asPosition(position),
      };
      const hoverResponse = await languageClient.sendRequest(HoverRequest.type, params, token);
      return languageClient.protocol2CodeConverter.asHover(hoverResponse);
    }
  }
Example #20
Source File: ReferenceRenameProvider.ts    From memo with MIT License 6 votes vote down vote up
public async prepareRename(
    document: TextDocument,
    position: Position,
  ): Promise<Range | { range: Range; placeholder: string }> {
    if (document.isDirty) {
      throw new Error('Rename is not available for unsaved files. Please save your changes first.');
    }

    const refAtPos = getReferenceAtPosition(document, position);

    if (refAtPos) {
      const { range, ref } = refAtPos;

      const unknownUris = containsUnknownExt(ref) ? await findFilesByExts([extractExt(ref)]) : [];

      const augmentedUris = unknownUris.length
        ? sortPaths([...cache.getWorkspaceCache().allUris, ...unknownUris], {
            pathKey: 'path',
            shallowFirst: true,
          })
        : cache.getWorkspaceCache().allUris;

      if (!findUriByRef(augmentedUris, ref)) {
        throw new Error(
          'Rename is not available for nonexistent links. Create file first by clicking on the link.',
        );
      }

      return new Range(
        new Position(range.start.line, range.start.character + openingBracketsLength),
        new Position(range.start.line, range.start.character + openingBracketsLength + ref.length),
      );
    }

    throw new Error('Rename is not available. Please try when focused on the link.');
  }
Example #21
Source File: createSimilarTask.ts    From vscode-todo-md with MIT License 6 votes vote down vote up
export async function createSimilarTask(editor: TextEditor) {
	// Create a task with all the tags, projects and contexts of another task
	const selection = editor.selection;
	const task = getTaskAtLineExtension(selection.start.line);
	if (!task) {
		return;
	}
	const line = editor.document.lineAt(task.lineNumber);
	const edit = new WorkspaceEdit();

	const tagsAsString = task.tags.map(tag => ` #${tag}`).join('');
	const projectsAsString = task.projects.map(project => `+${project}`).join(' ');
	const contextsAsString = task.contexts.map(context => `@${context}`).join(' ');
	let newTaskAsString = tagsAsString;
	newTaskAsString += projectsAsString ? ` ${projectsAsString}` : '';
	newTaskAsString += contextsAsString ? ` ${contextsAsString}` : '';
	edit.insert(editor.document.uri, new Position(line.rangeIncludingLineBreak.end.line, line.rangeIncludingLineBreak.end.character), `${newTaskAsString}\n`);

	await applyEdit(edit, editor.document);

	editor.selection = new Selection(line.lineNumber + 1, 0, line.lineNumber + 1, 0);
}
Example #22
Source File: client.ts    From vala-vscode with MIT License 6 votes vote down vote up
peekSymbol(_editor: TextEditor, _edit: TextEditorEdit, lspCurrentLocation: lsp.Location, lspTargetLocation: lsp.Location): void {
        let currentLocation = new Location(
            Uri.parse(lspCurrentLocation.uri),
            new Range(
                new Position(lspCurrentLocation.range.start.line, lspCurrentLocation.range.start.character),
                new Position(lspCurrentLocation.range.end.line, lspCurrentLocation.range.end.character)
            )
        );
        let targetLocation = new Location(
            Uri.parse(lspTargetLocation.uri),
            new Range(
                new Position(lspTargetLocation.range.start.line, lspTargetLocation.range.start.character),
                new Position(lspTargetLocation.range.end.line, lspTargetLocation.range.end.character)
            )
        );

        commands.executeCommand(
            'editor.action.peekLocations',
            currentLocation.uri, // anchor uri and position
            currentLocation.range.end,
            [targetLocation], // results (vscode.Location[])
            'peek', // mode ('peek' | 'gotoAndPeek' | 'goto')
            'Nothing found' // <- message
        );
    }
Example #23
Source File: NextObjectIdCompletionItem.ts    From al-objid with MIT License 6 votes vote down vote up
constructor(
        type: string,
        objectId: NextObjectIdInfo,
        app: ALApp,
        position: Position,
        uri: Uri,
        nextIdContext: NextIdContext,
        range?: NinjaALRange
    ) {
        super(`${objectId.id}${nextIdContext.injectSemicolon ? ";" : ""}`, CompletionItemKind.Constant);

        this._injectSemicolon = nextIdContext.injectSemicolon;
        this._range = range;

        this.sortText = nextIdContext.additional ? `0.${nextIdContext.additional.ordinal / 1000}` : "0";
        this.command = this.getCompletionCommand(position, uri, type, app, objectId);
        this.documentation = this.getCompletionDocumentation(type, objectId);
        this.insertText = `${objectId.id}${this._injectSemicolon ? ";" : ""}`;
        this.detail = "AL Object ID Ninja";
        this.label = range && range.description ? `${objectId.id} (${range.description})` : this.insertText;
        this.kind = CompletionItemKind.Constant;
    }
Example #24
Source File: DoComment.ts    From vscode-alxmldocumentation with MIT License 5 votes vote down vote up
/**
     * Do comment on current event.
     * @param activeEditor TextEditor object.
     * @param event TextDocumentContentChangeEvent object.
     */
    public async DoComment(activeEditor: TextEditor, event: TextDocumentContentChangeEvent) {
        this.event = event;
        this.vsCodeApi = new VSCodeApi(activeEditor);
        this.activeEditor = activeEditor;

        if ((this.event === undefined) || (this.event === null) || (this.activeEditor === undefined) || (this.activeEditor === null)) {
            return;
        }

        // if action comes from snippet an additional '/// ' is included 
        var doubleDocCommentIndex = this.vsCodeApi.ReadLineAtCurrent().indexOf('/// /// ');
        if (doubleDocCommentIndex !== -1) {
            const position: Position = this.vsCodeApi.GetPosition(this.vsCodeApi.GetActiveLine(), doubleDocCommentIndex);
            const anchor: Position = this.vsCodeApi.GetPosition(position.line, position.character + 4);
            const replaceSelection = this.vsCodeApi.GetSelectionByPosition(anchor, position);
            this.activeEditor.edit((editBuilder) => {
                editBuilder.replace(replaceSelection, '');
            });
        }

        // If we're not we in a XML documentation line
        if (!(this.vsCodeApi.ReadLine(this.vsCodeApi.GetActiveLine()).trim().startsWith('///'))) {
            if (this.event.text !== '/') {
                return;
            }
        }

        if (!this.IsDoCommentTrigger()) {
            return;
        }

        if (this.isEnterKey) {            
            var indent = StringUtil.GetIndentSpaces(this.vsCodeApi.ReadLine(this.vsCodeApi.GetActiveLine()).indexOf('///'));

            const position: Position = this.vsCodeApi.GetActivePosition();
            const anchor: Position = this.vsCodeApi.GetPosition(this.vsCodeApi.GetNextLine(), indent.length);
            const replaceSelection = this.vsCodeApi.GetSelectionByPosition(anchor, position);
            this.activeEditor.edit((editBuilder) => {
                editBuilder.replace(replaceSelection, `\n${indent}/// `);
            });

            return;
        }

        if (this.vsCodeApi.ReadLine(this.vsCodeApi.GetNextLine()).trim().startsWith('///')) {
            return;
        }
            
        if (!Configuration.DirectDocumentationIsEnabled(this.activeEditor.document.uri)) {
            return;
        }
        await this.WriteDocString();
    }