From 41ccad7cce599d7108319d90c1628641bc98685e Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Thu, 19 Sep 2024 20:00:05 -0400 Subject: [PATCH] Adds natural behavior of `Tab`, `Shift-Tab` in code blocks (#7622) * Adds proper handling of Tab, Shift-Tab in code blocks * refactor --- shared/editor/commands/codeFence.ts | 153 +++++++++++++++++++++-- shared/editor/nodes/CodeFence.ts | 26 +--- shared/editor/queries/findStartOfLine.ts | 22 ++++ 3 files changed, 169 insertions(+), 32 deletions(-) create mode 100644 shared/editor/queries/findStartOfLine.ts diff --git a/shared/editor/commands/codeFence.ts b/shared/editor/commands/codeFence.ts index 3bb62d8761..5fc6be6a03 100644 --- a/shared/editor/commands/codeFence.ts +++ b/shared/editor/commands/codeFence.ts @@ -1,6 +1,11 @@ +import { exitCode } from "prosemirror-commands"; import { Command, TextSelection } from "prosemirror-state"; +import { findStartOfLine } from "../queries/findStartOfLine"; import { isInCode } from "../queries/isInCode"; +const newline = "\n"; +const tabSize = 2; + /** * Moves the current selection to the previous newline, this is used inside * code fences only, prosemirror handles this functionality fine in other nodes. @@ -24,7 +29,7 @@ export const moveToPreviousNewline: Command = (state, dispatch) => { .split("") .reverse() .join("") - .indexOf("\n", $pos.parent.nodeSize - $pos.parentOffset - 2); + .indexOf(newline, $pos.parent.nodeSize - $pos.parentOffset - 2); const pos = startOfLine === -1 ? beginningOfNode @@ -55,7 +60,7 @@ export const moveToNextNewline: Command = (state, dispatch) => { // find next newline or end of node const beginningOfNode = $pos.pos - $pos.parentOffset; - const endOfLine = $pos.parent.textContent.indexOf("\n", $pos.parentOffset); + const endOfLine = $pos.parent.textContent.indexOf(newline, $pos.parentOffset); const pos = endOfLine === -1 ? beginningOfNode + $pos.parent.nodeSize - 2 @@ -81,13 +86,12 @@ export const newlineInCode: Command = (state, dispatch) => { } const { tr, selection } = state; const text = selection.$anchor.nodeBefore?.text; - let newText = "\n"; + let newText = newline; if (text) { - const splitByNewLine = text.split("\n"); - const numOfSpaces = - splitByNewLine[splitByNewLine.length - 1].search(/\S|$/); - newText += " ".repeat(numOfSpaces); + const splitByNewLine = text.split(newline); + const offset = splitByNewLine[splitByNewLine.length - 1].search(/\S|$/); + newText += " ".repeat(offset); } dispatch?.(tr.insertText(newText, selection.from, selection.to)); @@ -95,16 +99,141 @@ export const newlineInCode: Command = (state, dispatch) => { }; /** - * Insert two spaces to simulate the tab key. + * Indent the current selection by two spaces, accounting for multiple lines. * * @returns A prosemirror command */ -export const insertSpaceTab: Command = (state, dispatch) => { - if (!isInCode(state)) { +export const indentInCode: Command = (state, dispatch) => { + if (!isInCode(state, { onlyBlock: true })) { return false; } + const spaces = " ".repeat(tabSize); const { tr, selection } = state; - dispatch?.(tr.insertText(" ", selection.from, selection.to)); - return true; + const { $from, from, to } = selection; + + // If the selection is empty, just insert two spaces at the cursor position. + if (selection.empty) { + dispatch?.( + tr + .insertText(spaces, from) + .setSelection(TextSelection.create(tr.doc, from + spaces.length)) + ); + return true; + } + + if (dispatch) { + let line = 1; + tr.insertText(spaces, findStartOfLine($from, tr.doc)); + + // Find all newlines in the selection and insert spaces before them. + let index = from + 1; + while (index <= to - 1 + line * tabSize) { + const newLineBefore = tr.doc.textBetween(index - 1, index) === newline; + if (newLineBefore) { + tr.insertText(spaces, index); + line++; + } + index++; + } + + tr.setSelection( + TextSelection.create(tr.doc, from + tabSize, to + line * tabSize) + ); + + dispatch(tr); + return true; + } + + return false; +}; + +/** + * Outdent the current selection by two spaces, accounting for multiple lines. + * + * @returns A prosemirror command + */ +export const outdentInCode: Command = (state, dispatch) => { + if (!isInCode(state, { onlyBlock: true })) { + return false; + } + + if (dispatch) { + const { tr, selection } = state; + const { $from, from, to } = selection; + const selectionLength = to - from; + let line = 1; + + // Find all newlines in the selection and remove tab-sized spaces before + // them, working backwards to avoid changing the offset. + let index = to - 1; + let totalSpacesRemoved = 0; + let spacesRemovedOnFirstLine = 0; + const startOfFirstLine = findStartOfLine($from, tr.doc); + + while (index >= startOfFirstLine - line * tabSize) { + const newLineBefore = + tr.doc.textBetween(index - 1, index) === newline || + index === startOfFirstLine; + if (newLineBefore) { + // Remove upto offset spaces from the start of the line. + const textToConsider = tr.doc.textBetween(index, index + tabSize); + + // Find number of spaces in textToConsider + let spaces = 0; + for (let i = 0; i < textToConsider.length; i++) { + if (textToConsider[i] === " ") { + spaces++; + } else { + break; + } + } + + spacesRemovedOnFirstLine = spaces; + + if (spaces > 0) { + tr.delete(index, index + spaces); + totalSpacesRemoved += spaces; + } + line++; + } + index--; + } + + tr.setSelection( + TextSelection.create( + tr.doc, + to - selectionLength - spacesRemovedOnFirstLine, + to - totalSpacesRemoved + ) + ); + + dispatch(tr); + return true; + } + + return false; +}; + +/** + * Exit the code block by moving the cursor to the end of the code block and + * inserting a newline character. + * + * @returns A prosemirror command + */ +export const enterInCode: Command = (state, dispatch) => { + if (!isInCode(state, { onlyBlock: true })) { + return false; + } + const { selection } = state; + const text = selection.$anchor.nodeBefore?.text; + const selectionAtEnd = + selection.$anchor.parentOffset === selection.$anchor.parent.nodeSize - 2; + + if (selectionAtEnd && text?.endsWith(newline)) { + exitCode(state, dispatch); + return true; + } + + return newlineInCode(state, dispatch); }; diff --git a/shared/editor/nodes/CodeFence.ts b/shared/editor/nodes/CodeFence.ts index e9379b2efc..079f3728ad 100644 --- a/shared/editor/nodes/CodeFence.ts +++ b/shared/editor/nodes/CodeFence.ts @@ -1,6 +1,5 @@ import copy from "copy-to-clipboard"; import Token from "markdown-it/lib/token"; -import { exitCode } from "prosemirror-commands"; import { textblockTypeInputRule } from "prosemirror-inputrules"; import { NodeSpec, @@ -67,9 +66,11 @@ import { isMac } from "../../utils/browser"; import backspaceToParagraph from "../commands/backspaceToParagraph"; import { newlineInCode, - insertSpaceTab, + indentInCode, moveToNextNewline, moveToPreviousNewline, + outdentInCode, + enterInCode, } from "../commands/codeFence"; import { selectAll } from "../commands/selectAll"; import toggleBlockType from "../commands/toggleBlockType"; @@ -245,24 +246,9 @@ export default class CodeFence extends Node { // Both shortcuts work, but Shift-Ctrl-c matches the one in the menu "Shift-Ctrl-c": toggleBlockType(type, schema.nodes.paragraph), "Shift-Ctrl-\\": toggleBlockType(type, schema.nodes.paragraph), - Tab: insertSpaceTab, - Enter: (state, dispatch) => { - if (!isInCode(state)) { - return false; - } - const { selection } = state; - const text = selection.$anchor.nodeBefore?.text; - const selectionAtEnd = - selection.$anchor.parentOffset === - selection.$anchor.parent.nodeSize - 2; - - if (selectionAtEnd && text?.endsWith("\n")) { - exitCode(state, dispatch); - return true; - } - - return newlineInCode(state, dispatch); - }, + "Shift-Tab": outdentInCode, + Tab: indentInCode, + Enter: enterInCode, Backspace: backspaceToParagraph(type), "Shift-Enter": newlineInCode, "Mod-a": selectAll(type), diff --git a/shared/editor/queries/findStartOfLine.ts b/shared/editor/queries/findStartOfLine.ts new file mode 100644 index 0000000000..e26556ae43 --- /dev/null +++ b/shared/editor/queries/findStartOfLine.ts @@ -0,0 +1,22 @@ +import { Node, ResolvedPos } from "prosemirror-model"; + +/** + * Find the start of the line that the current position is on. + * + * @param $pos The current resolved position + * @param doc The current document + * @returns The position of the start of the line as an integer. + */ +export function findStartOfLine($pos: ResolvedPos, doc: Node) { + let lineStart = $pos.pos; + const parentStart = $pos.pos - $pos.parentOffset; + + while ( + lineStart > parentStart && + doc.textBetween(lineStart - 1, lineStart) !== "\n" + ) { + lineStart--; + } + + return lineStart; +}