vscode#ProviderResult TypeScript Examples

The following examples show how to use vscode#ProviderResult. 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: EngineNoteProvider.ts    From dendron with GNU Affero General Public License v3.0 6 votes vote down vote up
getParent(id: NoteProps): ProviderResult<NoteProps> {
    try {
      const { engine: client } = ExtensionProvider.getDWorkspace();

      const maybeParent = client.notes[id.parent || ""];
      return maybeParent || null;
    } catch (error) {
      Sentry.captureException(error);
      throw error;
    }
  }
Example #2
Source File: DecorationsProvider.ts    From al-objid with MIT License 6 votes vote down vote up
provideFileDecoration(uri: Uri): ProviderResult<FileDecoration> {
        if (uri.scheme !== "ninja") {
            return;
        }

        const map = this._decorations[uri.authority];
        if (!map) {
            return;
        }

        const decoration = map[uri.path];
        if (!decoration) {
            return;
        }

        return {
            ...decoration,
            propagate: false,
            color: new ThemeColor(SeverityColors[`${decoration.severity}`]),
        };
    }
Example #3
Source File: fileDecorator.ts    From vscode-swissknife with MIT License 6 votes vote down vote up
public provideFileDecoration(uri: Uri): ProviderResult<FileDecoration> {
    const workspace = workspacePathForUri(uri)
    const decoratorsForWorkspace = this.decoratedFilesForWorkspace(workspace)

    const decorator = decoratorsForWorkspace.find(f => f.file === relativePathForUri(uri))

    if (decorator)
      //color: new vscode.ThemeColor("button.background"),
      return { badge: decorator.decorator }
  }
Example #4
Source File: librarynote.ts    From vscode-lean4 with Apache License 2.0 6 votes vote down vote up
provideDocumentLinks(document: TextDocument): ProviderResult<DocumentLink[]> {
        const links: DocumentLink[] = [];
        for (const m of document.getText().matchAll(seeNoteRegex)) {
            const link = new DocumentLink(new Range(
                document.positionAt(m.index), document.positionAt(m.index + m[0].length)));
            link.tooltip = m[1];
            links.push(link);
        }
        return links;
    }
Example #5
Source File: modelDefinitionProvider.ts    From vscode-dbt-power-user with MIT License 6 votes vote down vote up
provideDefinition(
    document: TextDocument,
    position: Position,
    token: CancellationToken
  ): ProviderResult<Definition | DefinitionLink[]> {
    return new Promise((resolve, reject) => {
      const hover = document.getText(document.getWordRangeAtPosition(position));
      const word = document.getText(
        document.getWordRangeAtPosition(
          position,
          ModelDefinitionProvider.IS_REF
        )
      );
      if (word !== undefined && hover !== "ref") {
        const dbtModel = word.match(ModelDefinitionProvider.GET_DBT_MODEL);
        if (dbtModel && dbtModel.length === 1) {
          const definition = this.getDefinitionFor(dbtModel[0], document.uri);
          resolve(definition);
          return;
        }
      }
      reject();
    });
  }
Example #6
Source File: macroDefinitionProvider.ts    From vscode-dbt-power-user with MIT License 6 votes vote down vote up
provideDefinition(
    document: TextDocument,
    position: Position
  ): ProviderResult<Definition | DefinitionLink[]> {
    return new Promise((resolve, reject) => {
      const textLine = document.lineAt(position).text;
      const range = document.getWordRangeAtPosition(
        position,
        MacroDefinitionProvider.IS_MACRO
      );
      const word = document.getText(range);
      if (
        range &&
        textLine[range.end.character] === "(" &&
        isEnclosedWithinCodeBlock(document, range)
      ) {
        const packageName = this.dbtProjectContainer.getPackageName(
          document.uri
        );

        const macroName =
          packageName !== undefined && !word.includes(".")
            ? `${packageName}.${word}`
            : word;

        const definition = this.getMacroDefinition(macroName, document.uri);
        if (definition !== undefined) {
          resolve(definition);
          return;
        }
      }
      reject();
    });
  }
