Skip to content

Commit b0e19d5

Browse files
committed
feat(project): markdown.outline 按标题输出 Markdown 的文档结构树
用与 markdown.render 相同的 Comrak 方言解析,把标题按级别组织成与 LSP documentSymbol 归一化结果同形的符号树:selectionRange 是标题本身,range 是到下一个同级或更高级标题的整节;位置为零起始行和 UTF-16 列。宿主在没有语言服务器时也能为 Markdown 文件显示结构,且与预览页的目录一致。共享样例 rust/fixtures/editor/markdown-outline-v1.json。
1 parent c1df34b commit b0e19d5

11 files changed

Lines changed: 662 additions & 12 deletions

File tree

‎rust/Cargo.lock‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎rust/contracts/rust-core-api.md‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -551,6 +551,7 @@ or removing a command fails until the table changes in the same commit.
551551
| `processLifecycle.inventory` | Group a process snapshot of one Lithe instance into terminals, Agent tasks and background services |
552552
| `processLifecycle.settle` | Turn confirmation answers into what ends, what is kept and the updated settings |
553553
| `markdown.render` | Renders and sanitizes shared Markdown |
554+
| `markdown.outline` | Outlines the headings of shared Markdown as a document-symbol tree |
554555
| `markdown.resolveReference` | Decides what a link or an image of a rendered Markdown document points at |
555556
| `keymap.parseContext` | Compile a bounded boolean shortcut context (from `lithe-core-rules`) |
556557
| `keymap.evaluateContext` | Evaluate a precompiled shortcut context (from `lithe-core-rules`) |
@@ -5559,6 +5560,42 @@ load what this command refuses.
55595560
Shared examples: `rust/fixtures/editor/markdown-render-v1.json`,
55605561
`markdown-html-v1.json` and `markdown-rich-content-v1.json`.
55615562

5563+
### Markdown heading outline
5564+
5565+
`markdown.outline` accepts `{ "source": "<Markdown text>" }` and returns
5566+
`{ "symbols": [...] }`, the headings of the source as a tree in the normalized
5567+
document-symbol shape `lsp.request` returns for `textDocument/documentSymbol`.
5568+
Hosts show it where they show a language server's symbols, so a Markdown file
5569+
has a structure without a language server, and it lists the headings the
5570+
preview's outline lists: the source is parsed with the dialect of
5571+
`markdown.render`.
5572+
5573+
- Every heading Comrak parses is listed in document order, including ATX and
5574+
setext headings inside block quotes, lists and alerts. Front matter, code and
5575+
raw HTML headings such as `<h2>` are not headings.
5576+
- `name` is the heading's text as the preview shows it: text, inline code, math
5577+
literals and shortcode emoji, without images, footnote references and HTML
5578+
tags, with each run of whitespace collapsed to one space and the ends trimmed.
5579+
A heading whose name is empty is left out, and its section belongs to the
5580+
heading before it.
5581+
- A heading is a child of the nearest heading before it with a lower level, so a
5582+
skipped level nests one step.
5583+
- `kind` is `15` (`SymbolKind.String`, as editors mark Markdown headings);
5584+
`detail` and `containerName` are `null`, `tags` is empty and `deprecated` is
5585+
`false`.
5586+
- Positions are zero-based lines and UTF-16 columns (`{ line, utf16Column }`);
5587+
`\n`, `\r\n` and a lone `\r` end a line. `selectionRange` covers the heading
5588+
from its first character to just after its last, a setext heading's underline
5589+
included. `range` is its section: from the start of its first line to the start
5590+
of the line of the next heading of the same or a higher level, or to the end of
5591+
the source.
5592+
5593+
Hosts request the outline off their window thread, discard a response to an
5594+
older revision of the source, and bound the source size they send as they bound
5595+
the preview's.
5596+
5597+
Shared examples: `rust/fixtures/editor/markdown-outline-v1.json`.
5598+
55625599
### Structured logging of recoverable LSP maintenance warnings
55635600

55645601
`lsp.pollEvents` log observations may carry the existing `error` object even at

