vscode#SnippetString TypeScript Examples

The following examples show how to use vscode#SnippetString. 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: 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 #2
Source File: ALDocCommentProvider.ts    From vscode-alxmldocumentation with MIT License 6 votes vote down vote up
/**
     * Add Completion Item for class XML Documentation snippet.
     * @param alProcedure ALProcedure to document.
     */
    private AddXmlDocCompletionItem(alProcedure: ALProcedure) {
        const completionItem: CompletionItem = new CompletionItem(
            'AL XML Documentation Comment',
            CompletionItemKind.Text
        );

        let snippetText: string = ALDocCommentUtil.GetProcedureDocumentation(alProcedure);

        const snippet: SnippetString = new SnippetString(snippetText.replace('///', '')); // delete leading '///'. The trigger character is already in the document when the completion provider is triggered.
        completionItem.insertText = snippet;
        completionItem.documentation = snippetText;
        completionItem.detail = 'XML documentation comment to document AL procedures.';
        completionItem.sortText = '1';

        this.alXmlDocCompletionItems.push(completionItem);
    }
Example #3
Source File: ALDocCommentProvider.ts    From vscode-alxmldocumentation with MIT License 6 votes vote down vote up
/**
     * Add Completion Item for copying XML Documentation from Interface Procedure.
     * @param inheritObjLocation Location of Interface Object.
     * @param alProcedure AL Procedure to document.
     */
    private async AddXmlDocFromInterfaceCompletionItem(inheritObjLocation: Location[], alProcedure: ALProcedure) {
        try {
            const alLangServer = new ALLangServerProxy();
            const alDefinition = await alLangServer.GetALObjectFromDefinition(inheritObjLocation[0].uri.toString(), inheritObjLocation[0].range.start);
            if ((alDefinition !== undefined) && (alDefinition.ALObject !== null)) {
                let inheritALProcedure: ALProcedure | undefined = alDefinition.ALObject.Procedures?.find(inheritALProcedure => (inheritALProcedure.Code === alProcedure?.Code));
                if (inheritALProcedure !== undefined) {

                    const inheritCompletionItem2: CompletionItem = new CompletionItem(
                        'AL XML Documentation Interface Comment',
                        CompletionItemKind.Text
                    );

                    let snippetText: string = ALDocCommentUtil.GetProcedureDocumentation(inheritALProcedure);

                    const snippet: SnippetString = new SnippetString(snippetText.replace('///', '')); // delete leading '///'. The trigger character is already in the document when the completion provider is triggered.
                    inheritCompletionItem2.insertText = snippet;
                    inheritCompletionItem2.documentation = snippetText;
                    inheritCompletionItem2.detail = 'XML documentation interface comment.';
                    inheritCompletionItem2.sortText = '1';

                    this.alXmlDocCompletionItems.push(inheritCompletionItem2);
                }
            }
        } catch(ex) {
            console.error(`[AddXmlDocFromInterfaceCompletionItem] - ${ex} Please report this error at https://github.com/365businessdev/vscode-alxmldocumentation/issues`);
            return undefined;
        }

    }
Example #4
Source File: ALDocCommentProvider.ts    From vscode-alxmldocumentation with MIT License 6 votes vote down vote up
/**
     * Add Completion Item for "inheritdoc" XML Comment.
     * @param alObject ALObject.
     * @param alProcedure AL Procedure to document.
     */
    private AddInheritXmlDocCompletionItem(alObject: ALObject, alProcedure: ALProcedure) {
        const inheritCompletionItem: CompletionItem = new CompletionItem(
            'Inherit AL XML Documentation Comment',
            CompletionItemKind.Text
        );

        inheritCompletionItem.detail = 'XML documentation comment to document inherit AL procedures.';
        let snippetText: string = `/// <inheritdoc cref="${alProcedure.Code}"/>`;
        const snippet: SnippetString = new SnippetString(snippetText.replace('///', '')); // delete leading '///'. The trigger character is already in the document when the completion provider is triggered.
        inheritCompletionItem.insertText = snippet;
        inheritCompletionItem.documentation = snippetText;
        inheritCompletionItem.sortText = '1';
        this.alXmlDocCompletionItems.push(inheritCompletionItem);
    }
