vscode#MarkdownString TypeScript Examples

The following examples show how to use vscode#MarkdownString. 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: 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 #2
Source File: NextObjectIdCompletionItem.ts    From al-objid with MIT License 6 votes vote down vote up
getCompletionDocumentation(type: string, objectId: NextObjectIdInfo): MarkdownString {
        const firstLine = `Assigns the next available ${this.nextIdDescription(type)} from the Azure back end.`;
        let typeDesc = `${type} ${objectId.id}`;
        if (type.startsWith("table_")) {
            typeDesc = `field(${objectId.id}; ...)`;
        } else if (type.startsWith("enum_")) {
            typeDesc = `value(${objectId.id}; ...)`;
        }

        const message = new MarkdownString(firstLine);
        message.appendCodeblock(typeDesc, "al");
        if (!objectId.hasConsumption) {
            message.appendMarkdown(
                "**Important:** The back end has no object ID consumption information. Please, run `Ninja: Synchronize object IDs with the Azure back end` command before accepting this object ID."
            );
            return message;
        }
        message.appendMarkdown(
            "This number is **temporary**. The actual number will be assigned when you select this auto-complete entry."
        );

        return message;
    }
Example #3
Source File: AuthorizationStatusBar.ts    From al-objid with MIT License 6 votes vote down vote up
private async readUserInfo(app: ALApp, authKey: string) {
        const authorized = !!authKey;
        // TODO Use app.config.isValid rather than accessing back end again
        const info = await Backend.getAuthInfo(app, authKey);
        if (info) {
            if (info.authorized === authorized) {
                if (!info.valid && info.authorized) {
                    this._status.text = `$(error) Invalid authorization`;
                    this._status.tooltip = new MarkdownString(
                        "Your authorization is ***invalid***. The authorization key stored in `.objidconfig` is not accepted by the back end. If you switched branches, make sure the current branch has the latest `.objidconfig` from your main branch."
                    );
                    return;
                }
                this.updateTooltip(app!.name, authorized, this.getUserInfoText(info));
            } else {
                this._status.text = `$(${authorized ? "warning" : "error"}) Invalid authorization`;
                this._status.tooltip = new MarkdownString(
                    `Your authorization is ***invalid***. ${
                        authorized
                            ? "You have authorization file (`.objidconfig`) but the app is not authorized."
                            : "You have no authorization file (`.objidconfig`), but the app is authorized."
                    } Try to pull latest changes from your Git.${
                        info && info.user ? `\n\nThis app was last authorized by ${this.getUserInfoText(info)}` : ""
                    }`
                );
            }
        }
    }
Example #4
Source File: AuthorizationStatusBar.ts    From al-objid with MIT License 6 votes vote down vote up
private updateTooltip(name: string, authorized: boolean, userInfo: string) {
        this._status.tooltip = authorized
            ? new MarkdownString(
                  `The "${name}" application is ***authorized*** with ${EXTENSION_NAME} back end. Your data exchange is secure.${
                      userInfo ? " " + `\n\nAuthorized by ${userInfo}` : ""
                  }`
              )
            : new MarkdownString(
                  `The "${name}" application is ***not authorized***.\n\nTo authorize your app, please run the \`Ninja: Authorize AL App\` command or click this status bar item.\n\nTo learn more about authorization [click here](${URLS.AUTHORIZATION_LEARN})`
              );
    }
Example #5
Source File: statusBar.ts    From vscode-todo-md with MIT License 6 votes vote down vote up
update(fewNextTasks: TheTask[]) {
		if (!$config.statusBarMainEnabled) {
			return;
		}
		const firstTaskFormatted = formatTask(fewNextTasks[0]);
		this.updateText(firstTaskFormatted);
		const markdown = new MarkdownString(undefined, true);
		markdown.isTrusted = true;
		// TODO: use markdown formatting instead of formatTask()
		markdown.appendMarkdown(fewNextTasks.slice(0, 10).map((task, i) => `- ${formatTask(task)}`).join('\n'));
		this.updateHover(markdown);
	}
