Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions apps/vscode/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

- Reduce memory usage by only starting the language server (LSP) in projects containing Quarto documents (https://github.com/quarto-dev/quarto/pull/1059).
- Fixed a bug where single-line display math with a cross-reference label (e.g. `$$1+1$$ {#eq-spec0}`), or an unclosed `$$`, stopped the rest of the document from being parsed, so headings went missing from the outline, LaTeX preview was unavailable, and code cells below could not be run (<https://github.com/quarto-dev/quarto/pull/1063>).
- Adds a command "Quarto: Reflow Comments in Cell" that breaks up long comment lines into multiple comment lines (by default 80 characters is considered long, but that is configurable by `quarto.cells.reflowColumn`) (<https://github.com/quarto-dev/quarto/pull/1087>).

## 1.135.0 (Release on 2026-07-08)

Expand Down
17 changes: 17 additions & 0 deletions apps/vscode/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -377,6 +377,11 @@
"title": "Format Cell",
"category": "Quarto"
},
{
"command": "quarto.reflowCommentInCell",
"title": "Reflow Comments in Cell",
"category": "Quarto"
},
{
"command": "quarto.previewMath",
"category": "Quarto",
Expand Down Expand Up @@ -665,6 +670,11 @@
"when": "editorLangId == quarto && !editorHasSelection",
"group": "1_modification"
},
{
"command": "quarto.reflowCommentInCell",
"when": "editorLangId == quarto && !editorHasSelection",
"group": "1_modification"
},
{
"command": "quarto.editInVisualMode",
"when": "resourceScheme != untitled && editorLangId == quarto || resourceScheme != untitled && editorLangId == markdown",
Expand Down Expand Up @@ -1022,6 +1032,13 @@
"default": 500,
"markdownDescription": "Delay in milliseconds before updating diagnostics after document changes."
},
"quarto.cells.reflowColumn": {
"order": 28,
"scope": "window",
"type": "number",
"default": 80,
"markdownDescription": "Maximum line length used by the **Quarto: Reflow Comments in Cell** command."
},
"quarto.cells.background.enabled": {
"type": "boolean",
"description": "Enable coloring the background of executable code cells.",
Expand Down
3 changes: 3 additions & 0 deletions apps/vscode/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { kQuartoDocSelector } from "./core/doc";
import { activateLsp, deactivate as deactivateLsp } from "./lsp/client";
import { activateEmbeddedDiagnostics, type EmbeddedDiagnosticsService } from "./providers/diagnostics";
import { cellCommands } from "./providers/cell/commands";
import { reflowCommands } from "./providers/cell/reflow";
import { quartoCellExecuteCodeLensProvider } from "./providers/cell/codelens";
import { activateQuartoAssistPanel } from "./providers/assist/panel";
import { activatePreview } from "./providers/preview/preview";
Expand Down Expand Up @@ -177,6 +178,8 @@ export async function activate(context: vscode.ExtensionContext): Promise<Quarto

commands.push(...activateCodeFormatting(engine));

commands.push(...reflowCommands(engine));

// provide code lens (conditionally in Positron based on inline output setting)
const isPositron = tryAcquirePositronApi();
if (isPositron) {
Expand Down
4 changes: 2 additions & 2 deletions apps/vscode/src/providers/cell/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ export function cellOptions(language: string, source: string[]): Record<string,
}
}

function langCommentChars(lang: string): string[] {
export function langCommentChars(lang: string): string[] {
const chars = kLangCommentChars[lang] || "#";
if (!Array.isArray(chars)) {
return [chars];
Expand Down Expand Up @@ -140,6 +140,6 @@ const kLangCommentChars: Record<string, string | [string, string]> = {
apl: "⍝",
};

function escapeRegExp(str: string) {
export function escapeRegExp(str: string) {
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // $& means the whole matched string
}
273 changes: 273 additions & 0 deletions apps/vscode/src/providers/cell/reflow.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,273 @@
/*
* reflow.ts
*
* Copyright (C) 2026 by Posit Software, PBC
*
* Unless you have received this program directly from Posit Software pursuant
* to the terms of a commercial license agreement with Posit Software, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/

import { EndOfLine, Position, Range, window, workspace } from "vscode";

import { lines } from "core";
import {
TokenCodeBlock,
TokenMath,
codeForExecutableLanguageBlock,
languageBlockAtLine,
languageNameFromBlock,
} from "quarto-core";

import { Command } from "../../core/command";
import { isQuartoDoc } from "../../core/doc";
import { MarkdownEngine } from "../../markdown/engine";
import { languageFromBlock } from "../../vdoc/vdoc";
import { escapeRegExp, langCommentChars, optionCommentPattern } from "./options";

export function reflowCommands(engine: MarkdownEngine): Command[] {
return [new ReflowCommentInCellCommand(engine)];
}

const kDefaultReflowColumn = 80;

class ReflowCommentInCellCommand implements Command {
public readonly id = "quarto.reflowCommentInCell";
constructor(private readonly engine_: MarkdownEngine) { }

public async execute(): Promise<void> {
const editor = window.activeTextEditor;
if (!editor) {
// No active text editor
return;
}

const document = editor.document;
if (!isQuartoDoc(document)) {
window.showInformationMessage("Active editor is not a Quarto document");
return;
}

const includeFence = false;

const tokens = this.engine_.parse(document);
const block = languageBlockAtLine(tokens, editor.selection.start.line, includeFence);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can this use the selection when there is one? Today it reflows every comment run in the cell, so a user who selects three comment lines still gets the whole cell rewrapped. Filtering reflows to the runs that intersect the selection would cover it. The context menu needs a change too: the when clause at apps/vscode/package.json:675 hides the command while a selection exists.

if (!block) {
window.showInformationMessage("Editor selection is not within a code cell.");
return;
}

const comment = lineCommentForBlock(block);
if (!comment) {
window.showInformationMessage(
`Comment reflow is not supported for ${languageNameFromBlock(block)} cells.`
);
return;
}

const column = workspace
.getConfiguration("quarto")
.get<number>("cells.reflowColumn", kDefaultReflowColumn);

const cellLines = lines(codeForExecutableLanguageBlock(block, false));
const reflows = reflowComments(cellLines, comment, column);
if (reflows.length === 0) {
return;
}

// Use the document's line ending to avoid introducing mixed EOL in CRLF files.
const eol = document.eol === EndOfLine.CRLF ? "\r\n" : "\n";

// The `+ 1` skips the opening fence line.
const lineOffset = block.range.start.line + 1;

await editor.edit((editBuilder) => {
// Sort by descending start position to avoid range shifting issues
[...reflows]
.sort((a, b) => b.startLine - a.startLine)
.forEach((reflow) => {
const range = new Range(
new Position(lineOffset + reflow.startLine, 0),
document.lineAt(lineOffset + reflow.endLine).range.end
);
editBuilder.replace(range, reflow.newLines.join(eol));
});
});
}
}

// Resolve the line comment string for a block. Prefer the canonical comment
// from `editor-core` (via the embedded language) and fall back to the
// executor-oriented map in `cell/options.ts` for languages that aren't
// embedded (lua, haskell, fortran, ...). Languages that only have block
// comments (a [open, close] tuple in the map) return undefined.
function lineCommentForBlock(block: TokenMath | TokenCodeBlock): string | undefined {
const language = languageFromBlock(block);
if (language?.comment) {
return language.comment;
}
const commentChars = langCommentChars(languageNameFromBlock(block));
return commentChars.length === 1 ? commentChars[0] : undefined;
}

export interface CommentReflow {
/** First line of the replaced region (0-based, relative to the cell body). */
startLine: number;
/** Last line of the replaced region (inclusive). */
endLine: number;
/** Replacement lines (may be fewer or more than the region spans). */
newLines: string[];
}

interface ParsedCommentLine {
raw: string;
indent: string;
prefix: string;
content: string;
kind: "blank" | "fixed" | "text";
}

/**
* Reflow the full-line comments in a cell body to the given column.
*
* Consecutive comment lines form paragraphs whose words are re-wrapped
* greedily. Paragraphs are delimited by code lines, empty comment lines
* (which are preserved as separators), changes in indentation or comment
* prefix, and "fixed" lines that are kept verbatim: divider/banner lines
* without any word content (`# ------`, `#######`) and section headers
* ending in a run of `-`/`=` (`# Load data ----`). Quarto option directives
* (`#| echo: false`) and lines that mix code and a trailing comment are
* never touched.
*
* Returns one replacement per contiguous comment run that actually changed.
*/
export function reflowComments(
cellLines: string[],
comment: string,
column: number
): CommentReflow[] {
const optionPattern = optionCommentPattern(comment);
// An extended comment prefix: one or more repetitions of the comment
// string, optionally followed by a doc-comment marker. This keeps prefixes
// like `#'` (roxygen), `///` and `//!` (doc comments) intact when wrapping.
const prefixPattern = new RegExp("^((?:" + escapeRegExp(comment) + ")+[!'/]?)");

const parseLine = (raw: string): ParsedCommentLine | undefined => {
const trimmed = raw.trimStart();
if (!trimmed.startsWith(comment)) {
return undefined;
}
// Never touch cell option directives (`#| echo: false`)
if (optionPattern.test(trimmed)) {
return undefined;
}
const indent = raw.slice(0, raw.length - trimmed.length);
let prefix = prefixPattern.exec(trimmed)![1];
let rest = trimmed.slice(prefix.length);
if (rest !== "" && !/^[ \t]/.test(rest)) {
// The extended prefix runs straight into other text (e.g. `#--- foo`):
// fall back to the bare comment string as the prefix.
prefix = comment;
rest = trimmed.slice(comment.length);
}
const content = rest.trim();
const kind =
content === ""
? prefix === comment
? "blank"
: "fixed" // banner lines like `#####` are kept verbatim
: !/[\p{L}\p{N}]/u.test(content) || /[-=]{4,}$/.test(content)
? "fixed" // dividers (`# ----`) and section headers (`# Load ----`)
: "text";
return { raw, indent, prefix, content, kind };
};

const reflows: CommentReflow[] = [];
let i = 0;
while (i < cellLines.length) {
if (!parseLine(cellLines[i])) {
i++;
continue;
}
// Collect a contiguous run of comment lines
const runStart = i;
const run: ParsedCommentLine[] = [];
for (; i < cellLines.length; i++) {
const parsed = parseLine(cellLines[i]);
if (!parsed) {
break;
}
run.push(parsed);
}
const runEnd = i - 1;
const newLines = reflowRun(run, column);
const original = cellLines.slice(runStart, runEnd + 1);
if (
newLines.length !== original.length ||
newLines.some((line, idx) => line !== original[idx])
) {
reflows.push({ startLine: runStart, endLine: runEnd, newLines });
}
}
return reflows;
}

function reflowRun(run: ParsedCommentLine[], column: number): string[] {
const out: string[] = [];
let paragraph: ParsedCommentLine[] = [];
const flush = () => {
if (paragraph.length > 0) {
out.push(...wrapParagraph(paragraph, column));
paragraph = [];
}
};
for (const line of run) {
if (line.kind === "blank") {
flush();
// Normalize empty comment lines (drops trailing whitespace)
out.push(line.indent + line.prefix);
} else if (line.kind === "fixed") {
flush();
out.push(line.raw);
} else {
if (
paragraph.length > 0 &&
(paragraph[0].indent !== line.indent || paragraph[0].prefix !== line.prefix)
) {
flush();
}
paragraph.push(line);
}
}
flush();
return out;
}

function wrapParagraph(paragraph: ParsedCommentLine[], column: number): string[] {
const linePrefix = paragraph[0].indent + paragraph[0].prefix + " ";
const width = Math.max(1, column - linePrefix.length);
const words = paragraph
.flatMap((line) => line.content.split(/\s+/))
.filter((word) => word.length > 0);
const out: string[] = [];
let current = "";
for (const word of words) {
if (current === "") {
current = word;
} else if (current.length + 1 + word.length <= width) {
current += " " + word;
} else {
out.push(linePrefix + current);
current = word;
}
}
if (current !== "") {
out.push(linePrefix + current);
}
return out;
}
19 changes: 19 additions & 0 deletions apps/vscode/src/test/examples/reflow.qmd
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
---
title: Reflow
---

## Comments

```{r}
# It is a truth universally acknowledged, that a single man in possession of a good fortune must be in want of a wife.
#
# "My dear Mr. Bennet," said his lady to him one day, "have you heard that Netherfield Park is let at last?"

1 + 1
```

```{python}
#| echo: false
# However little known the feelings or views of such a man may be on his first entering a neighbourhood, this truth is so well fixed in the minds of the surrounding families.
x = 1
```
Loading
Loading