‎rust/crates/core/src/protocol/command.rs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,8 @@ pub enum CoreCommand {
126126
ProcessLifecycleSettle,
127127
/// Renders and sanitizes shared Markdown (`markdown.render`).
128128
MarkdownRender,
129+
/// Outlines the headings of shared Markdown as document symbols (`markdown.outline`).
130+
MarkdownOutline,
129131
/// Decides what a link or an image of a rendered Markdown document points at
130132
/// (`markdown.resolveReference`).
131133
MarkdownResolveReference,
@@ -1187,6 +1189,7 @@ impl CoreCommand {
11871189
"processLifecycle.inventory" => Some(Self::ProcessLifecycleInventory),
11881190
"processLifecycle.settle" => Some(Self::ProcessLifecycleSettle),
11891191
"markdown.render" => Some(Self::MarkdownRender),
1192+
"markdown.outline" => Some(Self::MarkdownOutline),
11901193
"markdown.resolveReference" => Some(Self::MarkdownResolveReference),
11911194
"keymap.parseContext" => Some(Self::Keymap(KeymapCommand::ParseContext)),
11921195
"keymap.evaluateContext" => Some(Self::Keymap(KeymapCommand::EvaluateContext)),

‎rust/crates/core/src/runtime/dispatcher.rs‎

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@
44
//! child module named after it; the remaining small families dispatch here.
55
66
use crate::project::{
7-
self, DocumentLifecycleRequest, FileReadRequest, FileWriteRequest, MarkdownReferenceRequest,
8-
MarkdownRenderRequest,
7+
self, DocumentLifecycleRequest, FileReadRequest, FileWriteRequest, MarkdownOutlineRequest,
8+
MarkdownReferenceRequest, MarkdownRenderRequest,
99
};
1010
use crate::protocol::{CoreCommand, CoreError, CoreRequest, CoreResponse, ErrorCode, GitCommand};
1111
use lithe_github::{NormalizeResponseRequest, ParseRemoteRequest, RequestPlanRequest};
@@ -456,6 +456,24 @@ fn execute_parsed(mut parsed: CoreRequest, document: Option<&str>) -> CoreRespon
456456
Err(error) => CoreResponse::failure(id, error),
457457
}
458458
}
459+
CoreCommand::MarkdownOutline => {
460+
match serde_json::from_value::<MarkdownOutlineRequest>(parsed.payload).map_err(
461+
|error| {
462+
CoreError::new(
463+
ErrorCode::InvalidRequest,
464+
"Invalid Markdown outline request",
465+
)
466+
.with_details(error.to_string())
467+
},
468+
) {
469+
Ok(request) => CoreResponse::success(
470+
id,
471+
serde_json::to_value(crate::project::outline(request))
472+
.expect("Markdown outline response should encode"),
473+
),
474+
Err(error) => CoreResponse::failure(id, error),
475+
}
476+
}
459477
CoreCommand::MarkdownResolveReference => {
460478
match serde_json::from_value::<MarkdownReferenceRequest>(parsed.payload).map_err(
461479
|error| {

‎rust/crates/core/src/runtime/request_trace.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,7 @@ pub(crate) fn is_hot(method: &str) -> bool {
154154
"document.classifyText"
155155
| "document.lifecycle"
156156
| "markdown.render"
157+
| "markdown.outline"
157158
| "markdown.resolveReference"
158159
| "workspace.classifyVisibility"
159160
| "workspace.visibilityDefaults"

‎rust/crates/core/src/tests/project.rs‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -926,6 +926,39 @@ fn markdown_render_command_returns_sanitized_html() {
926926
assert!(!html.contains("alert(1)"));
927927
}
928928

929+
#[test]
930+
fn markdown_outline_command_answers_the_shared_fixture() {
931+
let fixture: Value = serde_json::from_str(include_str!(
932+
"../../../../fixtures/editor/markdown-outline-v1.json"
933+
))
934+
.expect("Markdown outline fixture should decode");
935+
for case in fixture["cases"].as_array().expect("fixture cases") {
936+
let request = serde_json::json!({
937+
"id": "markdown-outline-1",
938+
"command": "markdown.outline",
939+
"payload": {"source": case["source"]}
940+
});
941+
let response: Value = serde_json::from_str(&execute_json(
942+
&serde_json::to_string(&request).expect("outline request should encode"),
943+
))
944+
.expect("outline response should be JSON");
945+
946+
assert_eq!(response["ok"], true, "{}: {response}", case["name"]);
947+
assert_eq!(response["data"], case["expected"], "{}", case["name"]);
948+
}
949+
}
950+
951+
#[test]
952+
fn markdown_outline_command_rejects_a_payload_without_source() {
953+
let response: Value = serde_json::from_str(&execute_json(
954+
r#"{"id":"markdown-outline-2","command":"markdown.outline","payload":{}}"#,
955+
))
956+
.expect("outline response should be JSON");
957+
958+
assert_eq!(response["ok"], false);
959+
assert_eq!(response["error"]["code"], "invalid_request");
960+
}
961+
929962
#[test]
930963
fn markdown_resolve_reference_command_answers_links_and_resources() {
931964
let resolve = |reference: &str, purpose: &str| -> Value {

‎rust/crates/project/Cargo.toml‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ name = "lithe-project"
33
version = "0.1.0"
44
edition = "2021"
55
license = "Apache-2.0"
6-
description = "Project services for Lithe: workspace files, indexing policy, search, local history and document rendering"
6+
description = "Project services for Lithe: workspace files, indexing policy, search, local history, document rendering and Markdown outlines"
77

88
[features]
99
# Lets lithe-core's tests trace which directories a workspace scan enumerates.
@@ -19,6 +19,7 @@ lithe-diagnostics = { path = "../diagnostics" }
1919
lithe-git = { path = "../git" }
2020
lithe-protocol = { path = "../protocol" }
2121
lithe-request-context = { path = "../request-context" }
22+
lithe-text = { path = "../text" }
2223
lithe-workspace = { path = "../workspace" }
2324
regex = "1.11"
2425
serde = { version = "1.0", features = ["derive"] }

‎rust/crates/project/src/lib.rs‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
//! Project services: workspace files and visibility, indexing policy, search, local history,
2-
//! document persistence decisions and Markdown rendering.
2+
//! document persistence decisions, and Markdown rendering and heading outlines.
33
//!
44
//! Language-server sessions sit above this crate. Calls that change indexing or the search index
55
//! take an `update_providers` callback, which lithe-core uses to tell running sessions which
@@ -16,6 +16,7 @@ pub mod files;
1616
mod history;
1717
pub mod indexing;
1818
mod markdown;
19+
mod markdown_outline;
1920
mod markdown_reference;
2021
mod name_matching;
2122
pub mod name_ranking;
@@ -27,6 +28,7 @@ pub use document_lifecycle::*;
2728
pub use files::*;
2829
pub use history::*;
2930
pub use markdown::*;
31+
pub use markdown_outline::*;
3032
pub use markdown_reference::*;
3133
pub use search_paging::{search_page, SearchPageRequest};
3234

‎rust/crates/project/src/markdown.rs‎

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -195,13 +195,10 @@ pub struct MarkdownRenderResponse {
195195
pub html: String,
196196
}
197197

198-
/// Renders the shared Markdown dialect used by every Lithe frontend.
199-
///
200-
/// Raw HTML is deliberately enabled in Comrak so useful document elements such
201-
/// as `<details>` survive parsing, then the complete fragment is passed through
202-
/// Ammonia. This keeps formatting HTML while removing executable content,
203-
/// event handlers, embeds, and unsafe URL schemes.
204-
pub fn render(request: MarkdownRenderRequest) -> MarkdownRenderResponse {
198+
/// The Comrak options of the shared dialect. Rendering and the heading outline
199+
/// parse with the same options, so a heading the preview shows is a heading the
200+
/// outline lists, on the same source line.
201+
pub(crate) fn dialect() -> Options<'static> {
205202
let mut options = Options::default();
206203
options.extension.strikethrough = true;
207204
// The final Ammonia pass is the security boundary. Leaving tagfilter off
@@ -226,8 +223,17 @@ pub fn render(request: MarkdownRenderRequest) -> MarkdownRenderResponse {
226223
options.extension.header_id_prefix_in_href = true;
227224
options.render.r#unsafe = true;
228225
options.render.sourcepos = true;
226+
options
227+
}
229228

230-
let rendered = markdown_to_html(&request.source, &options);
229+
/// Renders the shared Markdown dialect used by every Lithe frontend.
230+
///
231+
/// Raw HTML is deliberately enabled in Comrak so useful document elements such
232+
/// as `<details>` survive parsing, then the complete fragment is passed through
233+
/// Ammonia. This keeps formatting HTML while removing executable content,
234+
/// event handlers, embeds, and unsafe URL schemes.
235+
pub fn render(request: MarkdownRenderRequest) -> MarkdownRenderResponse {
236+
let rendered = markdown_to_html(&request.source, &dialect());
231237
let mut sanitizer = Builder::default();
232238
sanitizer
233239
.add_tags(&["section", "tfoot", "input", "audio", "video", "source"])

0 commit comments

Comments
 (0)