Example #6
Source File: completionProvider.ts    From memo with MIT License 6 votes vote down vote up
resolveCompletionItem = async (item: MemoCompletionItem) => {
  if (item.fsPath) {
    try {
      if (containsMarkdownExt(item.fsPath)) {
        item.documentation = new MarkdownString((await readFile(item.fsPath)).toString());
      } else if (containsImageExt(item.fsPath) && !isUncPath(item.fsPath)) {
        item.documentation = new MarkdownString(`![](${Uri.file(item.fsPath).toString()})`);
      }
    } catch (error) {
      console.error(error);
    }
  }

  return item;
}
Example #7
Source File: completionProvider.spec.ts    From memo with MIT License 6 votes vote down vote up
describe('resolveCompletionItem()', () => {
  beforeEach(closeEditorsAndCleanWorkspace);

  afterEach(closeEditorsAndCleanWorkspace);

  it('should add documentation for a markdown completion item', async () => {
    const noteName = `note-${rndName()}`;

    const noteUri = await createFile(`${noteName}.md`, 'Test documentation');

    const completionItem: MemoCompletionItem = new CompletionItem(
      noteName,
      CompletionItemKind.File,
    );

    completionItem.fsPath = noteUri!.fsPath;

    expect(
      ((await resolveCompletionItem(completionItem)).documentation as MarkdownString).value,
    ).toBe('Test documentation');
  });

  it('should add documentation for an image completion item', async () => {
    const imageName = `image-${rndName()}`;

    const imageUri = await createFile(`${imageName}.png`);

    const completionItem: MemoCompletionItem = new CompletionItem(
      imageName,
      CompletionItemKind.File,
    );

    completionItem.fsPath = imageUri!.fsPath;

    expect(
      ((await resolveCompletionItem(completionItem)).documentation as MarkdownString).value,
    ).toBe(`![](${Uri.file(completionItem.fsPath).toString()})`);
  });
});
Example #8
Source File: q-function.ts    From vscode-q with MIT License 6 votes vote down vote up
constructor(name: string, parent: QDictTreeItem, body: string) {
        super(name, TreeItemCollapsibleState.None);
        this._parent = parent;
        this._body = body;
        parent.appendChild(this);
        setCommand(this);
        const md = new MarkdownString();
        md.appendCodeblock(this._body, 'q');
        this.tooltip = md;
        this.iconPath = {
            light: path.join(__filename, '../../assets/svg/item/function.svg'),
            dark: path.join(__filename, '../../assets/svg/item/function.svg')
        };
    }
Example #9
Source File: history.ts    From vscode-q with MIT License 6 votes vote down vote up
private constructor(history: History, parent: TreeItem | null) {
        super(history.uniqLabel.replace(',', '-') + ' | ' + dayjs(history.time).format('HH:mm:ss'), TreeItemCollapsibleState.None);
        this.uniqLabel = history.uniqLabel;
        this.query = history.query;
        this.time = history.time;
        this.duration = history.duration;
        this._parent = parent;
        this.errorMsg = history.errorMsg;
        const mdString = new MarkdownString();
        mdString.appendMarkdown(`- server: ${history.uniqLabel.replace(',', '-')}\n`);
        mdString.appendMarkdown(`- time: ${dayjs(history.time).format('YYYY.MM.DD HH:mm:ss.SSS')}\n`);
        mdString.appendMarkdown(`- duration: ${history.duration}\n`);

        if (this.errorMsg) {
            mdString.appendMarkdown('- error:');
            mdString.appendCodeblock(this.errorMsg, 'q');
        } else {
            mdString.appendMarkdown('- query:');
            mdString.appendCodeblock(history.query, 'q');
        }
        this.tooltip = mdString;
    }
Example #10
Source File: LineHistory.ts    From vscode-realtime-debugging with GNU General Public License v3.0 6 votes vote down vote up
private updateDecorations() {
		for (const editor of window.visibleTextEditors) {
			const entry = this.map.get(editor.document.uri.toString());
			if (!entry) {
				editor.setDecorations(this.decorationType, []);
				continue;
			}

			editor.setDecorations(
				this.decorationType,
				[...entry.lines.values()].map((history) => {
					const range = editor.document.lineAt(history.line).range;
					const hoverMessage = new MarkdownString();
					hoverMessage.isTrusted = true;
					for (const h of history.history.slice().reverse()) {
						hoverMessage.appendMarkdown(`* ${h}`);
					}
					/*const params = encodeURIComponent(
						JSON.stringify({ stepId: o.id } as RunCmdIdArgs)
					);*/
					/*hoverMessage.appendMarkdown(
						`* [Run Step '${o.id}'](command:${runCmdId}?${params})`
					);*/

					return {
						range,
						renderOptions: {
							after: {
								contentText: history.history[0],
							},
						},
						hoverMessage,
					} as DecorationOptions;
				})
			);
		}
	}