Example #5
Source File: ALDocCommentProvider.ts    From vscode-alxmldocumentation with MIT License 6 votes vote down vote up
/**
     * Provide XML Documentation Completion Items for AL Object.
     * @param alObject ALObject.
     */
    private ProvideALObjectCompletionItems(alObject: ALObject) {               
        const completionItem: CompletionItem = new CompletionItem(
            'AL XML Documentation Comment',
            CompletionItemKind.Text
        );

        let snippetText: string = ALDocCommentUtil.GetObjectDocumentation(alObject);
        const snippet: SnippetString = new SnippetString(snippetText.replace('///', '')); // delete leading '///'. The trigger character is already in the document when the completion provider is triggered.
        completionItem.insertText = snippet;

        completionItem.detail = 'XML documentation comment to document AL objects.';
        completionItem.documentation = snippetText;
        completionItem.sortText = '1';

        this.alXmlDocCompletionItems.push(completionItem);

        return this.alXmlDocCompletionItems;
    }
Example #6
Source File: ALFixDocumentation.ts    From vscode-alxmldocumentation with MIT License 6 votes vote down vote up
/**
     * Add missing XML documentation for AL procedure.
     * @param editor {TextEditor}
     * @param alProcedure {ALProcedure}
     */
    public static FixObjectDocumentation(editor: TextEditor | undefined, alObject: ALObject) {
        if (editor === undefined) {
            return;
        }

        editor.insertSnippet(new SnippetString(
            `${ALDocCommentUtil.GetObjectDocumentation(alObject)}\r\n`),
            new Position(alObject.LineNo, ALDocCommentUtil.GetLineStartPosition(editor.document, alObject.LineNo))
        );
    }
Example #7
Source File: ALFixDocumentation.ts    From vscode-alxmldocumentation with MIT License 6 votes vote down vote up
/**
     * Add missing XML documentation for AL procedure.
     * @param editor {TextEditor}
     * @param alProcedure {ALProcedure}
     */
    public static FixDocumentation(editor: TextEditor | undefined, alProcedure: ALProcedure) {
        if (editor === undefined) {
            return;
        }

        let lineNo = this.FindLineNoToStartDocumentation(editor, alProcedure);

        editor.insertSnippet(new SnippetString(
            `${ALDocCommentUtil.GetProcedureDocumentation(alProcedure)}\r\n`),
            new Position(lineNo, ALDocCommentUtil.GetLineStartPosition(editor.document, lineNo))
        );
    }
Example #8
Source File: ALFixDocumentation.ts    From vscode-alxmldocumentation with MIT License 6 votes vote down vote up
/**
     * Add missing Summary XML documentation for AL procedure.
     * @param editor {TextEditor}
     * @param alProcedure {ALProcedure}
     */
    public static FixSummaryDocumentation(editor: TextEditor | undefined, alProcedure: ALProcedure) {
        if (editor === undefined) {
            return;
        }

        let lineNo = this.FindLineNoToStartDocumentation(editor, alProcedure);
        
        editor.insertSnippet(new SnippetString(
            `/// ${alProcedure.ALDocumentation.Documentation.replace('__idx__', '1').split('\r\n').join('\r\n/// ')}\r\n`),
            new Position(lineNo, ALDocCommentUtil.GetLineStartPosition(editor.document, lineNo))
        );
    }
