1use anyhow::{Context, Result};
2use mdbook::BookItem;
3use mdbook::book::{Book, Chapter};
4use mdbook::preprocess::CmdPreprocessor;
5use regex::Regex;
6use settings::KeymapFile;
7use std::borrow::Cow;
8use std::collections::{HashMap, HashSet};
9use std::io::{self, Read};
10use std::process;
11use std::sync::{LazyLock, OnceLock};
12
13static KEYMAP_MACOS: LazyLock<KeymapFile> = LazyLock::new(|| {
14 load_keymap("keymaps/default-macos.json").expect("Failed to load MacOS keymap")
15});
16
17static KEYMAP_LINUX: LazyLock<KeymapFile> = LazyLock::new(|| {
18 load_keymap("keymaps/default-linux.json").expect("Failed to load Linux keymap")
19});
20
21static KEYMAP_WINDOWS: LazyLock<KeymapFile> = LazyLock::new(|| {
22 load_keymap("keymaps/default-windows.json").expect("Failed to load Windows keymap")
23});
24
25static ALL_ACTIONS: LazyLock<Vec<ActionDef>> = LazyLock::new(dump_all_gpui_actions);
26
27const FRONT_MATTER_COMMENT: &str = "<!-- ZED_META {} -->";
28
29fn main() -> Result<()> {
30 zlog::init();
31 zlog::init_output_stderr();
32 // call a zed:: function so everything in `zed` crate is linked and
33 // all actions in the actual app are registered
34 zed::stdout_is_a_pty();
35 let args = std::env::args().skip(1).collect::<Vec<_>>();
36
37 match args.get(0).map(String::as_str) {
38 Some("supports") => {
39 let renderer = args.get(1).expect("Required argument");
40 let supported = renderer != "not-supported";
41 if supported {
42 process::exit(0);
43 } else {
44 process::exit(1);
45 }
46 }
47 Some("postprocess") => handle_postprocessing()?,
48 _ => handle_preprocessing()?,
49 }
50
51 Ok(())
52}
53
54#[derive(Debug, Clone, PartialEq, Eq, Hash)]
55enum PreprocessorError {
56 ActionNotFound {
57 action_name: String,
58 },
59 DeprecatedActionUsed {
60 used: String,
61 should_be: String,
62 },
63 InvalidFrontmatterLine(String),
64 InvalidSettingsJson {
65 file: std::path::PathBuf,
66 line: usize,
67 snippet: String,
68 error: String,
69 },
70}
71
72impl PreprocessorError {
73 fn new_for_not_found_action(action_name: String) -> Self {
74 for action in &*ALL_ACTIONS {
75 for alias in action.deprecated_aliases {
76 if alias == &action_name {
77 return PreprocessorError::DeprecatedActionUsed {
78 used: action_name,
79 should_be: action.name.to_string(),
80 };
81 }
82 }
83 }
84 PreprocessorError::ActionNotFound { action_name }
85 }
86
87 fn new_for_invalid_settings_json(
88 chapter: &Chapter,
89 location: usize,
90 snippet: String,
91 error: String,
92 ) -> Self {
93 PreprocessorError::InvalidSettingsJson {
94 file: chapter.path.clone().expect("chapter has path"),
95 line: chapter.content[..location].lines().count() + 1,
96 snippet,
97 error,
98 }
99 }
100}
101
102impl std::fmt::Display for PreprocessorError {
103 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
104 match self {
105 PreprocessorError::InvalidFrontmatterLine(line) => {
106 write!(f, "Invalid frontmatter line: {}", line)
107 }
108 PreprocessorError::ActionNotFound { action_name } => {
109 write!(f, "Action not found: {}", action_name)
110 }
111 PreprocessorError::DeprecatedActionUsed { used, should_be } => write!(
112 f,
113 "Deprecated action used: {} should be {}",
114 used, should_be
115 ),
116 PreprocessorError::InvalidSettingsJson {
117 file,
118 line,
119 snippet,
120 error,
121 } => {
122 write!(
123 f,
124 "Invalid settings JSON at {}:{}\nError: {}\n\n{}",
125 file.display(),
126 line,
127 error,
128 snippet
129 )
130 }
131 }
132 }
133}
134
135fn handle_preprocessing() -> Result<()> {
136 let mut stdin = io::stdin();
137 let mut input = String::new();
138 stdin.read_to_string(&mut input)?;
139
140 let (_ctx, mut book) = CmdPreprocessor::parse_input(input.as_bytes())?;
141
142 let mut errors = HashSet::<PreprocessorError>::new();
143 handle_frontmatter(&mut book, &mut errors);
144 template_big_table_of_actions(&mut book);
145 template_and_validate_keybindings(&mut book, &mut errors);
146 template_and_validate_actions(&mut book, &mut errors);
147 template_and_validate_json_snippets(&mut book, &mut errors);
148
149 if !errors.is_empty() {
150 const ANSI_RED: &str = "\x1b[31m";
151 const ANSI_RESET: &str = "\x1b[0m";
152 for error in &errors {
153 eprintln!("{ANSI_RED}ERROR{ANSI_RESET}: {}", error);
154 }
155 return Err(anyhow::anyhow!("Found {} errors in docs", errors.len()));
156 }
157
158 serde_json::to_writer(io::stdout(), &book)?;
159
160 Ok(())
161}
162
163fn handle_frontmatter(book: &mut Book, errors: &mut HashSet<PreprocessorError>) {
164 let frontmatter_regex = Regex::new(r"(?s)^\s*---(.*?)---").unwrap();
165 for_each_chapter_mut(book, |chapter| {
166 let new_content = frontmatter_regex.replace(&chapter.content, |caps: ®ex::Captures| {
167 let frontmatter = caps[1].trim();
168 let frontmatter = frontmatter.trim_matches(&[' ', '-', '\n']);
169 let mut metadata = HashMap::<String, String>::default();
170 for line in frontmatter.lines() {
171 let Some((name, value)) = line.split_once(':') else {
172 errors.insert(PreprocessorError::InvalidFrontmatterLine(format!(
173 "{}: {}",
174 chapter_breadcrumbs(chapter),
175 line
176 )));
177 continue;
178 };
179 let name = name.trim();
180 let value = value.trim();
181 metadata.insert(name.to_string(), value.to_string());
182 }
183 FRONT_MATTER_COMMENT.replace(
184 "{}",
185 &serde_json::to_string(&metadata).expect("Failed to serialize metadata"),
186 )
187 });
188 if let Cow::Owned(content) = new_content {
189 chapter.content = content;
190 }
191 });
192}
193
194fn template_big_table_of_actions(book: &mut Book) {
195 for_each_chapter_mut(book, |chapter| {
196 let needle = "{#ACTIONS_TABLE#}";
197 if let Some(start) = chapter.content.rfind(needle) {
198 chapter.content.replace_range(
199 start..start + needle.len(),
200 &generate_big_table_of_actions(),
201 );
202 }
203 });
204}
205
206fn template_and_validate_keybindings(book: &mut Book, errors: &mut HashSet<PreprocessorError>) {
207 let regex = Regex::new(r"\{#kb (.*?)\}").unwrap();
208
209 for_each_chapter_mut(book, |chapter| {
210 chapter.content = regex
211 .replace_all(&chapter.content, |caps: ®ex::Captures| {
212 let action = caps[1].trim();
213 if find_action_by_name(action).is_none() {
214 errors.insert(PreprocessorError::new_for_not_found_action(
215 action.to_string(),
216 ));
217 return String::new();
218 }
219 let macos_binding = find_binding("macos", action).unwrap_or_default();
220 let linux_binding = find_binding("linux", action).unwrap_or_default();
221
222 if macos_binding.is_empty() && linux_binding.is_empty() {
223 return "<div>No default binding</div>".to_string();
224 }
225
226 format!("<kbd class=\"keybinding\">{macos_binding}|{linux_binding}</kbd>")
227 })
228 .into_owned()
229 });
230}
231
232fn template_and_validate_actions(book: &mut Book, errors: &mut HashSet<PreprocessorError>) {
233 let regex = Regex::new(r"\{#action (.*?)\}").unwrap();
234
235 for_each_chapter_mut(book, |chapter| {
236 chapter.content = regex
237 .replace_all(&chapter.content, |caps: ®ex::Captures| {
238 let name = caps[1].trim();
239 let Some(action) = find_action_by_name(name) else {
240 errors.insert(PreprocessorError::new_for_not_found_action(
241 name.to_string(),
242 ));
243 return String::new();
244 };
245 format!("<code class=\"hljs\">{}</code>", &action.human_name)
246 })
247 .into_owned()
248 });
249}
250
251fn find_action_by_name(name: &str) -> Option<&ActionDef> {
252 ALL_ACTIONS
253 .binary_search_by(|action| action.name.cmp(name))
254 .ok()
255 .map(|index| &ALL_ACTIONS[index])
256}
257
258fn find_binding(os: &str, action: &str) -> Option<String> {
259 let keymap = match os {
260 "macos" => &KEYMAP_MACOS,
261 "linux" | "freebsd" => &KEYMAP_LINUX,
262 "windows" => &KEYMAP_WINDOWS,
263 _ => unreachable!("Not a valid OS: {}", os),
264 };
265
266 // Find the binding in reverse order, as the last binding takes precedence.
267 keymap.sections().rev().find_map(|section| {
268 section.bindings().rev().find_map(|(keystroke, a)| {
269 if name_for_action(a.to_string()) == action {
270 Some(keystroke.to_string())
271 } else {
272 None
273 }
274 })
275 })
276}
277
278fn template_and_validate_json_snippets(book: &mut Book, errors: &mut HashSet<PreprocessorError>) {
279 fn for_each_labeled_code_block_mut(
280 book: &mut Book,
281 errors: &mut HashSet<PreprocessorError>,
282 f: impl Fn(&str, &str) -> anyhow::Result<()>,
283 ) {
284 const TAGGED_JSON_BLOCK_START: &'static str = "```json [";
285 const JSON_BLOCK_END: &'static str = "```";
286
287 for_each_chapter_mut(book, |chapter| {
288 let mut offset = 0;
289 while let Some(loc) = chapter.content[offset..].find(TAGGED_JSON_BLOCK_START) {
290 let loc = loc + offset;
291 let tag_start = loc + TAGGED_JSON_BLOCK_START.len();
292 offset = tag_start;
293 let Some(tag_end) = chapter.content[tag_start..].find(']') else {
294 errors.insert(PreprocessorError::new_for_invalid_settings_json(
295 chapter,
296 loc,
297 chapter.content[loc..tag_start].to_string(),
298 "Unclosed JSON block tag".to_string(),
299 ));
300 continue;
301 };
302 let tag_end = tag_end + tag_start;
303
304 let tag = &chapter.content[tag_start..tag_end];
305
306 if tag.contains('\n') {
307 errors.insert(PreprocessorError::new_for_invalid_settings_json(
308 chapter,
309 loc,
310 chapter.content[loc..tag_start].to_string(),
311 "Unclosed JSON block tag".to_string(),
312 ));
313 continue;
314 }
315
316 let snippet_start = tag_end + 1;
317 offset = snippet_start;
318
319 let Some(snippet_end) = chapter.content[snippet_start..].find(JSON_BLOCK_END)
320 else {
321 errors.insert(PreprocessorError::new_for_invalid_settings_json(
322 chapter,
323 loc,
324 chapter.content[loc..tag_end + 1].to_string(),
325 "Missing closing code block".to_string(),
326 ));
327 continue;
328 };
329 let snippet_end = snippet_start + snippet_end;
330 let snippet_json = &chapter.content[snippet_start..snippet_end];
331 offset = snippet_end + 3;
332
333 if let Err(err) = f(tag, snippet_json) {
334 errors.insert(PreprocessorError::new_for_invalid_settings_json(
335 chapter,
336 loc,
337 chapter.content[loc..snippet_end + 3].to_string(),
338 err.to_string(),
339 ));
340 continue;
341 };
342 let tag_range_complete = tag_start - 1..tag_end + 1;
343 offset -= tag_range_complete.len();
344 chapter.content.replace_range(tag_range_complete, "");
345 }
346 });
347 }
348
349 for_each_labeled_code_block_mut(book, errors, |label, snippet_json| {
350 let mut snippet_json_fixed = snippet_json
351 .to_string()
352 .replace("\n>", "\n")
353 .trim()
354 .to_string();
355 while snippet_json_fixed.starts_with("//") {
356 if let Some(line_end) = snippet_json_fixed.find('\n') {
357 snippet_json_fixed.replace_range(0..line_end, "");
358 snippet_json_fixed = snippet_json_fixed.trim().to_string();
359 }
360 }
361 match label {
362 "settings" => {
363 if !snippet_json_fixed.starts_with('{') || !snippet_json_fixed.ends_with('}') {
364 snippet_json_fixed.insert(0, '{');
365 snippet_json_fixed.push_str("\n}");
366 }
367 settings::parse_json_with_comments::<settings::SettingsContent>(
368 &snippet_json_fixed,
369 )?;
370 }
371 "keymap" => {
372 if !snippet_json_fixed.starts_with('[') || !snippet_json_fixed.ends_with(']') {
373 snippet_json_fixed.insert(0, '[');
374 snippet_json_fixed.push_str("\n]");
375 }
376
377 let keymap = settings::KeymapFile::parse(&snippet_json_fixed)
378 .context("Failed to parse keymap JSON")?;
379 for section in keymap.sections() {
380 for (keystrokes, action) in section.bindings() {
381 keystrokes
382 .split_whitespace()
383 .map(|source| gpui::Keystroke::parse(source))
384 .collect::<std::result::Result<Vec<_>, _>>()
385 .context("Failed to parse keystroke")?;
386 if let Some((action_name, _)) = settings::KeymapFile::parse_action(action)
387 .map_err(|err| anyhow::format_err!(err))
388 .context("Failed to parse action")?
389 {
390 anyhow::ensure!(
391 find_action_by_name(action_name).is_some(),
392 "Action not found: {}",
393 action_name
394 );
395 }
396 }
397 }
398 }
399 "debug" => {
400 if !snippet_json_fixed.starts_with('[') || !snippet_json_fixed.ends_with(']') {
401 snippet_json_fixed.insert(0, '[');
402 snippet_json_fixed.push_str("\n]");
403 }
404
405 settings::parse_json_with_comments::<task::DebugTaskFile>(&snippet_json_fixed)?;
406 }
407 "tasks" => {
408 if !snippet_json_fixed.starts_with('[') || !snippet_json_fixed.ends_with(']') {
409 snippet_json_fixed.insert(0, '[');
410 snippet_json_fixed.push_str("\n]");
411 }
412
413 settings::parse_json_with_comments::<task::TaskTemplates>(&snippet_json_fixed)?;
414 }
415 "icon-theme" => {
416 if !snippet_json_fixed.starts_with('{') || !snippet_json_fixed.ends_with('}') {
417 snippet_json_fixed.insert(0, '{');
418 snippet_json_fixed.push_str("\n}");
419 }
420
421 settings::parse_json_with_comments::<theme::IconThemeFamilyContent>(
422 &snippet_json_fixed,
423 )?;
424 }
425 label => {
426 anyhow::bail!("Unexpected JSON code block tag: {}", label)
427 }
428 };
429 Ok(())
430 });
431}
432
433/// Removes any configurable options from the stringified action if existing,
434/// ensuring that only the actual action name is returned. If the action consists
435/// only of a string and nothing else, the string is returned as-is.
436///
437/// Example:
438///
439/// This will return the action name unmodified.
440///
441/// ```
442/// let action_as_str = "assistant::Assist";
443/// let action_name = name_for_action(action_as_str);
444/// assert_eq!(action_name, "assistant::Assist");
445/// ```
446///
447/// This will return the action name with any trailing options removed.
448///
449///
450/// ```
451/// let action_as_str = "\"editor::ToggleComments\", {\"advance_downwards\":false}";
452/// let action_name = name_for_action(action_as_str);
453/// assert_eq!(action_name, "editor::ToggleComments");
454/// ```
455fn name_for_action(action_as_str: String) -> String {
456 action_as_str
457 .split(",")
458 .next()
459 .map(|name| name.trim_matches('"').to_string())
460 .unwrap_or(action_as_str)
461}
462
463fn chapter_breadcrumbs(chapter: &Chapter) -> String {
464 let mut breadcrumbs = Vec::with_capacity(chapter.parent_names.len() + 1);
465 breadcrumbs.extend(chapter.parent_names.iter().map(String::as_str));
466 breadcrumbs.push(chapter.name.as_str());
467 format!("[{:?}] {}", chapter.source_path, breadcrumbs.join(" > "))
468}
469
470fn load_keymap(asset_path: &str) -> Result<KeymapFile> {
471 let content = util::asset_str::<settings::SettingsAssets>(asset_path);
472 KeymapFile::parse(content.as_ref())
473}
474
475fn for_each_chapter_mut<F>(book: &mut Book, mut func: F)
476where
477 F: FnMut(&mut Chapter),
478{
479 book.for_each_mut(|item| {
480 let BookItem::Chapter(chapter) = item else {
481 return;
482 };
483 func(chapter);
484 });
485}
486
487#[derive(Debug, serde::Serialize)]
488struct ActionDef {
489 name: &'static str,
490 human_name: String,
491 deprecated_aliases: &'static [&'static str],
492 docs: Option<&'static str>,
493}
494
495fn dump_all_gpui_actions() -> Vec<ActionDef> {
496 let mut actions = gpui::generate_list_of_all_registered_actions()
497 .map(|action| ActionDef {
498 name: action.name,
499 human_name: command_palette::humanize_action_name(action.name),
500 deprecated_aliases: action.deprecated_aliases,
501 docs: action.documentation,
502 })
503 .collect::<Vec<ActionDef>>();
504
505 actions.sort_by_key(|a| a.name);
506
507 actions
508}
509
510fn handle_postprocessing() -> Result<()> {
511 let logger = zlog::scoped!("render");
512 let mut ctx = mdbook::renderer::RenderContext::from_json(io::stdin())?;
513 let output = ctx
514 .config
515 .get_mut("output")
516 .expect("has output")
517 .as_table_mut()
518 .expect("output is table");
519 let zed_html = output.remove("zed-html").expect("zed-html output defined");
520 let default_description = zed_html
521 .get("default-description")
522 .expect("Default description not found")
523 .as_str()
524 .expect("Default description not a string")
525 .to_string();
526 let default_title = zed_html
527 .get("default-title")
528 .expect("Default title not found")
529 .as_str()
530 .expect("Default title not a string")
531 .to_string();
532
533 output.insert("html".to_string(), zed_html);
534 mdbook::Renderer::render(&mdbook::renderer::HtmlHandlebars::new(), &ctx)?;
535 let ignore_list = ["toc.html"];
536
537 let root_dir = ctx.destination.clone();
538 let mut files = Vec::with_capacity(128);
539 let mut queue = Vec::with_capacity(64);
540 queue.push(root_dir.clone());
541 while let Some(dir) = queue.pop() {
542 for entry in std::fs::read_dir(&dir).context("failed to read docs dir")? {
543 let Ok(entry) = entry else {
544 continue;
545 };
546 let file_type = entry.file_type().context("Failed to determine file type")?;
547 if file_type.is_dir() {
548 queue.push(entry.path());
549 }
550 if file_type.is_file()
551 && matches!(
552 entry.path().extension().and_then(std::ffi::OsStr::to_str),
553 Some("html")
554 )
555 {
556 if ignore_list.contains(&&*entry.file_name().to_string_lossy()) {
557 zlog::info!(logger => "Ignoring {}", entry.path().to_string_lossy());
558 } else {
559 files.push(entry.path());
560 }
561 }
562 }
563 }
564
565 zlog::info!(logger => "Processing {} `.html` files", files.len());
566 let meta_regex = Regex::new(&FRONT_MATTER_COMMENT.replace("{}", "(.*)")).unwrap();
567 for file in files {
568 let contents = std::fs::read_to_string(&file)?;
569 let mut meta_description = None;
570 let mut meta_title = None;
571 let contents = meta_regex.replace(&contents, |caps: ®ex::Captures| {
572 let metadata: HashMap<String, String> = serde_json::from_str(&caps[1]).with_context(|| format!("JSON Metadata: {:?}", &caps[1])).expect("Failed to deserialize metadata");
573 for (kind, content) in metadata {
574 match kind.as_str() {
575 "description" => {
576 meta_description = Some(content);
577 }
578 "title" => {
579 meta_title = Some(content);
580 }
581 _ => {
582 zlog::warn!(logger => "Unrecognized frontmatter key: {} in {:?}", kind, pretty_path(&file, &root_dir));
583 }
584 }
585 }
586 String::new()
587 });
588 let meta_description = meta_description.as_ref().unwrap_or_else(|| {
589 zlog::warn!(logger => "No meta description found for {:?}", pretty_path(&file, &root_dir));
590 &default_description
591 });
592 let page_title = extract_title_from_page(&contents, pretty_path(&file, &root_dir));
593 let meta_title = meta_title.as_ref().unwrap_or_else(|| {
594 zlog::debug!(logger => "No meta title found for {:?}", pretty_path(&file, &root_dir));
595 &default_title
596 });
597 let meta_title = format!("{} | {}", page_title, meta_title);
598 zlog::trace!(logger => "Updating {:?}", pretty_path(&file, &root_dir));
599 let contents = contents.replace("#description#", meta_description);
600 let contents = title_regex()
601 .replace(&contents, |_: ®ex::Captures| {
602 format!("<title>{}</title>", meta_title)
603 })
604 .to_string();
605 // let contents = contents.replace("#title#", &meta_title);
606 std::fs::write(file, contents)?;
607 }
608 return Ok(());
609
610 fn pretty_path<'a>(
611 path: &'a std::path::PathBuf,
612 root: &'a std::path::PathBuf,
613 ) -> &'a std::path::Path {
614 path.strip_prefix(&root).unwrap_or(path)
615 }
616 fn extract_title_from_page(contents: &str, pretty_path: &std::path::Path) -> String {
617 let title_tag_contents = &title_regex()
618 .captures(contents)
619 .with_context(|| format!("Failed to find title in {:?}", pretty_path))
620 .expect("Page has <title> element")[1];
621
622 title_tag_contents
623 .trim()
624 .strip_suffix("- Zed")
625 .unwrap_or(title_tag_contents)
626 .trim()
627 .to_string()
628 }
629}
630
631fn title_regex() -> &'static Regex {
632 static TITLE_REGEX: OnceLock<Regex> = OnceLock::new();
633 TITLE_REGEX.get_or_init(|| Regex::new(r"<title>\s*(.*?)\s*</title>").unwrap())
634}
635
636fn generate_big_table_of_actions() -> String {
637 let actions = &*ALL_ACTIONS;
638 let mut output = String::new();
639
640 let mut actions_sorted = actions.iter().collect::<Vec<_>>();
641 actions_sorted.sort_by_key(|a| a.name);
642
643 // Start the definition list with custom styling for better spacing
644 output.push_str("<dl style=\"line-height: 1.8;\">\n");
645
646 for action in actions_sorted.into_iter() {
647 // Add the humanized action name as the term with margin
648 output.push_str(
649 "<dt style=\"margin-top: 1.5em; margin-bottom: 0.5em; font-weight: bold;\"><code>",
650 );
651 output.push_str(&action.human_name);
652 output.push_str("</code></dt>\n");
653
654 // Add the definition with keymap name and description
655 output.push_str("<dd style=\"margin-left: 2em; margin-bottom: 1em;\">\n");
656
657 // Add the description, escaping HTML if needed
658 if let Some(description) = action.docs {
659 output.push_str(
660 &description
661 .replace("&", "&")
662 .replace("<", "<")
663 .replace(">", ">"),
664 );
665 output.push_str("<br>\n");
666 }
667 output.push_str("Keymap Name: <code>");
668 output.push_str(action.name);
669 output.push_str("</code><br>\n");
670 if !action.deprecated_aliases.is_empty() {
671 output.push_str("Deprecated Alias(es): ");
672 for alias in action.deprecated_aliases.iter() {
673 output.push_str("<code>");
674 output.push_str(alias);
675 output.push_str("</code>, ");
676 }
677 }
678 output.push_str("\n</dd>\n");
679 }
680
681 // Close the definition list
682 output.push_str("</dl>\n");
683
684 output
685}