Example #11
Source File: utils.ts    From yash with MIT License 6 votes vote down vote up
export function createMarkedCodeString(code: string, languageId: string): MarkdownString {
    const str = new MarkdownString();
    str.appendCodeblock(code, languageId);
    return str;
}
Example #12
Source File: document-generator.ts    From element-ui-helper with MIT License 6 votes vote down vote up
/**
   * 宣统提示文档生成入口
   *
   * @template T 文档类型
   * @param {T} document 文档
   * @param {string} key 属性key
   * @param {string} tag 文档标签
   * @param {string} attr 文档属性
   * @param {ExtensionLanguage} language 语言
   * @return {*}  {MarkdownString}
   * @memberof HoverDocumentGenerator
   */
  generate<T extends BaseDocument>(document: T, key: string, tag: string, attr: string, language: ExtensionLanguage): MarkdownString {
    let markdownString: MarkdownString = new MarkdownString('')
    switch (key) {
      case 'attributes':
        markdownString = this.generateAttribute<T>(document, tag, attr, language)
        break
      case 'methods':
        markdownString = this.generateMethods<T>(document, tag, attr, language)
        break
      case 'events':
        markdownString = this.generateEvents<T>(document, tag, attr, language)
        break
      case 'slots':
        markdownString = this.generateSlots<T>(document, tag, attr, language)
        break
      case 'scopedSlots':
        markdownString = this.generateScopedSlots<T>(document, tag, attr, language)
        break
      default:
        // 生成其他文档时 属性为key
        markdownString = this.generateOther<T>(document, tag, key, language)
    }
    return markdownString
  }
Example #13
Source File: ahkHoverProvider.ts    From vscode-autohotkey with MIT License 6 votes vote down vote up
private tryGetSnippetHover(context: Context): Hover {
        let snippetKey = context.word.toLowerCase();
        if (context.nextChart == "(") {
            snippetKey += "()"
        }
        const snippet = this.snippetCache.get(snippetKey)
        if (snippet) {
            const content = new MarkdownString(null, true)
                .appendCodeblock(snippet.body, 'ahk')
            if (snippet.description) {
                 content.appendText(snippet.description)
            }
            return new Hover(content)
        }
    }
Example #14
Source File: element-hover-provider.ts    From element-ui-helper with MIT License 6 votes vote down vote up
/**
   * 创建Hover实例
   *
   * @param language 语言
   * @param tag 标签
   * @param attr 属性
   * @param range 范围
   */
  createHoverInstance(language: ExtensionLanguage, tag: string, attr: string, range: Range): null | Hover {
    let document: Record<string, any> = localDocument[language]
    if (tag === attr) {
      attr = ''
    }
    if (Object.prototype.hasOwnProperty.call(document, tag)) {
      const tagDocument = document[tag]
      const hoverMarkdownStrings: MarkdownString[] = []
      Object.keys(tagDocument).forEach((key: string) => {
        const hoverMarkdownString: MarkdownString = HoverDocumentGenerator.getInstance().generate<ElDocument>(tagDocument, key, tag, attr, language)
        if (hoverMarkdownString) {
          hoverMarkdownStrings.push(hoverMarkdownString)
        }
      })
      return new Hover(hoverMarkdownStrings, range)
    } else {
      return null
    }
  }
Example #15
Source File: document-generator.ts    From element-ui-helper with MIT License 6 votes vote down vote up
/**
   * 生成其他文档表格
   *
   * @template T type extends BaseDocument
   * @param {T} document 文档 具体标签对应的文档
   * @param {string} tag 标签
   * @param {string} attribute 属性 文档对象具体的属性值
   * @param {string} language 语言
   * @return {*}  {MarkdownString}
   * @memberof HoverDocumentGenerator
   */
  private generateOther<T extends BaseDocument>(document: T, tag: string, attribute: string, language: string): MarkdownString {
    let isUndefined: boolean = true // 标记是否具有文档
    let markdownString: MarkdownString = new MarkdownString('', true)
    const attributes = document[attribute] || []
    if (attributes.length) {
      markdownString.appendMarkdown(`### ${tag} ${attribute} \r`)
      const keys = Object.keys(attributes[0])
      markdownString.appendMarkdown(`| ${keys.join('|')} |\r`)
      markdownString.appendMarkdown(`| ${keys.map(() => '---').join('|')} |\r`)
      // 遍历属性值值生成文档
      attributes.forEach((row: DocumentAttribute) => {
        let str = '|'
        keys.forEach((key) => {
          str += `${row[key]}|`
        })
        str += '\r'
        markdownString.appendMarkdown(str)
      })
      isUndefined = false
    }
    if (isUndefined) {
      markdownString = new MarkdownString('', true)
    }
    return markdownString
  }
Example #16
Source File: spUtils.ts    From sourcepawn-vscode with MIT License 6 votes vote down vote up
/**
 * Parse a Sourcemod JSDoc documentation string and convert it to a MarkdownString.
 * @param  {string} description   The Sourcemod JSDoc string.
 * @returns MarkdownString
 */