Example #7
Source File: sourceAutocompletionProvider.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 linePrefix = document
      .lineAt(position)
      .text.substr(0, position.character);
    if (!isEnclosedWithinCodeBlock(document, position)) {
      return undefined;
    }
    const projectRootpath = this.dbtProjectContainer.getProjectRootpath(
      document.uri
    );
    if (projectRootpath === undefined) {
      return;
    }

    if (linePrefix.match(SourceAutocompletionProvider.ENDS_WITH_SOURCE)) {
      return this.showSourceNameAutocompletionItems(projectRootpath);
    }

    if (
      linePrefix.match(SourceAutocompletionProvider.GET_SOURCE_NAME) &&
      linePrefix.includes("source")
    ) {
      return this.showTableNameAutocompletionItems(linePrefix, projectRootpath);
    }
    return undefined;
  }
Example #8
Source File: modelAutocompletionProvider.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 linePrefix = document
      .lineAt(position)
      .text.substr(0, position.character);
    if (
      linePrefix.match(ModelAutocompletionProvider.ENDS_WITH_REF) &&
      isEnclosedWithinCodeBlock(document, position)
    ) {
      return this.getAutoCompleteItems(document.uri);
    }

    return undefined;
  }
Example #9
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 #10
Source File: extension.ts    From vscode-riscv-venus with MIT License 6 votes vote down vote up
createDebugAdapterDescriptor(session: vscode.DebugSession, executable: vscode.DebugAdapterExecutable | undefined): vscode.ProviderResult<vscode.DebugAdapterDescriptor> {

		if (!this.server) {
			// start listening on a random port
			this.server = Net.createServer(socket => {
				const session = new VenusDebugSession();
				session.setRunAsServer(true);
				session.start(<NodeJS.ReadableStream>socket, socket);
			}).listen(0);
		}

		// make VS Code connect to debug server
		return new vscode.DebugAdapterServer((<Net.AddressInfo>this.server.address()).port);
	}
Example #11
Source File: extension.ts    From vscode-riscv-venus with MIT License 6 votes vote down vote up
// The following use of a DebugAdapter factory shows how to control what debug adapter executable is used.
	// Since the code implements the default behavior, it is absolutely not neccessary and we show it here only for educational purpose.

	createDebugAdapterDescriptor(_session: vscode.DebugSession, executable: vscode.DebugAdapterExecutable | undefined): ProviderResult<vscode.DebugAdapterDescriptor> {
		// param "executable" contains the executable optionally specified in the package.json (if any)

		// use the executable specified in the package.json if it exists or determine it based on some other information (e.g. the session)
		if (!executable) {
			const command = "absolute path to my DA executable";
			const args = [
				"some args",
				"another arg"
			];
			const options = {
				cwd: "working directory for executable",
				env: { "VAR": "some value" }
			};
			executable = new vscode.DebugAdapterExecutable(command, args, options);
		}

		// make VS Code launch the DA executable
		return executable;
	}
Example #12
Source File: extension.ts    From vscode-riscv-venus with MIT License 6 votes vote down vote up
/**
	 * Massage a debug configuration just before a debug session is being launched,
	 * e.g. add all missing attributes to the debug configuration.
	 */
	resolveDebugConfiguration(folder: WorkspaceFolder | undefined, config: DebugConfiguration, token?: CancellationToken): ProviderResult<DebugConfiguration> {

		// if launch.json is missing or empty
		if (!config.type && !config.request && !config.name) {
			const editor = vscode.window.activeTextEditor;
			if (editor && editor.document.languageId === 'riscv') {
				config.type = 'venus';
				config.name = 'Launch';
				config.request = 'launch';
				config.program = '${file}';
				config.stopOnEntry = true;
			}
		}

		if (!config.program) {
			return vscode.window.showInformationMessage("Cannot find a program to debug").then(_ => {
				return undefined;	// abort launch
			});
		}

		return config;
	}
