All files / helpers list-commands.ts

40.67% Statements 48/118
43.47% Branches 20/46
60% Functions 3/5
40.35% Lines 46/114

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271    2x 13x     2x                                                                                                                                                               2x                                                                                                                                                         11x 11x 11x 11x 11x     11x 2x     9x   9x   8x   8x 4x 4x 1x         7x     7x   1x               1x       6x 6x   6x               6x       13x 13x 13x     13x 13x     13x 2x       11x   11x     2x 2x 2x     2x   2x     1x     1x     1x 1x       2x               2x    
import { EditorView } from '@codemirror/view';
 
export function continueLists(view: EditorView): boolean {
    return handleQuoteContinuation(view) || handleListContinuation(view);
}
 
export function increaseListIndent(view: EditorView): boolean {
    const { state } = view;
    const { doc } = state;
    const selection = state.selection;
 
    // Проверяем, есть ли выделение
    if (selection.ranges.length > 0) {
        // Получаем диапазон строк, затронутых выделением
        const startLine = doc.lineAt(selection.main.from);
        const endLine = doc.lineAt(selection.main.to);
 
        // Если выделение охватывает несколько строк
        if (startLine.number !== endLine.number) {
            const changes = [];
            let affectedLines = false;
 
            // Проходим по всем строкам в выделении
            for (let i = startLine.number; i <= endLine.number; i++) {
                const line = doc.line(i);
                const lineContent = line.text;
 
                // Проверяем, является ли строка элементом списка
                const listPrefixMatch = lineContent.match(/^([*#]+)(\s*)/);
 
                if (listPrefixMatch) {
                    affectedLines = true;
                    const currentPrefix = listPrefixMatch[1];
                    // Используем последний символ префикса вместо первого
                    const lastChar = currentPrefix[currentPrefix.length - 1];
                    const newPrefix = currentPrefix + lastChar;
                    const spaceAfter = listPrefixMatch[2];
 
                    changes.push({
                        from: line.from,
                        to: line.from + listPrefixMatch[0].length,
                        insert: newPrefix + spaceAfter,
                    });
                }
            }
 
            if (affectedLines) {
                view.dispatch({ changes });
                return true;
            }
        }
    }
 
    // Обработка одной строки (как раньше)
    const { head } = selection.main;
 
    // Получаем текущую строку
    const line = doc.lineAt(head);
    const lineContent = line.text;
 
    // Проверяем, начинается ли строка с маркера списка (* или #)
    const listPrefixMatch = lineContent.match(/^([*#]+)(\s*)/);
 
    if (listPrefixMatch) {
        // Увеличиваем уровень вложенности, добавляя один символ в начало
        // Используем последний символ из текущего префикса
        const currentPrefix = listPrefixMatch[1]; // Текущие символы * и #
        const lastChar = currentPrefix[currentPrefix.length - 1]; // Последний символ
        const newPrefix = currentPrefix + lastChar; // Добавляем один символ того же типа
        const spaceAfter = listPrefixMatch[2]; // Сохраняем пробелы после префикса
 
        // Заменяем старый префикс на новый
        view.dispatch({
            changes: {
                from: line.from,
                to: line.from + listPrefixMatch[0].length,
                insert: newPrefix + spaceAfter,
            },
        });
 
        return true;
    }
 
    return false;
}
 
export function decreaseListIndent(view: EditorView): boolean {
    const { state } = view;
    const { doc } = state;
    const selection = state.selection;
 
    // Проверяем, есть ли выделение
    if (selection.ranges.length > 0) {
        // Получаем диапазон строк, затронутых выделением
        const startLine = doc.lineAt(selection.main.from);
        const endLine = doc.lineAt(selection.main.to);
 
        // Если выделение охватывает несколько строк
        if (startLine.number !== endLine.number) {
            const changes = [];
            let affectedLines = false;
 
            // Проходим по всем строкам в выделении
            for (let i = startLine.number; i <= endLine.number; i++) {
                const line = doc.line(i);
                const lineContent = line.text;
 
                // Проверяем, является ли строка элементом списка с вложенностью > 1
                const listPrefixMatch = lineContent.match(/^([*#]+)(\s*)/);
 
                if (listPrefixMatch && listPrefixMatch[1].length > 1) {
                    affectedLines = true;
                    const currentPrefix = listPrefixMatch[1];
                    const newPrefix = currentPrefix.slice(0, -1); // Удаляем последний символ
                    const spaceAfter = listPrefixMatch[2];
 
                    changes.push({
                        from: line.from,
                        to: line.from + listPrefixMatch[0].length,
                        insert: newPrefix + spaceAfter,
                    });
                }
            }
 
            if (affectedLines) {
                view.dispatch({ changes });
                return true;
            }
        }
    }
 
    // Обработка одной строки (как раньше)
    const { head } = selection.main;
 
    // Получаем текущую строку
    const line = doc.lineAt(head);
    const lineContent = line.text;
 
    // Проверяем, начинается ли строка с маркера списка (* или #)
    const listPrefixMatch = lineContent.match(/^([*#]+)(\s*)/);
 
    if (listPrefixMatch && listPrefixMatch[1].length > 1) {
        // Уменьшаем уровень вложенности, удаляя один символ из начала
        const currentPrefix = listPrefixMatch[1];
        const newPrefix = currentPrefix.slice(0, -1); // Удаляем последний символ
        const spaceAfter = listPrefixMatch[2]; // Сохраняем пробелы после префикса
 
        // Заменяем старый префикс на новый
        view.dispatch({
            changes: {
                from: line.from,
                to: line.from + listPrefixMatch[0].length,
                insert: newPrefix + spaceAfter,
            },
        });
 
        return true;
    }
 
    return false;
}
 
function handleListContinuation(view: EditorView): boolean {
    const { state } = view;
    const { doc } = state;
    const head = state.selection.main.head;
    const line = doc.lineAt(head);
    const lineContent = line.text;
 
    // Do not handle when cursor at the beginning of a line
    if (head === line.from) {
        return false;
    }
 
    const listMatch = lineContent.match(/^([*#]+)(\s*)/);
 
    if (!listMatch) return false;
 
    const symbolPrefix = listMatch[1]; // sequence of '*' or '#'
    // If single '*' and total '*' count is even, skip (likely bold syntax)
    if (symbolPrefix === '*') {
        const totalStars = (lineContent.match(/\*/g) || []).length;
        if (totalStars % 2 === 0) {
            return false;
        }
    }
 
    // Form the correct prefix with a guaranteed space
    const correctPrefix = symbolPrefix + ' ';
 
    // If the line contains only prefix and whitespace, remove the prefix
    if (lineContent.trim() === symbolPrefix.trim()) {
        // Remove prefix and insert an empty line before cursor
        view.dispatch({
            changes: {
                from: line.from,
                to: line.to,
                insert: '\n',
            },
            selection: { anchor: line.from + 1 }, // Position cursor after the empty line
        });
        return true;
    }
 
    // Insert a new line with the full prefix (guarantee a space)
    const reminder = lineContent.substring(head - line.from);
    const trimmedReminder = reminder.trim();
 
    view.dispatch({
        changes: {
            from: head,
            to: line.to,
            insert: '\n' + correctPrefix + trimmedReminder,
        },
        selection: { anchor: head + 1 + correctPrefix.length },
    });
    return true;
}
 
function handleQuoteContinuation(view: EditorView): boolean {
    const { state } = view;
    const { doc } = state;
    const { head } = state.selection.main;
 
    // Get the current line
    const line = doc.lineAt(head);
    const lineContent = line.text;
 
    // Do not handle when cursor at the beginning of a line
    if (head === line.from) {
        return false;
    }
 
    // Check if the line starts with a quote character ">"
    const quoteMatch = lineContent.match(/^>\s*/);
 
    if (!quoteMatch) return false;
 
    // Special handling for quote character ">"
    const prefix = quoteMatch[0];
    const remainingContent = lineContent.substring(head - line.from).trim();
    const isCursorAtEndOfLine = head === line.to;
 
    let insertText;
    const cursorPos = head + 2; // Position after first \n\n
 
    if (isCursorAtEndOfLine) {
        // If cursor is at the end of line, just insert two lines
        // One empty line and one for cursor
        insertText = '\n\n';
    } else {
        // Format: Empty line + cursor line + empty lines + (optional) remaining text with prefix
        insertText = '\n\n\n\n'; // Four lines: before cursor, cursor line, two empty lines after
 
        // Add remaining text with prefix
        Eif (remainingContent.trim().length > 0) {
            insertText += prefix + remainingContent;
        }
    }
 
    view.dispatch({
        changes: {
            from: head,
            to: line.to,
            insert: insertText,
        },
        selection: { anchor: cursorPos }, // Place cursor on the second line
    });
    return true;
}