Example #9
Source File: ALFixDocumentation.ts    From vscode-alxmldocumentation with MIT License 6 votes vote down vote up
public static FixReturnTypeDocumentation(editor: TextEditor | undefined, alProcedure: ALProcedure) {
        if (editor === undefined) {
            return;
        }

        if (!alProcedure.Return) {
            return;
        }

        let lineNo = this.FindLineNoToStartDocumentation(editor, alProcedure, false);
        
        editor.insertSnippet(new SnippetString(
            `/// ${alProcedure.Return.ALDocumentation.Documentation.replace('__idx__', '1').split('\r\n').join('\r\n/// ')}\r\n`),
            new Position(lineNo, ALDocCommentUtil.GetLineStartPosition(editor.document, lineNo))
        );
    }
Example #10
Source File: completionProvider.ts    From vscode-autohotkey with MIT License 6 votes vote down vote up
public async provideCompletionItems(document: vscode.TextDocument, position: vscode.Position): Promise<vscode.CompletionItem[] | vscode.CompletionList> {

        const prePostion = position.character === 0 ? position : new vscode.Position(position.line, position.character - 1);
        const preChart = position.character === 0 ? null : document.getText(new vscode.Range(prePostion, position));
        if (preChart == ".") {
            return []
        }

        const result: vscode.CompletionItem[] = [];

        (await Parser.getAllMethod()).forEach((method) => {
            const completionItem = new vscode.CompletionItem(method.params.length == 0 ? method.name : method.full, vscode.CompletionItemKind.Method);
            if (method.params.length == 0) {
                completionItem.insertText = method.name + "()"
            } else {
                completionItem.insertText = new SnippetString(method.name + "($1)")
            }
            completionItem.detail = method.comment;
            result.push(completionItem);
            if (method.document == document && position.line >= method.line && position.line <= method.endLine) {
                for (const param of method.params) {
                    result.push(new vscode.CompletionItem(param, vscode.CompletionItemKind.Variable));
                }
                for (const variable of method.variables) {
                    result.push(new vscode.CompletionItem(variable.name, vscode.CompletionItemKind.Variable));
                }
            }
        });

        const script = (await Parser.buildScript(document, true));
        script.variables.forEach((variable) => {
            const completionItem = new vscode.CompletionItem(variable.name, vscode.CompletionItemKind.Variable);
            result.push(completionItem);
        });

        return this.keywordComplectionItems.concat(result);
    }
Example #11
Source File: element-completion-item-povider.ts    From element-ui-helper with MIT License 6 votes vote down vote up
/**
   * 获取标签提示
   */
  getTagCompletionItems(tag: string): CompletionItem[] {
    let completionItems: CompletionItem[] = []
    const config = workspace.getConfiguration().get<ExtensionConfigutation>('element-ui-helper')
    const language = config?.language || ExtensionLanguage.cn
    const preText = this.getTextBeforePosition(this._position)
    const document: Record<string, any> = localDocument[language]
    Object.keys(document).forEach((key) => {
      const start = preText.lastIndexOf('<') + 1
      const end = preText.length - start + 1
      const startPos = new Position(this._position.line, start)
      const endPos = new Position(this._position.line, end)
      const range = new Range(startPos, endPos)
      completionItems.push({
        label: `${key}`,
        sortText: `0${key}`,
        detail: 'ElementUI Tag',
        kind: CompletionItemKind.Value,
        insertText: new SnippetString().appendText(`${key}`).appendTabstop().appendText('>').appendTabstop().appendText(`</${key}>`),
        range
      })
    })
    return completionItems
  }
Example #12
Source File: spDocCompletions.ts    From sourcepawn-vscode with MIT License 6 votes vote down vote up
constructor(position: Position, FunctionDesc: string[], indent: string) {
    super("/** */", CompletionItemKind.Text);
    let snippet = new SnippetString();
    let max = getMaxLength(FunctionDesc);
    snippet.appendText(`${indent}/**\n ${indent}* `);
    snippet.appendPlaceholder("Description");
    this.appendTextSnippet(snippet, "", indent);
    for (let arg of FunctionDesc) {
      this.appendTextSnippet(
        snippet,
        "@param " + arg + " ".repeat(getSpaceLength(arg, max)),
        indent
      );
      snippet.appendPlaceholder("Param description");
    }
    this.appendTextSnippet(
      snippet,
      "@return " + " ".repeat(getSpaceLengthReturn(max)),
      indent
    );
    snippet.appendPlaceholder("Return description");
    snippet.appendText(`\n${indent}`);
    this.insertText = snippet;
    let start: Position = new Position(position.line, 0);
    let end: Position = new Position(position.line, 0);
    this.range = new Range(start, end);
  }