Example #13
Source File: EngineNoteProvider.ts    From dendron with GNU Affero General Public License v3.0 6 votes vote down vote up
getChildren(noteProps?: NoteProps): ProviderResult<NoteProps[]> {
    try {
      const ctx = "TreeView:getChildren";
      Logger.debug({ ctx, id: noteProps });
      const { engine } = ExtensionProvider.getDWorkspace();
      const roots = _.filter(_.values(engine.notes), DNodeUtils.isRoot);
      if (!roots) {
        window.showInformationMessage("No notes found");
        return Promise.resolve([]);
      }
      if (noteProps) {
        const childrenIds = TreeUtils.sortNotesAtLevel({
          noteIds: noteProps.children,
          noteDict: engine.notes,
          labelType: this._labelType,
        });

        const childrenNoteProps = childrenIds.map((id) => {
          return engine.notes[id];
        });

        return Promise.resolve(childrenNoteProps);
      } else {
        Logger.info({ ctx, msg: "reconstructing tree: enter" });
        const out = Promise.all(
          roots.flatMap(async (root) => {
            const treeNote = await this.parseTree(root, engine.notes);
            return treeNote.note;
          })
        );
        Logger.info({ ctx, msg: "reconstructing tree: exit" });
        return out;
      }
    } catch (error) {
      Sentry.captureException(error);
      throw error;
    }
  }
Example #14
Source File: BacklinksTreeDataProvider.ts    From dendron with GNU Affero General Public License v3.0 6 votes vote down vote up
public getParent(element: Backlink): ProviderResult<Backlink> {
    try {
      if (element.parentBacklink) {
        return element.parentBacklink;
      } else {
        return undefined;
      }
    } catch (error) {
      Sentry.captureException(error);
      throw error;
    }
  }
Example #15
Source File: element-completion-item-povider.ts    From element-ui-helper with MIT License 6 votes vote down vote up
/**
   * 提供自动完成提示
   *
   * @param document 文档
   * @param position 位置
   * @param token token
   * @param context 上下文
   */
  provideCompletionItems(document: TextDocument, position: Position, token: CancellationToken, context: CompletionContext): ProviderResult<CompletionItem[] | CompletionList<CompletionItem>> {
    this._document = document
    this._position = position
    this.token = token

    let tag: TagObject | undefined = this.getPreTag()
    let attr = this.getPreAttr()

    if (!tag || !/^[E|e]l/.test(tag.text || '')) {
      // 如果不是element的标签(E|el开头) 则返回 null 表示没有hover
      return null
    } else if (this.isAttrValueStart(tag, attr)) {
      // 如果是属性值的开始
      return this.getAttrValueCompletionItems(tag.text, attr)
    } else if (this.isEventStart(tag)) {
      // 优先判定事件
      return this.getEventCompletionItems(tag.text)
    } else if (this.isAttrStart(tag)) {
      // 判断属性
      return this.getAttrCompletionItems(tag.text)
    } else if (this.isTagStart()) {
      // 判断标签
      return this.getTagCompletionItems(tag.text)
    }

    return null
  }
Example #16
Source File: element-hover-provider.ts    From element-ui-helper with MIT License 6 votes vote down vote up
provideHover(document: TextDocument, position: Position, token: CancellationToken): ProviderResult<Hover> {
    this._document = document
    this._position = position
    this._token = token

    const tag: TagObject | undefined = this.getTag()

    if (!/^[E|e]l/.test(tag?.text || '')) {
      // 如果不是element的标签(E|el开头) 则返回 null 表示没有hover
      return null
    }

    const attr = this.getAttr()
    const range = this.getHoverRange(attr)

    return this.getHoverInstance(tag, attr, range)
  }
Example #17
Source File: tree-data-provider.ts    From plugin-vscode with Apache License 2.0 6 votes vote down vote up
getChildren(element?: PackageTreeItem): ProviderResult<PackageTreeItem[]> {
        if (!this.ballerinaExtension.isSwanLake) {
            window.showErrorMessage("Ballerina package overview is only supported in Swan Lake.");
            return;
        }
        if (!element) {
            return this.getPackageStructure();
        } else if (element.getKind() === PROJECT_KIND.PACKAGE) {
            return this.getModuleStructure(element);
        } else if (element.getKind() === PROJECT_KIND.MODULE) {
            return this.getComponentStructure(element);
        } else if (element.getKind() === PROJECT_KIND.SERVICE) {
            return this.getResourceStructure(element);
        }
    }
