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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
//! Cheap, regex-based outline extraction for languages without an LSP
//! attached (or while one is starting up). Identifies function / class /
//! struct / module definitions and emits them as `DocumentSymbol`s the
//! existing outline pane already knows how to render.
//!
//! Languages covered: `rs` `py` `js` `jsx` `ts` `tsx` `go` `rb` `c` `cpp`
//! `coffee` `yaml`.
//! Anything else returns an empty list (callers can fall through to the
//! markdown extractor or just show "(no symbols)").
//!
//! Patterns are intentionally conservative — they target the common case
//! and skip clever things (decorators, generics, comma-separated `let`s,
//! macro-defined functions). Tree-sitter `tags.scm` queries would be more
//! accurate; this exists because it ships in 50 lines instead of 500.
use crate::lsp::DocumentSymbol;
use regex::Regex;
use std::sync::OnceLock;
/// Public entry — `(text, ext)` → flat list of symbols with approximate
/// depth derived from leading whitespace. Lines are 0-based; the outline
/// pane handles display.
///
/// Depth heuristic: each leading tab = one depth level, plus
/// `leading_spaces / 4` (best-guess indent width; configurable indent
/// detection would be nicer but this matches the common case for
/// rust / js / ts / py / rb / c / go where conventional indentation is
/// 2 or 4 spaces / 1 tab per scope). Sufficient for nested-method
/// rendering under classes / structs / impls.
pub fn extract_symbols(text: &str, ext: &str) -> Vec<DocumentSymbol> {
let patterns = patterns_for(ext);
if patterns.is_empty() {
return Vec::new();
}
let mut out: Vec<DocumentSymbol> = Vec::new();
for (line_no, line) in text.lines().enumerate() {
for (re, kind) in patterns {
if let Some(cap) = re.captures(line)
&& let Some(name) = cap.name("name").or_else(|| cap.get(1))
{
// multilang 3rd 2026-06-28 F5: Go methods carry
// their receiver type as an OPTIONAL named capture
// `recv` so the outline can disambiguate
// `Router.Handle` from `Handle`. Other languages
// ignore the second capture.
let display_name = if let Some(recv) = cap.name("recv") {
let recv_clean = recv
.as_str()
.split_whitespace()
.last()
.unwrap_or(recv.as_str())
.trim_start_matches('*');
format!("{}.{}", recv_clean, name.as_str())
} else {
name.as_str().to_string()
};
out.push(DocumentSymbol {
name: display_name,
kind,
line: line_no as u32,
character: line[..name.start()].chars().count() as u32,
depth: indent_depth(line),
});
break; // one match per line
}
}
}
out
}
/// Count leading-indent depth: each `\t` = 1, each 4 leading spaces = 1.
/// Mixed indents (rare) sum both. Capped at 8 so a wildly-indented line
/// doesn't push the outline column past the panel width.
fn indent_depth(line: &str) -> u32 {
let mut tabs = 0u32;
let mut spaces = 0u32;
for ch in line.chars() {
match ch {
'\t' => tabs += 1,
' ' => spaces += 1,
_ => break,
}
}
(tabs + spaces / 4).min(8)
}
/// Per-language pattern list (regex + symbol kind label). Cached behind
/// `OnceLock` so the regexes compile once.
fn patterns_for(ext: &str) -> &'static [(Regex, &'static str)] {
match ext {
"rs" => rust_patterns(),
"py" => python_patterns(),
"js" | "jsx" | "mjs" | "cjs" => js_patterns(),
"ts" | "tsx" => ts_patterns(),
"go" => go_patterns(),
"rb" => ruby_patterns(),
"c" | "h" => c_patterns(),
"cpp" | "cc" | "hpp" | "cxx" => cpp_patterns(),
"coffee" => coffee_patterns(),
"yaml" | "yml" => yaml_patterns(),
_ => &[],
}
}
macro_rules! patterns {
($cell:ident, [ $( ($pat:expr, $kind:expr) ),* $(,)? ]) => {{
static $cell: OnceLock<Vec<(Regex, &'static str)>> = OnceLock::new();
$cell.get_or_init(|| {
vec![
$(
(Regex::new($pat).expect("static regex compiles"), $kind),
)*
]
}).as_slice()
}};
}
fn rust_patterns() -> &'static [(Regex, &'static str)] {
patterns!(
RUST,
[
(
r"^\s*(?:pub(?:\([^)]+\))?\s+)?(?:async\s+)?fn\s+([A-Za-z_][A-Za-z0-9_]*)",
"fn"
),
(
r"^\s*(?:pub(?:\([^)]+\))?\s+)?struct\s+([A-Za-z_][A-Za-z0-9_]*)",
"struct"
),
(
r"^\s*(?:pub(?:\([^)]+\))?\s+)?enum\s+([A-Za-z_][A-Za-z0-9_]*)",
"enum"
),
(
r"^\s*(?:pub(?:\([^)]+\))?\s+)?trait\s+([A-Za-z_][A-Za-z0-9_]*)",
"trait"
),
(r"^\s*impl(?:<[^>]*>)?\s+([A-Za-z_][A-Za-z0-9_]*)", "impl"),
(
r"^\s*(?:pub(?:\([^)]+\))?\s+)?mod\s+([A-Za-z_][A-Za-z0-9_]*)",
"mod"
),
(
r"^\s*(?:pub(?:\([^)]+\))?\s+)?type\s+([A-Za-z_][A-Za-z0-9_]*)",
"type"
),
(
r"^\s*(?:pub(?:\([^)]+\))?\s+)?const\s+([A-Z_][A-Z0-9_]*)",
"const"
),
]
)
}
fn python_patterns() -> &'static [(Regex, &'static str)] {
patterns!(
PYTHON,
[
(r"^\s*(?:async\s+)?def\s+([A-Za-z_][A-Za-z0-9_]*)", "fn"),
(r"^\s*class\s+([A-Za-z_][A-Za-z0-9_]*)", "class"),
]
)
}
fn js_patterns() -> &'static [(Regex, &'static str)] {
patterns!(
JS,
[
(
r"^\s*(?:export\s+(?:default\s+)?)?(?:async\s+)?function\s*\*?\s*([A-Za-z_$][A-Za-z0-9_$]*)",
"fn"
),
(
r"^\s*(?:export\s+(?:default\s+)?)?class\s+([A-Za-z_$][A-Za-z0-9_$]*)",
"class"
),
(
r"^\s*(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*=\s*(?:async\s+)?(?:function|\([^)]*\)\s*=>)",
"fn"
),
]
)
}
fn ts_patterns() -> &'static [(Regex, &'static str)] {
patterns!(
TS,
[
(
r"^\s*(?:export\s+(?:default\s+)?)?(?:async\s+)?function\s*\*?\s*([A-Za-z_$][A-Za-z0-9_$]*)",
"fn"
),
(
r"^\s*(?:export\s+(?:default\s+)?)?class\s+([A-Za-z_$][A-Za-z0-9_$]*)",
"class"
),
(
r"^\s*(?:export\s+(?:default\s+)?)?interface\s+([A-Za-z_$][A-Za-z0-9_$]*)",
"interface"
),
(
r"^\s*(?:export\s+(?:default\s+)?)?type\s+([A-Za-z_$][A-Za-z0-9_$]*)",
"type"
),
(
r"^\s*(?:export\s+(?:default\s+)?)?enum\s+([A-Za-z_$][A-Za-z0-9_$]*)",
"enum"
),
(
r"^\s*(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*[:=]\s*(?:async\s+)?(?:function|\([^)]*\)\s*=>)",
"fn"
),
// multilang-redo 2026-06-28 F2: React.FC + typed arrow
// form — `const App: React.FC<Props> = ({...}) => ...`.
// The prior pattern's `[:=]\s*(?:function|\(` couldn't
// span across the type annotation. Capture the name
// immediately after const/let/var when ANY type-ish
// expression precedes the `= (` arrow.
//
// multilang 3rd 2026-06-28 SEV-3: handle callback types
// in generics — `React.FC<{ onClick: () => void }>`.
// The earlier `[^=]+` greedy match terminated on the
// first `=` it found (the one inside `=>`), so this
// pattern silently missed components with callback
// props. The `(?:[^=]|=>)+?` alternation matches the
// literal `=>` as a unit, so the type-annotation match
// doesn't break on it.
(
r"^\s*(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*:\s*(?:[^=]|=>)+?\s*=\s*(?:async\s+)?\([^)]*\)\s*=>",
"fn"
),
]
)
}
fn go_patterns() -> &'static [(Regex, &'static str)] {
patterns!(
GO,
[
// multilang 3rd 2026-06-28 F5: capture receiver as
// `recv` named group so methods show as `Router.Handle`
// instead of just `Handle`. `recv` is optional — plain
// functions like `func Handle(...)` still match.
(
r"^func(?:\s+\((?P<recv>[^)]+)\))?\s+(?P<name>[A-Za-z_][A-Za-z0-9_]*)",
"fn"
),
(r"^type\s+([A-Za-z_][A-Za-z0-9_]*)", "type"),
]
)
}
fn ruby_patterns() -> &'static [(Regex, &'static str)] {
patterns!(
RUBY,
[
(r"^\s*def\s+(?:self\.)?([A-Za-z_][A-Za-z0-9_]*[!?=]?)", "fn"),
(r"^\s*class\s+([A-Za-z_][A-Za-z0-9_]*)", "class"),
(r"^\s*module\s+([A-Za-z_][A-Za-z0-9_]*)", "module"),
]
)
}
fn c_patterns() -> &'static [(Regex, &'static str)] {
// C is hard without a real parser. Match `<type> <name>(`-like shapes
// at column 0. Skips static & inline since they're often mis-parsed.
patterns!(
C,
[
(
r"^[A-Za-z_][A-Za-z_0-9*\s]*\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(",
"fn"
),
(
r"^\s*typedef\s+(?:struct|enum|union)?\s*[A-Za-z_0-9\s{}]*\b([A-Za-z_][A-Za-z0-9_]*)\s*;",
"type"
),
]
)
}
fn cpp_patterns() -> &'static [(Regex, &'static str)] {
patterns!(
CPP,
[
(
r"^[A-Za-z_][A-Za-z_0-9:*<>\s,&]*\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(",
"fn"
),
(r"^\s*class\s+([A-Za-z_][A-Za-z0-9_]*)", "class"),
(r"^\s*struct\s+([A-Za-z_][A-Za-z0-9_]*)", "struct"),
(r"^\s*namespace\s+([A-Za-z_][A-Za-z0-9_]*)", "namespace"),
]
)
}
fn coffee_patterns() -> &'static [(Regex, &'static str)] {
// CoffeeScript — indent-scoped. Functions are `name = (args) ->` or
// `name: (args) ->` (object-property form); classes are `class Name`.
patterns!(
COFFEE,
[
(r"^\s*class\s+([A-Za-z_$][\w$.]*)", "class"),
(
r"^\s*([A-Za-z_$][\w$]*)\s*[:=]\s*(?:\([^)]*\)\s*)?[-=]>",
"fn"
),
]
)
}
fn yaml_patterns() -> &'static [(Regex, &'static str)] {
// YAML has no functions/classes — the meaningful structural unit is
// a mapping/sequence-heading key (`key:` with the value on indented
// lines below). Emitting those as `namespace` lets the indent-scope
// text objects (`ic` / `ac`) select a config block. Leaf `key: val`
// lines have content after the colon and are intentionally skipped.
patterns!(YAML, [(r"^\s*([\w.-]+):\s*$", "namespace")])
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rust_extracts_fn_struct_enum_impl() {
let src = "\
pub fn outer() {}
struct S {}
enum E { A, B }
impl S {
pub fn method(&self) {}
async fn other(&self) {}
}
trait T {}
mod inner {}
const MAX_N: usize = 10;
";
let s = extract_symbols(src, "rs");
let names: Vec<&str> = s.iter().map(|x| x.name.as_str()).collect();
assert_eq!(
names,
vec![
"outer", "S", "E", "S", "method", "other", "T", "inner", "MAX_N"
]
);
let kinds: Vec<&'static str> = s.iter().map(|x| x.kind).collect();
assert_eq!(
kinds,
vec![
"fn", "struct", "enum", "impl", "fn", "fn", "trait", "mod", "const"
]
);
}
#[test]
fn python_extracts_def_and_class() {
let src = "\
def top():
pass
class Foo:
def method(self):
pass
async def amethod(self):
pass
";
let s = extract_symbols(src, "py");
let names: Vec<&str> = s.iter().map(|x| x.name.as_str()).collect();
assert_eq!(names, vec!["top", "Foo", "method", "amethod"]);
}
#[test]
fn ts_extracts_function_class_interface_type() {
let src = "\
export function hello() {}
class Box {}
export interface Shape {}
type Aliased = string;
const arrow = () => 42;
";
let s = extract_symbols(src, "ts");
let names: Vec<&str> = s.iter().map(|x| x.name.as_str()).collect();
assert_eq!(names, vec!["hello", "Box", "Shape", "Aliased", "arrow"]);
}
#[test]
fn go_extracts_func_and_type() {
let src = "\
func Foo() {}
func (s *Bar) Method() {}
type Baz struct{}
";
let s = extract_symbols(src, "go");
let names: Vec<&str> = s.iter().map(|x| x.name.as_str()).collect();
// multilang 3rd F5: method shows as `Receiver.Name` when
// the func has a receiver. Plain functions and types
// continue to use the bare name.
assert_eq!(names, vec!["Foo", "Bar.Method", "Baz"]);
}
#[test]
fn unknown_ext_returns_empty() {
let s = extract_symbols("anything goes here", "xyz");
assert!(s.is_empty());
}
#[test]
fn indent_depth_counts_tabs_and_spaces() {
assert_eq!(indent_depth("no_indent"), 0);
assert_eq!(indent_depth(" four_spaces"), 1);
assert_eq!(indent_depth(" eight_spaces"), 2);
assert_eq!(indent_depth("\tone_tab"), 1);
assert_eq!(indent_depth("\t\t\tthree_tabs"), 3);
// Mixed: 1 tab + 4 spaces = depth 2.
assert_eq!(indent_depth("\t mixed"), 2);
// Partial groups under 4 spaces don't bump.
assert_eq!(indent_depth(" two_spaces"), 0);
}
#[test]
fn rust_impl_methods_get_depth_1() {
// Conventional 4-space rust indent: methods inside `impl` get depth 1
// so the outline pane indents them under the impl header.
let src = "\
impl S {
pub fn method(&self) {}
async fn other(&self) {}
}
";
let s = extract_symbols(src, "rs");
// First symbol is the impl header at depth 0; next two are methods at depth 1.
assert_eq!(s[0].name, "S");
assert_eq!(s[0].depth, 0);
assert_eq!(s[1].name, "method");
assert_eq!(s[1].depth, 1);
assert_eq!(s[2].name, "other");
assert_eq!(s[2].depth, 1);
}
#[test]
fn python_class_methods_get_depth_1() {
let src = "\
class Foo:
def method(self):
pass
async def amethod(self):
pass
";
let s = extract_symbols(src, "py");
// class at depth 0; both methods at depth 1.
assert_eq!(s[0].name, "Foo");
assert_eq!(s[0].depth, 0);
assert_eq!(s[1].name, "method");
assert_eq!(s[1].depth, 1);
assert_eq!(s[2].name, "amethod");
assert_eq!(s[2].depth, 1);
}
#[test]
fn coffeescript_extracts_class_and_functions() {
let src = "\
class Animal
speak: ->
'noise'
greet = (name) ->
console.log name
anon = ->
42
";
let s = extract_symbols(src, "coffee");
let names: Vec<&str> = s.iter().map(|x| x.name.as_str()).collect();
assert_eq!(names, vec!["Animal", "speak", "greet", "anon"]);
let kinds: Vec<&'static str> = s.iter().map(|x| x.kind).collect();
assert_eq!(kinds, vec!["class", "fn", "fn", "fn"]);
}
#[test]
fn yaml_extracts_block_heading_keys_only() {
let src = "\
server:
host: localhost
port: 8080
database:
name: app
debug: true
";
let s = extract_symbols(src, "yaml");
// Only `server:` and `database:` head a block; leaf `key: value`
// lines (host / port / name / debug) are skipped.
let names: Vec<&str> = s.iter().map(|x| x.name.as_str()).collect();
assert_eq!(names, vec!["server", "database"]);
assert!(s.iter().all(|x| x.kind == "namespace"));
}
}