feat(editor): Fill Paragraph action (#5681)

Edit › Fill Paragraph (code.fillParagraph, IDEA's FillParagraph) re-wraps the comment or plain-text paragraph at the caret to the hard wrap column: a run of line comments with the same marker, the * lines of a block comment up to a blank line or @tag, or non-blank lines of a plain text file. Code, string literals and read-only editors are left alone. No default shortcut, as in IDEA.

Closes #5680

Co-authored-by: mansur-akhmadi <[email protected]>
Цей коміт міститься в:
Mansur Akhmadiтаmansur-akhmadi authored and GitHub committed 2026-11-25 06:26:46 +08:00
1 джерело f16cfb507b
коміт fedd5ffd4f
12 files changed
+286 -1

No files matched your search

+2
Переглянути файл
@@ -51,6 +51,8 @@ The editor follows IntelliJ IDEA's behaviour and default keymap. Shortcuts below
**Duplicate Entire Lines** copies every line touched by a caret or selection below itself, even when only part of a line is selected, and keeps the selection on the copy. It has no default shortcut; run it from **Find Action** or assign one in **Settings › Keymap**.
**Fill Paragraph** re-wraps the paragraph at the caret to the hard wrap column (**Settings › Editor › Code Style**): a run of line comments, the `*` lines of a documentation comment up to the next blank line or `@` tag, or the lines between blank lines of a plain text file. In code it does nothing. It has no default shortcut.
Brackets and quotes are paired as you type, and typing a quote or bracket over a selection surrounds it. These and other typing aids (smart Home, Tab out of a closing bracket, a `;` typed before a closing `)` moving to the end of the statement, smart indent on Enter, documentation comment stubs, what Backspace does with indentation, reformat on paste) are under **Settings › Editor › General › Smart Keys**.
## Clipboard
+2
Переглянути файл
@@ -51,6 +51,8 @@ description: "多光标与选区、行编辑、剪贴板历史、代码折叠、
**复制整行** 把光标或选区涉及的每一行完整复制到其下方(即使只选中了行的一部分),并让选区落在副本上。它默认没有快捷键,可在查找操作中运行,或在 **设置 › 按键映射** 中分配快捷键。
**填充段落** 将光标处的段落按硬换行列(**设置 › 编辑器 › 代码样式**)重新换行:一组连续的行注释、文档注释中直到下一个空行或 `@` 标签为止的 `*` 行,或纯文本文件中空行之间的各行。在代码中不执行任何操作。它默认没有快捷键。
输入时括号和引号会自动成对,选中文本后输入引号或括号会把选区包起来。这些以及其他输入辅助(智能 Home、用 Tab 跳出右括号、在 `)` 前输入的 `;` 移到语句末尾、回车智能缩进、文档注释骨架、退格键如何处理缩进、粘贴时重新格式化)都在 **设置 › 编辑器 › 常规 › 智能键** 中。
## 剪贴板
+11
Переглянути файл
@@ -49,7 +49,9 @@ import {
foldSelection,
unfoldAtCaret,
} from "./cm/folding";
import { fillParagraph } from "./cm/fillParagraph";
import { reverseLines, sortLines } from "./cm/lines";
import { hardWrapAt } from "./cm/setup";
import { customRegions } from "./cm/regions";
import { toggleRenderedViewAtCaret } from "./cm/renderedDocs";
import { enclosingHeaders } from "./cm/stickyScroll";
@@ -987,6 +989,15 @@ export function registerEditorActions(): () => void {
}),
edit("code.sortLines", "Sort Lines", (v) => sortLines(v), { category: "Edit" }),
edit("code.reverseLines", "Reverse Lines", (v) => reverseLines(v), { category: "Edit" }),
text(
"code.fillParagraph",
"Fill Paragraph",
(v, slot) => fillParagraph(v, hardWrapAt(slot.model.settings(), slot.model.info)),
{
category: "Edit",
keywords: ["wrap", "reflow", "rewrap comment"],
},
),
text("code.unwrap", "Unwrap/Remove…", (_v, slot) => void unwrapAtCaret(slot), {
keywords: ["unwrap", "remove if"],
}),
+145
Переглянути файл
@@ -0,0 +1,145 @@
import { afterEach, describe, expect, it } from "vitest";
import { EditorSelection, EditorState, type Extension } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { ensureSyntaxTree } from "@codemirror/language";
import { java } from "@codemirror/lang-java";
import { languages } from "@codemirror/language-data";
import { fillParagraph } from "./fillParagraph";
import { loadSupport } from "./languages";
const views: EditorView[] = [];
afterEach(() => views.splice(0).forEach((v) => v.destroy()));
/** `|` marks the caret. */
function make(text: string, extensions: Extension = []) {
const at = text.indexOf("|");
const view = new EditorView({
state: EditorState.create({
doc: text.replace("|", ""),
selection: EditorSelection.cursor(at),
extensions,
}),
parent: document.body,
});
ensureSyntaxTree(view.state, view.state.doc.length, 5000);
views.push(view);
return view;
}
function show(v: EditorView) {
const doc = v.state.doc.toString();
const head = v.state.selection.main.head;
return doc.slice(0, head) + "|" + doc.slice(head);
}
describe("fill paragraph", () => {
it("re-wraps a run of line comments to the hard wrap column", () => {
const text = "class A {\n // one two three\n // four| five six\n // seven\n int a;\n}";
const v = make(text, java());
expect(fillParagraph(v, 20)).toBe(true);
expect(show(v)).toBe(text);
expect(fillParagraph(v, 40)).toBe(true);
expect(show(v)).toBe("class A {\n // one two three four| five six seven\n int a;\n}");
});
it("breaks before the word that would cross the column and keeps a long word on its own line", () => {
const v = make("// aaa bbb ccc ddd| eee\n// supercalifragilistic x", java());
fillParagraph(v, 10);
expect(show(v)).toBe("// aaa bbb\n// ccc ddd|\n// eee\n// supercalifragilistic\n// x");
});
it("stops at a blank comment line and at code", () => {
const v = make("int a; // trailing\n// a\n// b|\n//\n// c\nint b;", java());
fillParagraph(v, 80);
expect(show(v)).toBe("int a; // trailing\n// a b|\n//\n// c\nint b;");
});
it("re-wraps the ` * ` lines of a documentation comment, up to a tag", () => {
const v = make("/**\n * Returns the\n * sum| of a\n * and b.\n *\n * @param a first\n */\nint f;", java());
fillParagraph(v, 80);
expect(show(v)).toBe("/**\n * Returns the sum| of a and b.\n *\n * @param a first\n */\nint f;");
});
it("keeps a tag's lines together and the next tag apart", () => {
const v = make("/**\n * @param a the| first\n * operand\n * @param b second\n */", java());
fillParagraph(v, 80);
expect(show(v)).toBe("/**\n * @param a the| first operand\n * @param b second\n */");
});
it("uses the language's line comment token", async () => {
const python = (await loadSupport(languages.find((l) => l.name === "Python")!))!;
const v = make("def f():\n # one\n # two|\n return 1\n", python);
fillParagraph(v, 80);
expect(show(v)).toBe("def f():\n # one two|\n return 1\n");
});
it("does not mix comments with a different marker", () => {
const v = make("/// doc a\n// b|\n// c", java());
fillParagraph(v, 80);
expect(show(v)).toBe("/// doc a\n// b| c");
});
it("keeps a marker with punctuation (`//!`) apart and the space after the marker as it is", async () => {
const rust = (await loadSupport(languages.find((l) => l.name === "Rust")!))!;
const v = make("//! crate\n//! doc|\n// plain\n//tight\n", rust);
fillParagraph(v, 80);
expect(show(v)).toBe("//! crate doc|\n// plain\n//tight\n");
const tight = make("//a\n//b|", java());
fillParagraph(tight, 80);
expect(show(tight)).toBe("//a b|");
});
it("leaves a shebang alone", async () => {
const python = (await loadSupport(languages.find((l) => l.name === "Python")!))!;
const v = make("#!/usr/bin/env| python\n# hello\n", python);
expect(fillParagraph(v, 10)).toBe(false);
const next = make("#!/usr/bin/env python\n# a\n# b|\n", python);
fillParagraph(next, 80);
expect(show(next)).toBe("#!/usr/bin/env python\n# a b|\n");
});
it("starts a paragraph at <p> and keeps <pre> apart in a documentation comment", () => {
const v = make("/**\n * one\n * two|\n * <p>three\n * <pre>\n * x();\n * </pre>\n */", java());
fillParagraph(v, 80);
expect(show(v)).toBe("/**\n * one two|\n * <p>three\n * <pre>\n * x();\n * </pre>\n */");
});
it("keeps the other carets", () => {
const v = make("// a\n// b|\nint x;", [java(), EditorState.allowMultipleSelections.of(true)]);
v.dispatch({
selection: EditorSelection.create([EditorSelection.cursor(16), EditorSelection.cursor(9)], 1),
});
fillParagraph(v, 80);
expect(v.state.doc.toString()).toBe("// a b\nint x;");
expect(v.state.selection.ranges.map((r) => r.head)).toEqual([6, 13]);
expect(v.state.selection.main.head).toBe(6);
});
it("treats `@` as text in a plain text file", () => {
const v = make("hello\n@world|\nfoo");
fillParagraph(v, 80);
expect(show(v)).toBe("hello @world| foo");
});
it("re-wraps a plain text paragraph between blank lines", () => {
const v = make("Title\n\nalpha beta\ngamma| delta\nepsilon\n\nnext");
fillParagraph(v, 12);
expect(show(v)).toBe("Title\n\nalpha beta\ngamma| delta\nepsilon\n\nnext");
fillParagraph(v, 80);
expect(show(v)).toBe("Title\n\nalpha beta gamma| delta epsilon\n\nnext");
});
it("does nothing in code, in a string or on a blank line", () => {
for (const text of ["int| a = 1;\nint b = 2;", 'String s = "// not| a comment";\nint b;', "// a\n|\n// b"]) {
const v = make(text, java());
expect(fillParagraph(v, 80)).toBe(false);
expect(show(v)).toBe(text);
}
});
it("does nothing in a read-only editor", () => {
const v = make("// a\n// b|", [java(), EditorState.readOnly.of(true)]);
expect(fillParagraph(v, 80)).toBe(false);
expect(show(v)).toBe("// a\n// b|");
});
});
+111
Переглянути файл
@@ -0,0 +1,111 @@
/**
* Edit › Fill Paragraph (IDEA's FillParagraph): re-wraps the paragraph at the
* caret to the hard wrap column. A paragraph is a run of line comments with the
* same marker, of ` * ` lines of a block comment, or of non-blank lines of a
* plain text file; a blank line, a comment opener / closer, a line with code or
* a `@tag` line ends it. Elsewhere in code the command does nothing.
*/
import { language, syntaxTree } from "@codemirror/language";
import { EditorSelection, countColumn, type EditorState, type Line } from "@codemirror/state";
import type { EditorView } from "@codemirror/view";
const escape = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
function inComment(state: EditorState, pos: number): boolean {
return /comment/i.test(syntaxTree(state).resolveInner(pos, 1).name);
}
/** The marker a paragraph line starts with (indentation plus `//`, `#`, `*`), or `null` if the line can't be filled. */
function markerOf(state: EditorState, line: Line): string | null {
const indent = /^[ \t]*/.exec(line.text)![0];
if (!state.facet(language)) return indent;
const at = line.from + indent.length;
const tokens = state.languageDataAt<{ line?: string; block?: { open: string } }>("commentTokens", at)[0];
const rest = line.text.slice(indent.length);
// A shebang or a block comment opened by the line token (Lua's `--[[`) isn't a line comment.
if ((line.number === 1 && rest.startsWith("#!")) || (tokens?.block && rest.startsWith(tokens.block.open)))
return null;
// `///`, `//!` and `#:` are markers of their own, not text after `//` or `#`.
const lineComment = tokens?.line && new RegExp(`^${escape(tokens.line)}[^\\s\\w]*`).exec(rest);
if (lineComment && inComment(state, at)) return indent + lineComment[0];
if (/^\*(?!\/)/.test(rest) && inComment(state, at)) return indent + "*";
return null;
}
/** The text of `line` after `marker`, or `null` if the line isn't part of a paragraph with that marker. */
function contentOf(state: EditorState, line: Line, marker: string): string | null {
if (markerOf(state, line) !== marker) return null;
const text = line.text.slice(marker.length).trim();
return text && !text.includes("*/") ? text : null;
}
const solid = (s: string) => s.replace(/\s/g, "").length;
export function fillParagraph(view: EditorView, width: number): boolean {
const { state } = view;
if (state.readOnly) return false;
const head = state.selection.main.head;
const caretLine = state.doc.lineAt(head);
const marker = markerOf(state, caretLine);
if (marker == null || contentOf(state, caretLine, marker) == null) return false;
// In a comment a `@tag`, `<p>` or list item starts a paragraph of its own.
const starts = (n: number) =>
!!marker.trim() && /^(?:@|<\/?(?:p|pre|ul|ol|li)\b)/i.test(contentOf(state, state.doc.line(n), marker) ?? "");
let first = caretLine.number;
while (!starts(first) && first > 1 && contentOf(state, state.doc.line(first - 1), marker) != null) first--;
let last = caretLine.number;
while (last < state.doc.lines && !starts(last + 1) && contentOf(state, state.doc.line(last + 1), marker) != null)
last++;
const prefix = marker + /^[ \t]*/.exec(state.doc.line(first).text.slice(marker.length))![0];
const lines: string[] = [];
let current = "";
let before = 0;
for (let n = first; n <= last; n++) {
const line = state.doc.line(n);
const text = contentOf(state, line, marker)!;
if (n < caretLine.number) before += solid(text);
else if (n === caretLine.number) {
const offset = head - line.from - marker.length;
before += offset > 0 ? solid(line.text.slice(marker.length, marker.length + offset)) : 0;
}
for (const word of text.split(/\s+/)) {
const next = current ? `${current} ${word}` : word;
if (current && countColumn(prefix + next, state.tabSize) > width) {
lines.push(current);
current = word;
} else current = next;
}
}
lines.push(current);
const from = state.doc.line(first).from;
const to = state.doc.line(last).to;
const insert = lines.map((l) => prefix + l).join(state.lineBreak);
if (insert === state.sliceDoc(from, to)) return true;
// Keep the caret after the same non-blank character of the paragraph's text.
let caret = from + insert.length;
for (let i = 0, pos = from, left = before; i < lines.length; i++) {
const text = lines[i]!;
if (left <= solid(text)) {
let k = 0;
for (let seen = 0; seen < left; k++) if (!/\s/.test(text[k]!)) seen++;
caret = pos + prefix.length + k;
break;
}
left -= solid(text);
pos += prefix.length + text.length + 1;
}
const changes = state.changes({ from, to, insert });
const { ranges, mainIndex } = state.selection;
view.dispatch({
changes,
selection: EditorSelection.create(
ranges.map((r, i) => (i === mainIndex ? EditorSelection.cursor(caret) : r.map(changes))),
mainIndex,
),
scrollIntoView: true,
userEvent: "input.fill",
});
return true;
}
+1
Переглянути файл
@@ -52,6 +52,7 @@ export const IDEA_ACTIONS: Readonly<Record<string, string>> = {
EditorSelectWord: "code.extendSelection",
EditorUnSelectWord: "code.shrinkSelection",
EditorDuplicateLines: "code.duplicateEntireLines",
FillParagraph: "code.fillParagraph",
CollapseRegion: "code.fold",
ExpandRegion: "code.unfold",
CollapseAllRegions: "code.foldAll",
+8
Переглянути файл
@@ -57,6 +57,14 @@ describe("IntelliJ IDEA keymap import", () => {
expect(k.unknownActions).toEqual([]);
});
it("maps Fill Paragraph, which has no shortcut in the presets", () => {
const k = parseIdeaKeymap(
`<keymap name="M" parent="Mac OS X 10.5+"><action id="FillParagraph"><keyboard-shortcut first-keystroke="alt meta Q"/></action></keymap>`,
);
expect(k.overrides["code.fillParagraph"]).toEqual([normalizeBinding("Alt+Meta+Q")]);
expect(k.unknownActions).toEqual([]);
});
it("maps Remove All Breakpoints and Remove All Breakpoints In The Current File", () => {
const k = parseIdeaKeymap(
`<keymap name="M" parent="Mac OS X 10.5+"><action id="Debugger.RemoveAllBreakpoints"><keyboard-shortcut first-keystroke="shift meta F9"/></action><action id="Debugger.RemoveAllBreakpointsInFile"><keyboard-shortcut first-keystroke="alt meta F9"/></action></keymap>`,
+1
Переглянути файл
@@ -158,6 +158,7 @@ export const intellijMacos: Record<string, string[]> = {
"code.pasteFromHistory": ["Meta+Shift+V"],
"code.sortLines": [],
"code.reverseLines": [],
"code.fillParagraph": [],
"code.unwrap": ["Meta+Shift+Delete"],
"code.foldSelection": ["Meta+."],
"editor.toggleColumnSelection": ["Meta+Shift+8"],
+1
Переглянути файл
@@ -160,6 +160,7 @@ export const intellijWindows: Record<string, string[]> = {
"code.pasteFromHistory": ["Ctrl+Shift+V"],
"code.sortLines": [],
"code.reverseLines": [],
"code.fillParagraph": [],
"code.unwrap": ["Ctrl+Shift+Delete"],
"code.foldSelection": ["Ctrl+."],
"editor.toggleColumnSelection": ["Alt+Shift+Insert"],
+1
Переглянути файл
@@ -177,6 +177,7 @@ export const vscodeMacos: Record<string, string[]> = {
"code.pasteFromHistory": [],
"code.sortLines": [],
"code.reverseLines": [],
"code.fillParagraph": [],
"code.unwrap": [],
"code.foldSelection": [],
"editor.toggleColumnSelection": [],
+2 -1
Переглянути файл
@@ -9248,5 +9248,6 @@
"Find where this component is imported and used": "查找此元件被匯入和使用的位置",
"Gradle project sync failed": "Gradle 專案同步失敗",
"Gradle could not sync {project}. Java code insight may not work until the build syncs. Fix the build, then reload the Gradle project. Cause: {cause}": "Gradle 無法同步 {project}。建置同步成功前,Java 程式碼分析可能無法正常運作。請修正建置,然後重新載入 Gradle 專案。原因:{cause}",
"Gradle could not sync {project}. Java code insight may not work until the build syncs. Fix the build, then reload the Gradle project.": "Gradle 無法同步 {project}。建置同步成功前,Java 程式碼分析可能無法正常運作。請修正建置,然後重新載入 Gradle 專案。"
"Gradle could not sync {project}. Java code insight may not work until the build syncs. Fix the build, then reload the Gradle project.": "Gradle 無法同步 {project}。建置同步成功前,Java 程式碼分析可能無法正常運作。請修正建置,然後重新載入 Gradle 專案。",
"Fill Paragraph": "填充段落"
}
+1
Переглянути файл
@@ -1014,6 +1014,7 @@
"Paste from History…": "从历史记录粘贴…",
"Sort Lines": "排序行",
"Reverse Lines": "反转行序",
"Fill Paragraph": "填充段落",
"Unwrap/Remove…": "解包/移除…",
"Basic": "基本补全",
"Quick Definition": "快速定义",