export function descriptionToMD(description?: string): MarkdownString {
  if (description === undefined) {
    return new MarkdownString("");
  }
  description = description
    // Remove leading *< from documentation (usually present in enum member's description)
    .replace(/^\*\</, "")
    .replace(/\</gm, "\\<")
    .replace(/\>/gm, "\\>")
    .replace(/([\w\,]{1})\n/gm, "$1")
    //.replace(/([^.])(\.) *[\n]+(?:\s*([^@\s.]))/gm, "$1. $3")
    .replace(/\s+\*\s*/gm, "\n\n");
  // Make all @ nicer
  description = description.replace(/\s*(@[A-Za-z]+)\s+/gm, "\n\n_$1_ ");
  // Make the @param nicer
  description = description.replace(
    /(\_@param\_) ([A-Za-z0-9_.]+)\s*/gm,
    "$1 `$2` — "
  );

  // Format other functions which are referenced in the description
  description = description.replace(/(\w*.\w+\([A-Za-z0-9_ \:]*\))/gm, "`$1`");
  description = description.replace("DEPRECATED", "**DEPRECATED**");
  return new MarkdownString(description);
}
Example #17
Source File: completionHelper.ts    From coffeesense with MIT License 5 votes vote down vote up
export async function testCompletionResolve(
  docUri: vscode.Uri,
  position: vscode.Position,
  expectedItems: CompletionItem[],
  itemResolveCount = 1,
  matchFn?: (ei: CompletionItem) => (result: CompletionItem) => boolean
) {
  await showFile(docUri);

  const result = (await vscode.commands.executeCommand(
    'vscode.executeCompletionItemProvider',
    docUri,
    position,
    undefined,
    itemResolveCount
  )) as vscode.CompletionList;

  expectedItems.forEach(ei => {
    if (typeof ei === 'string') {
      assert.ok(
        result.items.some(i => i.label === ei),
        `Can't find matching item for\n${JSON.stringify(ei, null, 2)}\nSeen items:\n${JSON.stringify(
          result.items,
          null,
          2
        )}`
      );
    } else {
      const match = matchFn ? result.items.find(matchFn(ei)) : result.items.find(i => i.label === ei.label);
      if (!match) {
        assert.fail(
          `Can't find matching item for\n${JSON.stringify(ei, null, 2)}\nSeen items:\n${JSON.stringify(
            result.items,
            null,
            2
          )}`
        );
      }

      assert.equal(match.label, ei.label);
      if (ei.kind) {
        assert.equal(match.kind, ei.kind);
      }
      if (ei.detail) {
        assert.equal(match.detail, ei.detail);
      }

      if (ei.documentation) {
        if (typeof match.documentation === 'string') {
          assert.equal(normalizeNewline(match.documentation), normalizeNewline(ei.documentation as string));
        } else {
          if (ei.documentation && (ei.documentation as MarkdownString).value && match.documentation) {
            assert.equal(
              normalizeNewline((match.documentation as vscode.MarkdownString).value),
              normalizeNewline((ei.documentation as MarkdownString).value)
            );
          }
        }
      }

      if (ei.additionalTextEdits) {
        assert.strictEqual(match.additionalTextEdits?.length, ei.additionalTextEdits.length);

        ei.additionalTextEdits.forEach((textEdit, i) => {
          assert.strictEqual(match.additionalTextEdits?.[i].newText, textEdit.newText);
          assert.strictEqual(match.additionalTextEdits?.[i].range.start.line, textEdit.range.start.line);
          assert.strictEqual(match.additionalTextEdits?.[i].range.start.character, textEdit.range.start.character);
          assert.strictEqual(match.additionalTextEdits?.[i].range.end.line, textEdit.range.end.line);
          assert.strictEqual(match.additionalTextEdits?.[i].range.end.character, textEdit.range.end.character);
        });
      }
    }
  });
}
Example #18
Source File: ALHoverProvider.ts    From vscode-alxmldocumentation with MIT License 5 votes vote down vote up
async provideHover(document: TextDocument, position: Position, token: CancellationToken) {   
        let result: MarkdownString = new MarkdownString();

        // retrieve source code from language server
        let alLangServerProxy = new ALLangServerProxy();     
        const alDefinition = await alLangServerProxy.GetALObjectFromDefinition(document.uri.toString(), position);
        if ((alDefinition === undefined) || (alDefinition.ALObject === null)) {
            return;
        }

        // find AL procedure by line no.
        let alProcedure: ALProcedure | undefined = alDefinition.ALObject.Procedures?.find(procedure => procedure.LineNo === alDefinition.Position.line);
        if ((alProcedure === undefined) || (alProcedure.ALDocumentation.Exists === ALDocumentationExists.No)) {
            return; // not found
        }

        let jsonDocumentation: any = await alDefinition.ALObject.GetDocumentationAsJsonObject(alProcedure);                
        // AL Language Version 6.x is providing simple XML Documentation capabilities. Do not push procedure summary in this case.
        if ((alLangServerProxy.GetALExtension()?.packageJSON.version < '6.0.0') || (alProcedure.ALDocumentation.Exists === ALDocumentationExists.Inherit)) {
            // add Summary to hover message.
            if ((jsonDocumentation.summary) && (jsonDocumentation.summary !== '')) {
                result.appendMarkdown(`${jsonDocumentation.summary} \n`);
            } else {
                return; // don't show w/o summary
            }
        }
        // add Remarks to hover message.
        if ((jsonDocumentation.remarks) && (jsonDocumentation.remarks.trim() !== '')) {
            result.appendMarkdown(`*${jsonDocumentation.remarks}*  \n`);
        } 

        // add Return to hover message.
        if ((alProcedure.Return !== undefined) && (alProcedure.Return.ALDocumentation.Exists === ALDocumentationExists.Yes)) {
            // convert XML Documentation to more readable JSON object.
            let returnDocumentation = ALDocCommentUtil.GetJsonFromALDocumentation(alProcedure.Return.ALDocumentation.Documentation);
            if ((returnDocumentation.returns) && (returnDocumentation.returns.trim() !== '')) {
                result.appendMarkdown(`${returnDocumentation.returns} \n`);
            }
        }
        
        // add Example to hover message.
        if (jsonDocumentation.example) {
            result.appendMarkdown(`#### Example \n`);
            result.appendMarkdown(`${jsonDocumentation.example.value} \n`);
            result.appendCodeblock(jsonDocumentation.example.code);
        }

        if (result.value !== '') {
            return new Hover(result);
        }
    }