Example #13
Source File: InsertNoteCommand.ts    From dendron with GNU Affero General Public License v3.0 6 votes vote down vote up
async execute(opts: CommandOpts) {
    const ctx = "InsertNoteCommand";
    opts = _.defaults(opts, { closeAndOpenFile: true });
    Logger.info({ ctx, opts });
    const templates = opts.picks.map((pick) => {
      return pick.body;
    });
    const txt = templates.join("\n");
    const snippet = new SnippetString(txt);
    const editor = VSCodeUtils.getActiveTextEditor()!;
    const pos = editor.selection.active;
    const selection = new Selection(pos, pos);
    await editor.insertSnippet(snippet, selection);
    AnalyticsUtils.track(ExtensionEvents.DeprecationNoticeShow, {
      source: DENDRON_COMMANDS.INSERT_NOTE.key,
    });
    window
      .showWarningMessage(
        "Heads up that InsertNote is being deprecated and will be replaced with the 'Apply Template' command",
        "See whats changed"
      )
      .then((resp) => {
        if (resp === "See whats changed") {
          AnalyticsUtils.track(ExtensionEvents.DeprecationNoticeAccept, {
            source: DENDRON_COMMANDS.INSERT_NOTE.key,
          });
          VSCodeUtils.openLink(
            "https://wiki.dendron.so/notes/ftohqknticu6bw4cfmzskq6"
          );
        }
      });
    return txt;
  }
Example #14
Source File: ALFixDocumentation.ts    From vscode-alxmldocumentation with MIT License 5 votes vote down vote up
/**
     * Add missing Summary XML documentation for AL procedure.
     * @param editor {TextEditor}
     * @param alProcedure {ALProcedure}
     */
    public static FixParameterDocumentation(editor: TextEditor | undefined, alProcedure: ALProcedure) {
        if (editor === undefined) {
            return;
        }

        let placeholderIdx = 1;
        let documentation: string = ALDocCommentUtil.GenerateProcedureDocString(alProcedure, placeholderIdx);
        alProcedure.Parameters?.forEach(alParameter => {
            placeholderIdx++;
            documentation += ALDocCommentUtil.GenerateParameterDocString(alParameter, placeholderIdx);
        });
        let jsonDocumentation = ALDocCommentUtil.GetJsonFromALDocumentation(documentation);
        let parameters: { alParameter: ALParameter | undefined; documentation: string; insertAtLineNo: number }[] = [];
        if (jsonDocumentation.param.length === undefined) {
            parameters.push({
                alParameter: alProcedure.Parameters!.find(alParameter => (alParameter.Name === jsonDocumentation.param.attr.name)),
                documentation: jsonDocumentation.param.value,
                insertAtLineNo: ALDocCommentUtil.GetALDocumentationNodeLineNo(editor, alProcedure.LineNo, 'param', 'name', jsonDocumentation.param.attr.name)
            });
        } else {
            jsonDocumentation.param.forEach((param: { attr: { name: string; }; value: string; }) => {
                parameters.push({
                    alParameter: alProcedure.Parameters!.find(alParameter => (alParameter.Name === param.attr.name)),
                    documentation: param.value,
                    insertAtLineNo: ALDocCommentUtil.GetALDocumentationNodeLineNo(editor, alProcedure.LineNo, 'param', 'name', param.attr.name)
                });
            });
        }

        let i = 0;
        let j = 0;
        parameters.forEach(parameter => {
            if (parameter.insertAtLineNo === -1) {
                if ((i === 0) || (parameters[i-1].insertAtLineNo === -1)) {
                    parameter.insertAtLineNo = ALDocCommentUtil.GetALDocumentationNodeLineNo(editor, alProcedure.LineNo, 'summary');
                } else {
                    parameter.insertAtLineNo = parameters[i-1].insertAtLineNo + j;
                }
                if (parameter.alParameter !== undefined) {
                    editor.insertSnippet(new SnippetString(`/// ${ALDocCommentUtil.GenerateParameterDocString(parameter.alParameter, i)}\r\n`), 
                        new Position(parameter.insertAtLineNo, ALDocCommentUtil.GetLineStartPosition(editor.document, parameter.insertAtLineNo)));
                }
                j++;
            }
            i++;
        });
    }