Example #18
Source File: BacklinksTreeDataProvider.test.ts    From dendron with GNU Affero General Public License v3.0 6 votes vote down vote up
function assertAreEqual(actual: ProviderResult<Backlink>, expected: Backlink) {
  if (actual instanceof Backlink) {
    actual = cleanOutParentPointers(actual);
  } else {
    throw new Error(
      `Actual type was '${typeof actual}'. Must be Backlink type for this assert.`
    );
  }
  expected = cleanOutParentPointers(expected);

  const plainActual = toPlainObject(actual);
  const plainExpected = toPlainObject(expected);

  expect(plainActual).toEqual(plainExpected);
}
Example #19
Source File: cfgFormat.ts    From sourcepawn-vscode with MIT License 6 votes vote down vote up
public provideDocumentFormattingEdits(
    document: TextDocument,
    options: FormattingOptions,
    token: CancellationToken
  ): ProviderResult<TextEdit[]> {
    let workspaceFolder = Workspace.getWorkspaceFolder(document.uri);

    // Get the user's settings.
    let insertSpaces: boolean =
      Workspace.getConfiguration("editor", workspaceFolder).get(
        "insertSpaces"
      ) || false;
    let tabSize: number =
      Workspace.getConfiguration("editor", workspaceFolder).get("tabSize") || 2;

    // Apply user settings
    const start = new Position(0, 0);
    const end = new Position(
      document.lineCount - 1,
      document.lineAt(document.lineCount - 1).text.length
    );
    let range = new Range(start, end);

    let text = formatCFGText(document.getText(), insertSpaces, tabSize);

    // If process failed,
    if (text === "") {
      window.showErrorMessage(
        "The formatter failed to run, check the console for more details."
      );
      return undefined;
    }
    return [new TextEdit(range, text)];
  }
Example #20
Source File: codelens-provider.ts    From plugin-vscode with Apache License 2.0 5 votes vote down vote up
provideCodeLenses(_document: TextDocument, _token: CancellationToken): ProviderResult<CodeLens[]> {
        let codeLenses: CodeLens[] = [];
        if (this.ballerinaExtension.langClient && window.activeTextEditor) {
            return this.getCodeLensList();
        }
        return codeLenses;
    }
Example #21
Source File: extension.ts    From vscode-autohotkey with MIT License 5 votes vote down vote up
public createDebugAdapterDescriptor(_session: vscode.DebugSession): ProviderResult<vscode.DebugAdapterDescriptor> {
        return new vscode.DebugAdapterInlineImplementation(new DebugSession());
    }
Example #22
Source File: gcodeHoverProvider.ts    From vscode-gcode with MIT License 5 votes vote down vote up
provideHover(document: TextDocument, position: Position, token: CancellationToken): ProviderResult<Hover> {
        const code = document.getText(document.getWordRangeAtPosition(position));
        const definition = this.dictionary.lookup(code);
        return definition == null ? null : new Hover(definition);
    }
Example #23
Source File: microProfileCompletionItemProvider.ts    From vscode-microprofile with Apache License 2.0 5 votes vote down vote up
provideCompletionItems(
      document: TextDocument,
      position: Position,
      _token: CancellationToken,
      _context: CompletionContext): ProviderResult<CompletionItem[] | CompletionList<CompletionItem>> {
    return commands.executeCommand("java.execute.workspaceCommand", JAVA_COMPLETION_REQUEST, adaptToMicroProfileCompletionParams(document, position));
  }
Example #24
Source File: sourceDefinitionProvider.ts    From vscode-dbt-power-user with MIT License 5 votes vote down vote up
provideDefinition(
    document: TextDocument,
    position: Position,
    token: CancellationToken
  ): ProviderResult<Definition | DefinitionLink[]> {
    return new Promise((resolve, reject) => {
      const hover = document.getText(document.getWordRangeAtPosition(position));
      const range = document.getWordRangeAtPosition(
        position,
        SourceDefinitionProvider.IS_SOURCE
      );
      const word = document.getText(range);

      const linePrefix = document
        .lineAt(position)
        .text.substr(0, position.character);

      if (
        !isEnclosedWithinCodeBlock(document, position) ||
        !linePrefix.includes("source") ||
        hover === "source"
      ) {
        reject();
        return;
      }

      const source = word.match(SourceDefinitionProvider.GET_SOURCE_INFO);
      if (source === null || source === undefined) {
        reject();
        return;
      }
      if (source.length < 2) {
        reject();
        return;
      }
      const definition = this.getSourceDefinition(
        source[0],
        document.uri,
        source[1],
      );
      resolve(definition);
    });
  }