Example #19
Source File: document-generator.ts    From element-ui-helper with MIT License 5 votes vote down vote up
/**
   * 生成属性文档表格
   *
   * @template T type extends BaseDocument
   * @param {T} document 文档 具体标签对应的文档
   * @param {string} tag 标签
   * @param {string} attribute 属性 在标签的属性上悬停时具有
   * @param {string} language 语言
   * @return {*}  {MarkdownString}
   * @memberof HoverDocumentGenerator
   */
  private generateAttribute<T extends BaseDocument>(document: T, tag: string, attribute: string, language: string): MarkdownString {
    let isUndefined: boolean = true // 标记是否具有文档
    let markdownString: MarkdownString = new MarkdownString('', true)
    const attributes = document.attributes || [] // 取得属性列表
    if (attributes.length) {
      // 生成表头
      if (language === 'zh-CN') {
        markdownString.appendMarkdown(`### ${tag} 属性 \r`)
        markdownString.appendMarkdown('| 属性 | 说明 | 类型 | 可选值 | 默认值 |\r')
      } else {
        markdownString.appendMarkdown(`### ${tag} Attributes \r`)
        markdownString.appendMarkdown('| Attributes | Description | Type | Accepted Values | Default |\r')
      }
      markdownString.appendMarkdown('|---|---|:-:|---|:-:|\r')
    }
    if (attribute.length === 0) {
      // 属性 和标签一样 显示全部
      attributes.forEach((row: DocumentAttribute) => {
        markdownString.appendMarkdown(`|${row.name}|${row.description}|${row.type}|${row.value}|${row.default}|\r`)
        isUndefined = false
      })
    } else {
      // 属性和标签不一样 显示标签下的某个属性的信息
      const row = attributes.find((row: DocumentAttribute) => row.name === attribute)
      if (row) {
        markdownString.appendMarkdown(`|${row.name}|${row.description}|${row.type}|${row.value}|${row.default}|\r`)
        isUndefined = false
      }
    }
    if (isUndefined) {
      markdownString = new MarkdownString('', true)
    }
    return markdownString
  }
Example #20
Source File: statusBar.ts    From vscode-todo-md with MIT License 5 votes vote down vote up
protected updateHover(text: MarkdownString | string): void {
		this.statusBarItem.tooltip = text;
	}
Example #21
Source File: getTaskHover.ts    From vscode-todo-md with MIT License 5 votes vote down vote up
/**
 * Transform task to show it in Tree View or Editor hover as markdown
 */
