VS C Реализация форматтера не влияет - PullRequest
0 голосов
/ 12 июля 2020

Тип проблемы: Ошибка

  • Запуск расширения
  • Щелкните правой кнопкой мыши файл переформатирования (файл .items из openhab)

Версия VS Code: Code 1.47.0 Версия ОС: Darwin x64 19.5.0

Привет, ребята,

В следующей реализации ничего не происходит при сохранении файла (форматирование при сохранении включено) или при переформатировании файла с помощью правой кнопки мыши. Я пробовал много других решений, но ни одно из них не помогло. Надеюсь, вы сможете мне помочь.

export function activate(context: vscode.ExtensionContext) {
    vscode.languages.registerDocumentFormattingEditProvider("openhab", {
        provideDocumentFormattingEdits(document: vscode.TextDocument, options: vscode.FormattingOptions): vscode.TextEdit[] {
            var range = getDocumentRange(document);
            var content = document.getText(range);
            var result: vscode.TextEdit[] = [];
            var formatted = formatItemFile();
            //if (formatted) {
            //  result.push(new vscode.TextEdit(range, formatted));
            //}
            return formatted;
        },
    });
}
export function formatItemFile(): vscode.TextEdit[] {
    var result: vscode.TextEdit[] = [];
    // Get the section lengths of each line with an item in it.
    // Only execute if there's an active text editor
    if (!vscode.window.activeTextEditor) {
        return result;
    }

    // Define the basic vscode variables
    let doc = vscode.window.activeTextEditor.document;
    let editor = vscode.window.activeTextEditor;
    let currentPos = editor.selection.active;
    let newPos: vscode.Position;
    let itemArray: Array<Item>;
    itemArray = new Array();

    // Get the format configuration settings
    let config = vscode.workspace.getConfiguration("oh-alignment-tool");
    let preserveWhitespace = config.preserveWhitespace;

    // Reset the comment tracker
    isInBlockComment = false;

    // Clear the file in case of line-by-line item definitions
    for (let index = 0; index < doc.lineCount; index++) {
        // Get Position at the beginning of the current line and start a selection
        newPos = currentPos.with(index, 0);
        editor.selection = new vscode.Selection(newPos, newPos);

        // Get Text of current line and check if there is a comment in it
        let lineText = doc.lineAt(newPos.line);
        var comment = doc.getWordRangeAtPosition(newPos.with(newPos.line, 0), REGEX_COMMENT);
        var blockComment = doc.getWordRangeAtPosition(newPos.with(newPos.line, 0), REGEX_START_BLOCKCOMMENT);
        var endBlockComment = doc.getWordRangeAtPosition(newPos.with(newPos.line, 0), REGEX_END_BLOCKCOMMENT);

        // If line is empty or contains a comment continue to the next line
        if (lineText.text.length === 0 || lineText.isEmptyOrWhitespace) {
            continue;
        } else if (comment) {
            continue;
        } else if (blockComment && endBlockComment) {
            isInBlockComment = false;
            continue;
        } else if (blockComment) {
            isInBlockComment = true;
            continue;
        } else if (endBlockComment) {
            isInBlockComment = false;
            continue;
        } else if (isInBlockComment) {
            continue;
        }

        // Default these to empty. They will be changed
        // if they exist in the item definition
        let itemType = "";
        let itemName = "";
        let itemLabel = "";
        let itemIcon = "";
        let itemGroup = "";
        let itemTag = "";
        let itemChannel = "";
        let itemComment = "";

        // Check if there is leading Whitespace. If Yes add one in size of a tab.
        let leadingWhiteSpace = lineText.firstNonWhitespaceCharacterIndex;

        if (preserveWhitespace === false) {
            leadingWhiteSpace = 0;
        }

        // Discover item Type
        // Count Whitespace or tabs at the begin of the line
        newPos = newPos.with(newPos.line, newPos.character + utils.countWhitespace(doc, newPos));
        var wordRange = doc.getWordRangeAtPosition(newPos, REGEX_ITEM_TYPE);
        if (wordRange && wordRange.isSingleLine) {
            itemType = doc.getText(wordRange);
            highestTypeLength = itemType.length > highestTypeLength ? itemType.length : highestTypeLength;
            newPos = newPos.with(newPos.line, newPos.character + itemType.length);
            newPos = newPos.with(newPos.line, newPos.character + utils.countWhitespace(doc, newPos));

            // Discover item Name
            var itemNameRange = doc.getWordRangeAtPosition(newPos, REGEX_ITEM_NAME);
            if (itemNameRange && itemNameRange.isSingleLine) {
                itemName = doc.getText(itemNameRange);
                highestNameLength = itemName.length > highestNameLength ? itemName.length : highestNameLength;
                newPos = newPos.with(newPos.line, newPos.character + itemName.length);
                newPos = newPos.with(newPos.line, newPos.character + utils.countWhitespace(doc, newPos));
            }
        }
        // Must have a type and name to continue
        if (itemType.length === 0 || itemName.length === 0) {
            continue;
        }
        // Discover item Label
        let itemLabelRange = doc.getWordRangeAtPosition(newPos, REGEX_ITEM_LABEL);
        if (itemLabelRange && itemLabelRange.isSingleLine) {
            itemLabel = doc.getText(itemLabelRange);
            highestLabelLength = itemLabel.length > highestLabelLength ? itemLabel.length : highestLabelLength;
            newPos = newPos.with(newPos.line, newPos.character + itemLabel.length);
            newPos = newPos.with(newPos.line, newPos.character + utils.countWhitespace(doc, newPos));
        }
        // Discover item Icon
        let itemIconRange = doc.getWordRangeAtPosition(newPos, REGEX_ITEM_ICON);
        if (itemIconRange && itemIconRange.isSingleLine) {
            itemIcon = doc.getText(itemIconRange);
            highestIconLength = itemIcon.length > highestIconLength ? itemIcon.length : highestIconLength;
            newPos = newPos.with(newPos.line, newPos.character + itemIcon.length);
            newPos = newPos.with(newPos.line, newPos.character + utils.countWhitespace(doc, newPos));
        }
        // Discover item Group
        let itemGroupRange = doc.getWordRangeAtPosition(newPos, REGEX_ITEM_GROUP);
        if (itemGroupRange && itemGroupRange.isSingleLine) {
            itemGroup = doc.getText(itemGroupRange);
            highestGroupLength = itemGroup.length > highestGroupLength ? itemGroup.length : highestGroupLength;
            newPos = newPos.with(newPos.line, newPos.character + itemGroup.length);
            newPos = newPos.with(newPos.line, newPos.character + utils.countWhitespace(doc, newPos));
        }
        // Discover item Tag
        let itemTagRange = doc.getWordRangeAtPosition(newPos, REGEX_ITEM_TAG);
        if (itemTagRange && itemTagRange.isSingleLine) {
            itemTag = doc.getText(itemTagRange);
            highestTagLength = itemTag.length > highestTagLength ? itemTag.length : highestTagLength;
            //console.log("Tag: " + itemTag);
            newPos = newPos.with(newPos.line, newPos.character + itemTag.length);
            newPos = newPos.with(newPos.line, newPos.character + utils.countWhitespace(doc, newPos));
        }
        // Discover item Channel
        let itemChannelRange = doc.getWordRangeAtPosition(newPos, REGEX_ITEM_CHANNEL);
        if (itemChannelRange && itemChannelRange.isSingleLine) {
            itemChannel = doc.getText(itemChannelRange);
            highestChannelLength = itemChannel.length > highestChannelLength ? itemChannel.length : highestChannelLength;
            newPos = newPos.with(newPos.line, newPos.character + itemChannel.length);
            newPos = newPos.with(newPos.line, newPos.character + utils.countWhitespace(doc, newPos));
        }
        // Discover comment at end of line
        let itemCommentRange = doc.getWordRangeAtPosition(newPos, REGEX_EOL_COMMENT);
        if (itemCommentRange && itemCommentRange.isSingleLine) {
            itemComment = doc.getText(itemCommentRange);
            newPos = newPos.with(newPos.line, newPos.character + itemComment.length);
            newPos = newPos.with(newPos.line, newPos.character + utils.countWhitespace(doc, newPos));
        }

        // Add the new item to the itemArray
        itemArray.push(new Item(index, leadingWhiteSpace, itemType, itemName, itemLabel, itemIcon, itemGroup, itemTag, itemChannel, itemComment));
    }

    // Convert the column lengths to tabs
    highestTypeLength = utils.generateTabFromSpaces(highestTypeLength);
    highestNameLength = utils.generateTabFromSpaces(highestNameLength);
    highestLabelLength = utils.generateTabFromSpaces(highestLabelLength);
    highestIconLength = utils.generateTabFromSpaces(highestIconLength);
    highestGroupLength = utils.generateTabFromSpaces(highestGroupLength);
    highestTagLength = utils.generateTabFromSpaces(highestTagLength);
    highestChannelLength = utils.generateTabFromSpaces(highestChannelLength);

    // Insert the newly formatted items
    itemArray.forEach(function (item) {
        newPos = currentPos.with(item.line, 0);
        editor.selection = new vscode.Selection(newPos, newPos);
        let reformattedItem = formatItem(item);
        if (reformattedItem !== "") {
            let selection = new vscode.Range(newPos, newPos.with(newPos.line, doc.lineAt(newPos.line).text.length));
            result.push(new vscode.TextEdit(selection, reformattedItem));
        }
    });

    // Apply all    clean and formatting Edits
    //textWorkEdit.set(doc.uri, textTextEdits);
    //await vscode.workspace.applyEdit(textWorkEdit);

    return result;
}
...