Example #25
Source File: spFormat.ts    From sourcepawn-vscode with MIT License 5 votes vote down vote up
public provideDocumentFormattingEdits(
    document: TextDocument,
    options: FormattingOptions,
    token: CancellationToken
  ): ProviderResult<TextEdit[]> {
    // Get the user's settings.
    let insertSpaces: boolean =
      Workspace.getConfiguration("editor").get("insertSpaces") || false;
    let UseTab: string = insertSpaces ? "Never" : "Always";
    let tabSize: number =
      Workspace.getConfiguration("editor").get("tabSize") || 2;

    let workspaceFolder = Workspace.getWorkspaceFolder(document.uri);
    let defaultStyles: string[] =
      Workspace.getConfiguration("sourcepawn", workspaceFolder).get(
        "formatterSettings"
      ) || [];

    let default_style: string = "{" + defaultStyles.join(", ") + "}";

    // Apply user settings
    default_style = default_style
      .replace(/\${TabSize}/g, tabSize.toString())
      .replace(/\${UseTab}/g, UseTab);
    const start = new Position(0, 0);
    const end = new Position(
      document.lineCount - 1,
      document.lineAt(document.lineCount - 1).text.length
    );
    const range = new Range(start, end);
    const tempFile = join(__dirname, "temp_format.sp");
    let file = openSync(tempFile, "w", 0o765);
    writeSync(file, document.getText());
    closeSync(file);
    let text = this.clangFormat(tempFile, "utf-8", default_style);

    // If process failed,
    if (text === undefined) {
      window.showErrorMessage(
        "The formatter failed to run, check the console for more details."
      );
      return undefined;
    }
    text = fixFormatting(text);
    return [new TextEdit(range, text)];
  }
Example #26
Source File: tree-data-provider.ts    From plugin-vscode with Apache License 2.0 5 votes vote down vote up
getParent?(element: PackageTreeItem): ProviderResult<PackageTreeItem> {
        return element.getParent();
    }
Example #27
Source File: extension.ts    From vscode-riscv-venus with MIT License 5 votes vote down vote up
createDebugAdapterDescriptor(_session: vscode.DebugSession): ProviderResult<vscode.DebugAdapterDescriptor> {
		return new vscode.DebugAdapterInlineImplementation(new VenusDebugSession());
	}
Example #28
Source File: actions.ts    From format-imports-vscode with MIT License 5 votes vote down vote up
provideCodeActions(): ProviderResult<(CodeAction | Command)[]> {
    return SortActionProvider.ACTION_COMMANDS;
  }
Example #29
Source File: BacklinksTreeDataProvider.ts    From dendron with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
   * Implementing this method allows us to asynchronously calculate hover
   * contents ONLY when the user actually hovers over an item. Lazy loading this
   * data allows us to speed up the initial load time of the backlinks panel.
   * @param _item
   * @param element
   * @param _token
   * @returns
   */
  public resolveTreeItem(
    _item: TreeItem,
    element: Backlink,
    _token: CancellationToken
  ): ProviderResult<TreeItem> {
    // This method implies that an item was hovered over
    AnalyticsUtils.track(VSCodeEvents.BacklinksPanelUsed, {
      type: "ItemHoverDisplayed",
      state: element.treeItemType,
    });

    if (
      element.treeItemType === BacklinkTreeItemType.noteLevel &&
      element.refs
    ) {
      return new Promise<TreeItem>((resolve) => {
        this.getTooltipForNoteLevelTreeItem(element.refs!).then((tooltip) => {
          resolve({
            tooltip,
          });
        });
      });
    } else if (element.treeItemType === BacklinkTreeItemType.referenceLevel) {
      return new Promise<TreeItem>((resolve) => {
        if (element.singleRef?.isFrontmatterTag) {
          resolve({
            tooltip: new MarkdownString(
              this.FRONTMATTER_TAG_CONTEXT_PLACEHOLDER
            ),
          });
        }
        this.getSurroundingContextForRef(
          element.singleRef!,
          this.MAX_LINES_OF_CONTEX̣T
        ).then((value) => {
          const tooltip = new MarkdownString();
          tooltip.appendMarkdown(value);

          tooltip.supportHtml = true;
          tooltip.isTrusted = true;
          tooltip.supportThemeIcons = true;

          resolve({
            tooltip,
          });
        });
      });
    } else {
      return undefined;
    }
  }