export function getTaskHoverMd(task: TheTask) {
	const markdown = new MarkdownString(undefined, true);
	markdown.isTrusted = true;
	const priorityColor = task.priority === 'A' ? '#ec4f47' :
		task.priority === 'B' ? '#fd9f9a' :
			task.priority === 'C' ? '#ffb648' :
				task.priority === 'D' ? '#f1d900' :
					task.priority === 'E' ? '#97c500' :
						task.priority === 'F' ? '#00cfad' : undefined;
	if (priorityColor) {
		markdown.appendMarkdown(`<span style="background-color:${priorityColor};">&thinsp;</span>&nbsp;`);
	}
	if (task.done) {
		markdown.appendMarkdown(`<span style="color:#7cc54b;">$(pass)</span> `);
	}

	let count = '';
	if (task.count) {
		count = ` \`[${task.count.current}/${task.count.needed}]\``;
	}
	let due = '';
	if (task.due || task.overdue) {
		let dueColor = '';
		let dueContent = '';
		let codicon = '$(history)';
		if (task.due?.isDue === DueState.Due) {
			dueColor = helpGetColor('due');
		} else if (task.due?.isDue === DueState.Overdue) {
			dueColor = helpGetColor('overdue');
			dueContent = String(task.due.overdueInDays);
		} else if (task.due?.isDue === DueState.NotDue) {
			dueColor = helpGetColor('notDue');
			dueContent = makeClosestDueDateDecoration(task);
		} else if (task.due?.isDue === DueState.Invalid) {
			dueColor = helpGetColor('invalid');
			codicon = '$(error)';
			dueContent = 'Invalid';
		}
		due = ` <span style="color:${dueColor || 'inherit'};">|${codicon} ${dueContent}|</span>&nbsp;`;
	}

	const words = task.title.split(' ');
	let taskTitle = task.title;

	const resultWords = [];
	for (const word of words) {
		if (
			word.length > 1 &&
			(word[0] === '#' || word[0] === '+' || word[0] === '@')
		) {
			if (word[0] === '#') {
				resultWords.push(`<span style="color:#fff;background-color:#029cdf;">&nbsp;${word}&nbsp;</span>`);
			} else if (word[0] === '+') {
				resultWords.push(`<span style="color:#fff;background-color:#36cc9a;">&nbsp;${word}&nbsp;</span>`);
			} else {
				resultWords.push(`<span style="color:#fff;background-color:#7284eb;">&nbsp;${word}&nbsp;</span>`);
			}
		} else {
			resultWords.push(word);
		}
	}

	taskTitle = resultWords.join(' ');

	markdown.appendMarkdown(`${taskTitle}${count}${due}\n\n`);

	if (task.start) {
		markdown.appendMarkdown(`<span>$(watch) ${durationTo(task, false, $config.durationIncludeSeconds)}</span>\n\n`);
	}

	return markdown;
}
Example #22
Source File: document-generator.ts    From element-ui-helper with MIT License 5 votes vote down vote up
/**
   * 生成方法文档表格
   *
   * @template T type extends BaseDocument
   * @param {T} document 文档 具体标签对应的文档
   * @param {string} tag 标签
   * @param {string} attribute 属性 在标签的属性上悬停时具有
   * @param {string} language 语言
   * @return {*}  {MarkdownString}
   * @memberof HoverDocumentGenerator
   */
  private generateMethods<T extends BaseDocument>(document: T, tag: string, attribute: string, language: string): MarkdownString {
    let isUndefined: boolean = true // 标记是否具有文档
    let markdownString: MarkdownString = new MarkdownString('', true)
    const methods = document.methods || []
    if (methods.length) {
      if (language === 'zh-CN') {
        markdownString.appendMarkdown(`### ${tag} 方法\r`)
        markdownString.appendMarkdown('| 方法 | 说明 | 参数 |\r')
      } else {
        markdownString.appendMarkdown(`### ${tag} Method\r`)
        markdownString.appendMarkdown('| Method | Description | Parameters |\r')
      }
      markdownString.appendMarkdown('|---|---|:-:|\r')
    }
    if (attribute.length === 0) {
      // 属性 和标签一样 显示全部
      methods.forEach((row: DocumentMethod) => {
        markdownString.appendMarkdown(`|${row.name}|${row.description}|${row.parameter}|\r`)
        isUndefined = false
      })
    } else {
      // 属性和标签不一样 显示标签下的某个属性的信息
      const row = methods.find((row: DocumentMethod) => row.name === attribute)
      if (row) {
        markdownString.appendMarkdown(`|${row.name}|${row.description}|${row.parameter}|\r`)
        isUndefined = false
      }
    }
    if (isUndefined) {
      markdownString = new MarkdownString('', true)
    }
    return markdownString
  }