Example #15
Source File: spDocCompletions.ts    From sourcepawn-vscode with MIT License 5 votes vote down vote up
private appendTextSnippet(
    snippet: SnippetString,
    text: string,
    indent: string
  ): void {
    snippet.appendText(`\n${indent} * ${text}`);
  }
Example #16
Source File: autoClose.ts    From language-tools with MIT License 4 votes vote down vote up
export function activateTagClosing(
    tagProvider: (document: TextDocument, position: Position) => Thenable<string>,
    supportedLanguages: { [id: string]: boolean },
    configName: string
): Disposable {
    const disposables: Disposable[] = [];
    workspace.onDidChangeTextDocument(
        (event) => onDidChangeTextDocument(event.document, event.contentChanges),
        null,
        disposables
    );

    let isEnabled = false;
    updateEnabledState();
    window.onDidChangeActiveTextEditor(updateEnabledState, null, disposables);

    let timeout: NodeJS.Timer | undefined = void 0;

    function updateEnabledState() {
        isEnabled = false;
        const editor = window.activeTextEditor;
        if (!editor) {
            return;
        }
        const document = editor.document;
        if (!supportedLanguages[document.languageId]) {
            return;
        }
        if (!workspace.getConfiguration(void 0, document.uri).get<boolean>(configName)) {
            return;
        }
        isEnabled = true;
    }

    function onDidChangeTextDocument(
        document: TextDocument,
        changes: readonly TextDocumentContentChangeEvent[]
    ) {
        if (!isEnabled) {
            return;
        }
        const activeDocument = window.activeTextEditor && window.activeTextEditor.document;
        if (document !== activeDocument || changes.length === 0) {
            return;
        }
        if (typeof timeout !== 'undefined') {
            clearTimeout(timeout);
        }
        const lastChange = changes[changes.length - 1];
        const lastCharacter = lastChange.text[lastChange.text.length - 1];
        if (
            ('range' in lastChange && (lastChange.rangeLength ?? 0) > 0) ||
            (lastCharacter !== '>' && lastCharacter !== '/')
        ) {
            return;
        }
        const rangeStart =
            'range' in lastChange
                ? lastChange.range.start
                : new Position(0, document.getText().length);
        const version = document.version;
        timeout = setTimeout(() => {
            const position = new Position(
                rangeStart.line,
                rangeStart.character + lastChange.text.length
            );
            tagProvider(document, position).then((text) => {
                if (text && isEnabled) {
                    const activeEditor = window.activeTextEditor;
                    if (activeEditor) {
                        const activeDocument = activeEditor.document;
                        if (document === activeDocument && activeDocument.version === version) {
                            const selections = activeEditor.selections;
                            if (
                                selections.length &&
                                selections.some((s) => s.active.isEqual(position))
                            ) {
                                activeEditor.insertSnippet(
                                    new SnippetString(text),
                                    selections.map((s) => s.active)
                                );
                            } else {
                                activeEditor.insertSnippet(new SnippetString(text), position);
                            }
                        }
                    }
                }
            });
            timeout = void 0;
        }, 100);
    }
    return Disposable.from(...disposables);
}