Example #23
Source File: document-generator.ts    From element-ui-helper with MIT License 5 votes vote down vote up
/**
   * 生成事件文档表格
   *
   * @template T type extends BaseDocument
   * @param {T} document 文档 具体标签对应的文档
   * @param {string} tag 标签
   * @param {string} attribute 属性 在标签的属性上悬停时具有
   * @param {string} language 语言
   * @return {*}  {MarkdownString}
   * @memberof HoverDocumentGenerator
   */
  private generateEvents<T extends BaseDocument>(document: T, tag: string, attribute: string, language: string): MarkdownString {
    let isUndefined: boolean = true // 标记是否具有文档
    let markdownString: MarkdownString = new MarkdownString('', true)
    const events = document.events || []
    if (events.length) {
      if (language === 'zh-CN') {
        markdownString.appendMarkdown(`### ${tag} 事件\r`)
        markdownString.appendMarkdown('| 方法 | 说明 | 参数 |\r')
      } else {
        markdownString.appendMarkdown(`### ${tag} Event\r`)
        markdownString.appendMarkdown('| Event | Description | Parameters |\r')
      }
      markdownString.appendMarkdown('|---|---|:-:|\r')
    }
    if (attribute.length === 0) {
      // 属性 和标签一样 显示全部
      events.forEach((row: DocumentMethod) => {
        markdownString.appendMarkdown(`|${row.name}|${row.description}|${row.parameter}|\r`)
        isUndefined = false
      })
    } else {
      // 属性和标签不一样 显示标签下的某个属性的信息
      const row = events.find((row: DocumentMethod) => row.name === attribute)
      if (row) {
        markdownString.appendMarkdown(`|${row.name}|${row.description}|${row.parameter}|\r`)
        isUndefined = false
      }
    }
    if (isUndefined) {
      markdownString = new MarkdownString('', true)
    }
    return markdownString
  }
Example #24
Source File: hoverProvider.ts    From vscode-stripe with MIT License 5 votes vote down vote up
async provideHover(
    document: TextDocument,
    position: Position,
    token: CancellationToken,
  ): Promise<Hover | undefined> {
    let contents: any[] = [];
    let range;

    const params = {
      textDocument: this.languageClient.code2ProtocolConverter.asTextDocumentIdentifier(document),
      position: this.languageClient.code2ProtocolConverter.asPosition(position),
    };

    // get javs doc convent from server
    const hoverResponse = await this.languageClient.sendRequest(HoverRequest.type, params, token);

    // parse for stripe api hover content
    let stripeApiHoverContent;
    if (hoverResponse && hoverResponse.contents && Array.isArray(hoverResponse.contents)) {
      const stripeFullClassPath = Object.entries(hoverResponse.contents[0])
        .filter((item) => item[0] === 'value')
        .filter((item) => item[1].includes('com.stripe.model'));
      if (stripeFullClassPath.length > 0) {
        const stripeMethod = stripeFullClassPath[0][1].split(' ')[1].split('(')[0];
        const url = getJavaApiDocLink(stripeMethod);
        if (url) {
          stripeApiHoverContent = new MarkdownString(
            'See this method in the [Stripe API Reference](' + url + ')',
          );
          stripeApiHoverContent.isTrusted = true;
        }
      }
    }

    if (!!stripeApiHoverContent) {
      contents = contents.concat([stripeApiHoverContent]);
    }

    // get contributed hover commands from third party extensions.
    const contributedCommands: Command[] = await this.getContributedHoverCommands(params, token);

    if (contributedCommands.length > 0) {
      const contributedContent = new MarkdownString(
        contributedCommands.map((command) => this.convertCommandToMarkdown(command)).join(' | '),
      );
      contributedContent.isTrusted = true;
      contents = contents.concat([contributedContent]);
    }

    // combine all hover contents with java docs from server
    const serverHover = this.languageClient.protocol2CodeConverter.asHover(hoverResponse);
    if (serverHover && serverHover.contents) {
      contents = contents.concat(serverHover.contents);
      range = serverHover.range;
    }

    return new Hover(contents, range);
  }
Example #25
Source File: hoverHelper.ts    From coffeesense with MIT License 5 votes vote down vote up
function markedStringToSTring(s: MarkdownString | MarkedString) {
  return typeof s === 'string' ? s : s.value;
}
Example #26
Source File: document-generator.ts    From element-ui-helper with MIT License 5 votes vote down vote up
/**
   * 生成插槽文档表格
   *
   * @template T type extends BaseDocument
   * @param {T} document 文档 具体标签对应的文档
   * @param {string} tag 标签
   * @param {string} attribute 属性 在标签的属性上悬停时具有
   * @param {string} language 语言
   * @return {*}  {MarkdownString}
   * @memberof HoverDocumentGenerator
   */
  private generateSlots<T extends BaseDocument>(document: T, tag: string, attribute: string, language: string): MarkdownString {
    let isUndefined: boolean = true // 标记是否具有文档
    let markdownString: MarkdownString = new MarkdownString('', true)
    const slots = document.slots || []
    if (slots.length) {
      if (language === 'zh-CN') {
        markdownString.appendMarkdown(`### ${tag} 插槽\r`)
        markdownString.appendMarkdown('| 插槽 | 说明 |\r')
      } else {
        markdownString.appendMarkdown(`### ${tag} Slot\r`)
        markdownString.appendMarkdown('| Slot | Description |\r')
      }
      markdownString.appendMarkdown('|---|---|\r')
    }
    if (attribute.length === 0) {
      // 属性 和标签一样 显示全部
      slots.forEach((row: DocumentSlot) => {
        markdownString.appendMarkdown(`|${row.name}|${row.description}|\r`)
        isUndefined = false
      })
    } else {
      // 属性和标签不一样 显示标签下的某个属性的信息
      const row = slots.find((row: DocumentSlot) => row.name === attribute)
      if (row) {
        markdownString.appendMarkdown(`|${row.name}|${row.description}|\r`)
        isUndefined = false
      }
    }
    if (isUndefined) {
      markdownString = new MarkdownString('', true)
    }
    return markdownString
  }
Example #27
Source File: document-generator.ts    From element-ui-helper with MIT License 5 votes vote down vote up
/**
   * 生成局部插槽文档表格
   *
   * @template T type extends BaseDocument
   * @param {T} document 文档 具体标签对应的文档
   * @param {string} tag 标签
   * @param {string} attribute 属性 在标签的属性上悬停时具有
   * @param {string} language 语言
   * @return {*}  {MarkdownString}
   * @memberof HoverDocumentGenerator
   */
  private generateScopedSlots<T extends BaseDocument>(document: T, tag: string, attribute: string, language: string): MarkdownString {
    let isUndefined: boolean = true // 标记是否具有文档
    let markdownString: MarkdownString = new MarkdownString('', true)
    const scopedSlots = document.scopedSlots || []
    if (scopedSlots.length) {
      if (language === 'zh-CN') {
        markdownString.appendMarkdown(`### ${tag} 插槽\r`)
        markdownString.appendMarkdown('| 插槽 | 说明 |\r')
      } else {
        markdownString.appendMarkdown(`### ${tag} Slot\r`)
        markdownString.appendMarkdown('| Slot | Description |\r')
      }
      markdownString.appendMarkdown('|---|---|\r')
    }
    if (attribute.length === 0) {
      // 属性 和标签一样 显示全部
      scopedSlots.forEach((row: DocumentScopedSlot) => {
        markdownString.appendMarkdown(`|${row.name}|${row.description}|\r`)
        isUndefined = false
      })
    } else {
      // 属性和标签不一样 显示标签下的某个属性的信息
      const row = scopedSlots.find((row: DocumentScopedSlot) => row.name === attribute)
      if (row) {
        markdownString.appendMarkdown(`|${row.name}|${row.description}|\r`)
        isUndefined = false
      }
    }
    if (isUndefined) {
      markdownString = new MarkdownString('', true)
    }
    return markdownString
  }
Example #28
Source File: completionProvider.ts    From dendron with GNU Affero General Public License v3.0 5 votes vote down vote up
resolveCompletionItem = sentryReportingCallback(
  async (
    item: CompletionItem,
    token: CancellationToken
  ): Promise<CompletionItem | undefined> => {
    const ctx = "resolveCompletionItem";
    const { label: fname, detail: vname } = item;
    if (
      !_.isString(fname) ||
      !_.isString(vname) ||
      token.isCancellationRequested
    )
      return;

    const engine = ExtensionProvider.getEngine();
    const { vaults, wsRoot } = engine;
    const vault = VaultUtils.getVaultByName({ vname, vaults });
    if (_.isUndefined(vault)) {
      Logger.info({ ctx, msg: "vault not found", fname, vault, wsRoot });
      return;
    }

    const note = NoteUtils.getNoteByFnameFromEngine({
      fname,
      vault,
      engine,
    });

    if (_.isUndefined(note)) {
      Logger.info({ ctx, msg: "note not found", fname, vault, wsRoot });
      return;
    }

    try {
      // Render a preview of this note
      const proc = MDUtilsV5.procRemarkFull(
        {
          dest: DendronASTDest.MD_REGULAR,
          engine,
          vault: note.vault,
          fname: note.fname,
        },
        {
          flavor: ProcFlavor.HOVER_PREVIEW,
        }
      );
      const rendered = await proc.process(
        `![[${VaultUtils.toURIPrefix(note.vault)}/${note.fname}]]`
      );
      if (token.isCancellationRequested) return;
      item.documentation = new MarkdownString(rendered.toString());
      Logger.debug({ ctx, msg: "rendered note" });
    } catch (err) {
      // Failed creating preview of the note
      Logger.info({ ctx, err, msg: "failed to render note" });
      return;
    }

    return item;
  }
)
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;
    }
  }