// The CodeChat Editor, a word processor for software developers.
Copyright // (C) 2024-2026 Bryan A. Jones. // // This file is part of the CodeChat Editor. The CodeChat Editor is free // software: you can redistribute it and/or modify it under the terms of the GNU // General Public License as published by the Free Software Foundation, either // version 3 of the License, or (at your option) any later version. // // The CodeChat Editor is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more // details. // // You should have received a copy of the GNU General Public License along with // the CodeChat Editor. If not, see // [http://www.gnu.org/licenses](http://www.gnu.org/licenses). //! `processing.rs` -- Transform source code to its web-editable equivalent and //! back //! =========================================================================== // Modules // ------- pub mod cache; // Imports // ------- // // ### Standard library use std::{ borrow::Cow, cell::RefCell, cmp::{max, min}, collections::HashMap, collections::HashSet, ffi::OsStr, io, iter::Map, mem, ops::Range, path::{Path, PathBuf}, rc::Rc, slice::Iter, string::FromUtf8Error, sync::LazyLock, sync::{Arc, Mutex}, }; // ### Third-party use ammonia::Builder; use dprint_plugin_markdown::{ FormatError, configuration::{ Configuration, ConfigurationBuilder, EmphasisKind, HeadingKind, ListUnorderedMarker, StrongKind, TextWrap, }, format_text, }; use htmd::{ Conversion, HtmlToMarkdown, options::{BrStyle, LinkStyle, TranslationMode}, }; use html5ever::{ Attribute, LocalName, Namespace, ParseOpts, QualName, ns, parse_fragment, serialize, serialize::{SerializeOpts, TraversalScope}, tendril::TendrilSink, tree_builder::TreeBuilderOpts, }; use imara_diff::{Algorithm, Diff, Hunk, InternedInput, TokenSource}; use markup5ever_rcdom::{Node, NodeData, RcDom, SerializableHandle}; use minify_html; use path_slash::PathBufExt as _; use phf::phf_map; use pulldown_cmark::{Event, Options, Parser, Tag, TagEnd, html}; use regex::Regex; use serde::{Deserialize, Serialize}; use ts_rs::TS; // ### Local use crate::{ lexer::{ CodeDocBlock, DocBlock, LEXERS, LanguageLexerCompiled, source_lexer, supported_languages::MARKDOWN_MODE, }, processing::cache::{FileFacts, FileStamp, FragmentFact, IdResolution, TargetFact}, webserver::canonicalize, }; use cache::{Cache, CacheMap, get_or_insert_cache}; // Data structures // --------------- // // ### Translation between a local (traditional) source file and its web-editable, client-side representation // // There are three ways that a source file is represented: // // 1. As traditional source code, in a plain text file. // 2. As a alternating series of code and doc blocks, produced by the lexer. See // `lexer.rs\CodeDocBlock`. // 3. As a CodeMirror data structure, which consists of a single block of text, // to which are attached doc blocks at specific character offsets. // // The lexer translates between items 1 and 2; `processing.rs` translates // between 2 and 3. The following data structures define the format for item 3. /// Define the JSON data structure used to represent /// a source file in a web-editable format. #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, TS)] #[ts(export)] pub struct CodeChatForWeb { pub metadata: SourceFileMetadata, /// The version number after accepting this update. pub version: f64, pub source: CodeMirrorDiffable, } /// Provide two options for sending CodeMirror data -- as the full contents /// (`Plain`), or as a diff of the existing contents (`Diff`). #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, TS)] #[ts(export)] pub enum CodeMirrorDiffable { Plain(CodeMirror), Diff(CodeMirrorDiff), } /// Metadata about a source file sent along with /// it both to and from the client. TODO: currently, this is too simple to /// justify a struct. This allows for future growth -- perhaps the valid types /// of comment delimiters? #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, TS)] pub struct SourceFileMetadata { /// The lexer used to transforms source code into code and doc blocks and /// vice versa. pub mode: String, } pub type CodeMirrorDocBlockVec = Vec; /// The format used by CodeMirror to serialize/deserialize editor contents. /// TODO: Link to JS code where this data structure is defined. #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, TS)] pub struct CodeMirror { /// The document being edited. pub doc: String, pub doc_blocks: CodeMirrorDocBlockVec, } /// A diff of the `CodeMirror` struct. #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, TS)] pub struct CodeMirrorDiff { /// The version number from which this diff was produced. pub version: f64, /// A diff of the document being edited. pub doc: Vec, pub doc_blocks: Vec, } /// A transaction produced by the diff of the `CodeMirror` struct. #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, TS)] pub enum CodeMirrorDocBlockTransaction { Add(CodeMirrorDocBlock), Update(CodeMirrorDocBlockUpdate), Delete(CodeMirrorDocBlockDelete), } /// This defines a doc block for CodeMirror. #[derive(Clone, Debug, PartialEq, TS)] // Serde replaces this struct with a tuple for coding efficiency -- see // `CodeMirrorDocBlockTuple`. #[ts(as = "CodeMirrorDocBlockTuple")] pub struct CodeMirrorDocBlock { /// The starting character this doc block is anchored to, measured in UTF-16 /// code units. `to` is measured the same way. pub from: usize, /// The ending character this doc block is anchored to. pub to: usize, /// Indent. pub indent: String, /// Delimiter. pub delimiter: String, /// Contents. pub contents: String, } /// Store the difference between the previous and current `CodeMirrorDocBlock`s. #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, TS)] #[ts(optional_fields)] pub struct CodeMirrorDocBlockUpdate { /// The starting character this doc block is anchored to before this update. /// Like `CodeMirrorDocBlock`, units for this, `from_update`, and `to` are /// in UTF-16 code units. pub from: usize, /// The starting character this doc block is anchored to after this update. #[serde(skip_serializing_if = "Option::is_none")] pub from_new: Option, /// The ending character this doc block is anchored to. #[serde(skip_serializing_if = "Option::is_none")] pub to: Option, /// `None` if the indent is unchanged. Since the indent may be many /// characters, use an `Option` here. #[serde(skip_serializing_if = "Option::is_none")] pub indent: Option, /// Delimiter. #[serde(skip_serializing_if = "Option::is_none")] pub delimiter: Option, /// Contents, as a diff of the previous contents. pub contents: Vec, } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, TS)] pub struct CodeMirrorDocBlockDelete { pub from: usize, } /// Store the difference between a previous and current string; this is based on /// [CodeMirror's ChangeSpec](https://codemirror.net/docs/ref/#state.ChangeSpec). #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, TS)] #[ts(export, optional_fields)] pub struct StringDiff { /// The index of the start of the change, in UTF-16 code units. pub from: usize, /// The index of the end of the change; defined for deletions and /// replacements, in UTF-16 code units. See the /// [skip serializing field docs](https://serde.rs/attr-skip-serializing.html); /// this must be excluded from the JSON output if it's `None` to avoid /// CodeMirror errors. #[serde(skip_serializing_if = "Option::is_none")] pub to: Option, /// The text to insert/replace; an empty string indicates deletion. pub insert: String, } /// This enum contains the results of translating a source file to a string /// rendering of the CodeChat Editor format. #[derive(Debug, PartialEq)] pub enum TranslationResultsString { /// This is a binary file; it must be viewed raw or using the simple viewer. Binary, /// This file is unknown to the CodeChat Editor. It must be viewed raw or /// using the simple viewer. Unknown, /// A CodeChat Editor file; the struct contains the file's contents /// translated to CodeMirror. CodeChat(CodeChatForWeb), /// The table of contents file, translated to HTML. Toc(String), } // On save, the process is CodeChatForWeb -> Vec\ -> source code. // // Globals // ------- /// Match the lexer directive in a source file. static LEXER_DIRECTIVE: LazyLock = LazyLock::new(|| Regex::new(r"CodeChat Editor lexer: (\w+)").unwrap()); /// If this matches, it means an unterminated fenced code block. This should be /// replaced with the `` terminator. static DOC_BLOCK_SEPARATOR_BROKEN_FENCE: LazyLock = LazyLock::new(|| { Regex::new(concat!( // Allow the `.` wildcard to match newlines. "(?s)", // The first `` will be munged when a fenced code // block isn't closed. "<CodeChatEditor-fence>\n", // Non-greedy wildcard -- match the first separator, so we don't munch // multiple `DOC_BLOCK_SEPARATOR_STRING`s in one replacement. ".*?", r"(\d+)\n" )) .unwrap() }); /// After converting Markdown to HTML, this can be used to split doc blocks /// apart. It ignores case since html5ever normalizes the element names to lower /// case, while the HTML it parses keeps the case of the separator string. static DOC_BLOCK_SEPARATOR_SPLIT_REGEX: LazyLock = LazyLock::new(|| { Regex::new(r"(?i)\d+").unwrap() }); /// Match a valid /// [CSS identifier](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Values/ident), /// which all cached ids must be. This is a slight simplification of the CSS /// grammar: escape sequences aren't recognized, and all code points above /// U+0080 are accepted. static CSS_IDENTIFIER: LazyLock = LazyLock::new(|| { Regex::new(r"^(?:--|-?[_a-zA-Z\x{0080}-\x{10FFFF}])[-_a-zA-Z0-9\x{0080}-\x{10FFFF}]*$").unwrap() }); // Use this as a way to end unterminated fenced code blocks and specific types // of HTML blocks. (The remaining types of HTML blocks are terminated by a blank // line, which this also provides.) const DOC_BLOCK_SEPARATOR_STRING: &str = concat!( // If an HTML block with specific start conditions (see the // [section 4.6 of the commonmark spec](https://spec.commonmark.org/0.31.2/#html-blocks), // items 1-5) doesn't have a matching end condition, provide one here. // Otherwise, hide these end conditions inside a raw HTML block, so that it // doesn't get processed by the Markdown parser. Note that this only // supports fenced code blocks with an opening code fence of 23 characters // or less (which should cover most cases). To allow more, we'd need to know // the length of the opening code fence, which is hard to find. Since // CommonMark doesn't care if there are multiple HTML start conditions, // abuse this by not closing the fence until the very end of this string. // The first fence line is doubled because a declaration (item 4) ends at // the first `>`, which is the end of that line; the second line then begins // the raw HTML block which hides everything else. r#" -->?>]]> "#, // Likewise, if there's an unterminated fenced code block with \`\`\` // characters, then provide the ending fence here. Otherwise, hide the // ending fence inside a raw HTML block as before. r#" ``````````````````````` "#, // Repeat for the other style of fenced code block. r#" ~~~~~~~~~~~~~~~~~~~~~~~ {} "# ); // Correctly terminated fenced code blocks produce this, which can be removed // from the HTML produced by Markdown conversion. const DOC_BLOCK_SEPARATOR_REMOVE_FENCE: &str = r" -->?>]]> ``````````````````````` ~~~~~~~~~~~~~~~~~~~~~~~ "; // The replacement string for the `DOC_BLOCK_SEPARATOR_BROKEN_FENCE` regex. It // relies on the first capture group in that regex (`$1`) containing the index, // which it replaces here. const DOC_BLOCK_SEPARATOR_MENDED_FENCE: &str = "\n$1\n"; // The element `parse_doc_block` appends to a doc block, to discover what an // unclosed tag does to the text after it. const DOC_BLOCK_SENTINEL: &str = "codechateditor-sentinel"; // The value of an `id` attribute which requests that the cache assign an id; // see `Auto-assignment of ids` in the cache spec. const AUTO_ID: &str = "*"; // The column at which to word wrap doc blocks. const WORD_WRAP_COLUMN: usize = 80; // The minimum width for doc block word wrap, since large indents may leave // little space for word wrapping. const WORD_WRAP_MIN_WIDTH: usize = 40; // Serialization for `CodeMirrorDocBlock` // -------------------------------------- #[derive(Serialize, Deserialize, TS)] #[ts(export)] struct CodeMirrorDocBlockTuple<'a>( // from usize, // to usize, // indent Cow<'a, str>, // delimiter Cow<'a, str>, // contents Cow<'a, str>, ); // Convert the struct to a tuple, then serialize the tuple. This makes the // resulting JSON more compact. impl Serialize for CodeMirrorDocBlock { fn serialize(&self, serializer: S) -> Result where S: serde::Serializer, { let tuple = CodeMirrorDocBlockTuple( self.from, self.to, Cow::from(&self.indent), Cow::from(&self.delimiter), Cow::from(&self.contents), ); tuple.serialize(serializer) } } // Deserialize the tuple, then convert it to a struct. impl<'de> Deserialize<'de> for CodeMirrorDocBlock { fn deserialize(deserializer: D) -> Result where D: serde::Deserializer<'de>, { let tuple = CodeMirrorDocBlockTuple::deserialize(deserializer)?; Ok(CodeMirrorDocBlock { from: tuple.0, to: tuple.1, indent: tuple.2.into_owned(), delimiter: tuple.3.into_owned(), contents: tuple.4.into_owned(), }) } } // Determine if the provided file is part of a project // --------------------------------------------------- #[must_use] pub fn find_path_to_toc(file_path: &Path) -> Option { // To determine if this source code is part of a project, look for a project // file by searching the current directory, then all its parents, for a file // named `toc.md`. let mut path_to_toc = PathBuf::new(); let mut current_dir = file_path.to_path_buf(); // Drop the last element (the current file name) from the search. current_dir.pop(); loop { let mut project_file = current_dir.clone(); project_file.push("toc.md"); if project_file.is_file() { path_to_toc.push("toc.md"); return Some(path_to_toc); } if !current_dir.pop() { return None; } path_to_toc.push("../"); } } /// Return the cache of the project containing a file, creating it -- and the /// threads which keep it current -- if this project has none. pub fn project_cache( // The map of project caches. cache_map: &CacheMap, // A file in the project. file_path: &Path, // The path to the project's TOC, relative to the directory containing // `file_path`, as returned by `find_path_to_toc`. path_to_toc: &Path, ) -> Arc> { // The project root is the directory containing `toc.md`. Canonicalize it so // that every file in a project keys the same cache, and different projects // key different caches. let toc_path = file_path .parent() .unwrap_or_else(|| Path::new(".")) .join(path_to_toc); let root = toc_path .parent() .map_or_else(PathBuf::new, Path::to_path_buf); let root = canonicalize(&root).unwrap_or(root); get_or_insert_cache(&mut cache_map.lock().unwrap(), &root, || { Cache::new_project(root.clone()) }) } #[derive(Debug, thiserror::Error)] pub enum CodechatForWebToSourceError { #[error("invalid lexer {0}")] InvalidLexer(String), #[error("doc blocks not allowed in Markdown documents")] DocBlocksNotAllowed, #[error("TODO: diffs not supported")] TodoDiff, #[error("unable to convert from HTML to Markdown: {0}")] HtmlToMarkdownFailed(#[from] HtmlToMarkdownWrappedError), #[error("unable to translate CodeChat to source: {0}")] CannotTranslateCodeChat(#[from] CodeDocBlockVecToSourceError), #[error("unable to parse HTML {0}")] ParseFailed(#[from] io::Error), } // Transform `CodeChatForWeb` to source code // ----------------------------------------- /// This function takes in a source file in web-editable format (the /// `CodeChatForWeb` struct) and transforms it into source code. pub fn codechat_for_web_to_source( // The file to save plus metadata, stored in the `LexedSourceFile` codechat_for_web: &CodeChatForWeb, ) -> Result { let lexer_name = &codechat_for_web.metadata.mode; // Given the mode, find the lexer. let Some(lexer) = LEXERS.map_mode_to_lexer.get(lexer_name) else { return Err(CodechatForWebToSourceError::InvalidLexer( lexer_name.clone(), )); }; // Extract the plain (not diffed) CodeMirror contents. let CodeMirrorDiffable::Plain(ref code_mirror) = codechat_for_web.source else { return Err(CodechatForWebToSourceError::TodoDiff); }; // If this is a Markdown-only document, handle this special case. if *lexer.language_lexer.lexer_name == MARKDOWN_MODE { // There should be no doc blocks. if !code_mirror.doc_blocks.is_empty() { return Err(CodechatForWebToSourceError::DocBlocksNotAllowed); } // Translate the HTML document to Markdown. let html_to_markdown = new_html_to_markdown(); let converter = HtmlToMarkdownWrapped::new(&html_to_markdown); let tree = html_to_dom(&code_mirror.doc, None)?; dehydrating_walk_node(&tree)?; return converter .convert(&tree) .map_err(CodechatForWebToSourceError::HtmlToMarkdownFailed); } let code_doc_block_vec_html = code_mirror_to_code_doc_blocks(code_mirror); let mut code_doc_block_vec = doc_block_html_to_markdown(code_doc_block_vec_html, None) .map_err(CodechatForWebToSourceError::HtmlToMarkdownFailed)?; // Word wrapping normally supplies the newline ending a doc block, but not // if its output has no printed width (empty Markdown or only zero-width // characters) or if a `dprint-ignore-file` comment makes it skip the text. // Without this newline, the next line of the file joins the comment. Supply // it here rather than during Markdown conversion, since only the CodeMirror // document shows whether this newline exists: the document holds it at the // doc block's `from`, unless the doc block is a comment with no text ending // a file with no final newline. In this case, `from` lies at the end of the // document. let doc_utf16_len = len_utf16(&code_mirror.doc); let doc_blocks = code_doc_block_vec .iter_mut() .filter_map(|code_doc_block| match code_doc_block { CodeDocBlock::DocBlock(doc_block) => Some(doc_block), CodeDocBlock::CodeBlock(_) => None, }); for (doc_block, code_mirror_doc_block) in doc_blocks.zip(&code_mirror.doc_blocks) { if !doc_block.contents.ends_with('\n') && code_mirror_doc_block.from < doc_utf16_len { doc_block.contents.push('\n'); } } code_doc_block_vec_to_source(&code_doc_block_vec, lexer) .map_err(CodechatForWebToSourceError::CannotTranslateCodeChat) } /// Return the byte index of `s[utf_16_index]`, where the indexing operation is /// in UTF-16 code units. #[must_use] pub fn byte_index_of(s: &str, utf_16_index: usize) -> usize { let mut byte_index = 0; let mut current_index = 0; for c in s.chars() { if current_index >= utf_16_index { return byte_index; } current_index += c.len_utf16(); byte_index += c.len_utf8(); } // This index refers to the end of the string -- return that. s.len() } /// Translate from CodeMirror to CodeDocBlocks. fn code_mirror_to_code_doc_blocks(code_mirror: &CodeMirror) -> Vec { let doc_blocks = &code_mirror.doc_blocks; // Translate between UTF-16 code units (the `from` and `to` provided by // CodeMirror) and byte indexes (which Rust uses). Keep track of the current // byte index/UTF-16 index; we always move forward from that location. let mut byte_index: usize = 0; let mut utf16_index: usize = 0; let mut code_doc_block_arr: Vec = Vec::new(); // Walk through each doc block, inserting the previous code block followed // by the doc block. for codemirror_doc_block in doc_blocks { // Translate `from`. Use a checked subtraction, since a malformed (for // example, out-of-order or overlapping) `doc_blocks` array sent by the // Client could otherwise cause this to underflow and wrap around to a // huge value, producing a confusing out-of-bounds slice panic below // instead of a clear error at the point of the actual problem. let byte_index_prev = byte_index; byte_index += byte_index_of( &code_mirror.doc[byte_index..], codemirror_doc_block .from .checked_sub(utf16_index) .expect("doc_blocks must be sorted, with non-overlapping from/to ranges"), ); utf16_index = codemirror_doc_block.from; // Append the code block, unless it's empty. let code_contents = &code_mirror.doc[byte_index_prev..byte_index]; if !code_contents.is_empty() { code_doc_block_arr.push(CodeDocBlock::CodeBlock(code_contents.to_string())); } // Append the doc block. code_doc_block_arr.push(CodeDocBlock::DocBlock(DocBlock { indent: codemirror_doc_block.indent.clone(), delimiter: codemirror_doc_block.delimiter.clone(), contents: codemirror_doc_block.contents.clone(), lines: 0, })); let byte_index_prev = byte_index; // Translate `to`. byte_index += byte_index_of( &code_mirror.doc[byte_index..], codemirror_doc_block .to .checked_sub(utf16_index) .expect("doc_blocks must be sorted, with non-overlapping from/to ranges"), ); utf16_index = codemirror_doc_block.to; // Verify that everything between `from` and `to` is newlines. for char in code_mirror.doc[byte_index_prev..byte_index].chars() { assert_eq!(char, '\n'); } } // See if there's a code block after the last doc block. let code_contents = &code_mirror.doc[byte_index..]; if !code_contents.is_empty() { code_doc_block_arr.push(CodeDocBlock::CodeBlock(code_contents.to_string())); } code_doc_block_arr } /// Build the HTML to Markdown converter which an \[`HtmlToMarkdownWrapped`\] /// borrows. A `Conversion` holds a reference to its converter, so the converter /// must outlive the wrapper rather than live inside it. fn new_html_to_markdown() -> HtmlToMarkdown { // Most of the options don't need to be specified here, since the line // wrapper will override them. HtmlToMarkdown::builder() .options(htmd::options::Options { link_style: LinkStyle::Inlined, translation_mode: TranslationMode::Faithful, // Note that this is ignored in Faithful mode. br_style: BrStyle::Backslash, ..Default::default() }) .build() } /// This converts a document, supplied as one or more DOM trees, from HTML to /// Markdown then word wraps the result. struct HtmlToMarkdownWrapped<'a> { html_to_markdown_conversion: Conversion<'a>, word_wrap_config: Configuration, } #[derive(Debug, thiserror::Error)] pub enum HtmlToMarkdownWrappedError { #[error("unable to convert from HTML to markdown")] HtmlToMarkdownFailed(#[from] std::io::Error), #[error("unable to word wrap Markdown")] WordWrapFailed(#[from] FormatError), #[error("line width exceeds u32::MAX")] LineWidthOverflow(#[from] std::num::TryFromIntError), } impl<'a> HtmlToMarkdownWrapped<'a> { fn new( // The converter, typically from `new_html_to_markdown`. html_to_markdown: &'a HtmlToMarkdown, ) -> Self { HtmlToMarkdownWrapped { html_to_markdown_conversion: html_to_markdown.start_conversion(), // TODO: numbered list formatting should be improved in the dprint // library. word_wrap_config: ConfigurationBuilder::new() .emphasis_kind(EmphasisKind::Asterisks) .strong_kind(StrongKind::Asterisks) .list_unordered_marker(ListUnorderedMarker::Asterisks) .text_wrap(TextWrap::Always) .heading_kind(HeadingKind::Setext) .code_block_preserve_blank_lines(true) .code_block_preserve_indentation(true) .build(), } } fn set_line_width(&mut self, line_width: usize) -> Result<(), HtmlToMarkdownWrappedError> { self.word_wrap_config.line_width = u32::try_from(line_width)?; Ok(()) } /// Convert one item in a stream of HTML to markdown. The HTML must be start /// at the root, not continue a previous incomplete section of the DOM. fn next(&self, tree: &Rc) -> Result { let converted = self.html_to_markdown_conversion.tree_to_markdown(tree); Ok( format_text(&converted, &self.word_wrap_config, |_, _, _| Ok(None))? // A return value of `None` means the text was unchanged or // ignored (by an // [ignoreFileDirective](https://dprint.dev/plugins/markdown/config/)). // Simply return the unchanged text in this case. .unwrap_or(converted), ) } /// End the document, returning the Markdown placed at its end (such as link /// reference definitions). This consumes the wrapper, since finishing a /// `Conversion` consumes it. fn last( self, // The word-wrapped Markdown which ends the document. ) -> Result { let converted = self.html_to_markdown_conversion.finish(); Ok( format_text(&converted, &self.word_wrap_config, |_, _, _| Ok(None))? .unwrap_or(converted), ) } /// Convert a document consisting of a single DOM tree from HTML to /// markdown. fn convert( self, // The DOM tree holding the entire document. tree: &Rc, // The document as word-wrapped Markdown. ) -> Result { let mut converted = self.next(tree)?; converted.push_str(&self.last()?); Ok(converted) } } // Transform HTML in doc blocks to Markdown. pub fn doc_block_html_to_markdown( mut code_doc_block_vec: Vec, // If provided, the index of each successive node in the DOM, ending with // the offset in UTF-16 characters within the last node (which must be a // text node) at which a marker character will be inserted. // // For this reason, when provided, this function must called with a vec // containing only one doc block. dom_location: Option<&(Vec, usize)>, ) -> Result, HtmlToMarkdownWrappedError> { let html_to_markdown = new_html_to_markdown(); let mut converter = HtmlToMarkdownWrapped::new(&html_to_markdown); let mut last_doc_block_index = None; // Only perform marker insertions to a length 1 vec. assert!(dom_location.is_none() || code_doc_block_vec.len() == 1); for (index, code_doc_block) in &mut code_doc_block_vec.iter_mut().enumerate() { if let CodeDocBlock::DocBlock(doc_block) = code_doc_block { last_doc_block_index = Some(index); let tree = html_to_dom(&doc_block.contents, dom_location)?; dehydrating_walk_node(&tree)?; // Calculate the total delimiter width: the delimiter width plus the // extra space after it. Special case: an empty delimiter means // we're wrapping a Markdown document to insert a marker, so don't // add the extra space. let delimiter_width = doc_block.delimiter.chars().count(); let total_delimiter_width = if delimiter_width > 0 { delimiter_width + 1 } else { 0 }; // Compute a line wrap width based on the current indent. Set a // minimum of half the line wrap width, to prevent ridiculous // wrapping with large indents. converter.set_line_width(max( WORD_WRAP_MIN_WIDTH, // Use `min` to avoid overflow with unsigned subtraction. WORD_WRAP_COLUMN - min( total_delimiter_width + doc_block.indent.chars().count(), WORD_WRAP_COLUMN, ), ))?; doc_block.contents = converter.next(&tree)?; } } // Append the finalized conversion to the last doc block. if let Some(last_doc_block_index) = last_doc_block_index { let CodeDocBlock::DocBlock(ref mut last_doc_block) = code_doc_block_vec[last_doc_block_index] else { unreachable!(); }; let last = converter.last()?; last_doc_block.contents.push_str(&last); } Ok(code_doc_block_vec) } #[derive(Debug, PartialEq, thiserror::Error)] pub enum CodeDocBlockVecToSourceError { #[error("unknown comment opening delimiter '{0}'")] UnknownCommentOpeningDelimiter(String), } // Turn this vec of CodeDocBlocks into a string of source code. fn code_doc_block_vec_to_source( code_doc_block_vec: &[CodeDocBlock], lexer: &LanguageLexerCompiled, ) -> Result { let mut file_contents = String::new(); for code_doc_block in code_doc_block_vec { match code_doc_block { CodeDocBlock::DocBlock(doc_block) => { // Append a doc block, adding a space between the opening // delimiter and the contents when necessary. let mut append_doc_block = |indent: &str, delimiter: &str, contents: &str| { file_contents += indent; file_contents += delimiter; // Add a space between the delimiter and comment body, // unless the comment was a newline or we're at the end of // the file. if contents.is_empty() || contents == "\n" { // Nothing to append in this case. } else { // Put a space between the delimiter and the contents. file_contents += " "; } file_contents += contents; }; let is_inline_delim = lexer .language_lexer .inline_comment_delim_arr .contains(&doc_block.delimiter); // Build a comment based on the type of the delimiter. if is_inline_delim { // To produce an inline comment, split the contents into a // series of lines, adding the indent and inline comment // delimiter to each line. // // A special case: an empty string processed by // `split_inclusive` becomes an empty list, not `[""]`. Note // that this mirrors what Python's // [splitlines](https://docs.python.org/3/library/stdtypes.html#str.splitlines) // does, and is also the subject of a // [Rust bug report](https://github.com/rust-lang/rust/issues/111457). let lines: Vec<_> = doc_block.contents.split_inclusive('\n').collect(); let lines_fixed = if lines.is_empty() { vec![""] } else { lines }; for content_line in lines_fixed { append_doc_block(&doc_block.indent, &doc_block.delimiter, content_line); } } else { // Block comments are more complex. // // First, determine the closing comment delimiter matching // the provided opening delimiter. let block_comment_closing_delimiter = match lexer .language_lexer .block_comment_delim_arr .iter() .position(|bc| bc.opening == doc_block.delimiter) { Some(index) => &lexer.language_lexer.block_comment_delim_arr[index].closing, None => { return Err( CodeDocBlockVecToSourceError::UnknownCommentOpeningDelimiter( doc_block.delimiter.clone(), ), ); } }; // An empty comment has no lines to place the delimiters // around, so write it directly. if doc_block.contents.is_empty() || doc_block.contents == "\n" { append_doc_block( &doc_block.indent, &doc_block.delimiter, &format!("{block_comment_closing_delimiter}{}", doc_block.contents), ); continue; } // Then, split the contents into a series of lines. Build a // properly-indented block comment around these lines. let content_lines: Vec<&str> = doc_block.contents.split_inclusive('\n').collect(); for (index, content_line) in content_lines.iter().enumerate() { // Note: using `.len()` here is correct -- it refers to // an index into `content_lines`, not an index into a // string. let is_last = index == content_lines.len() - 1; // Process each line, based on its location (first/not // first/last). Note that the first line can also be the // last line in a one-line comment. // // On the last line, include a properly-formatted // closing comment delimiter: let content_line_updated = if is_last { match content_line.strip_suffix('\n') { // include a space then the closing delimiter // before the final newline (if it exists; at // the end of a file, it may not); Some(stripped_line) => { stripped_line.to_string() + " " + block_comment_closing_delimiter + "\n" } // otherwise (i.e. there's no final newline), // just include a space and the closing // delimiter. None => { content_line.to_string() + " " + block_comment_closing_delimiter } } } else { // Since this isn't the last line, don't include the // closing comment delimiter. content_line.to_string() }; // On the first line, include the indent and opening // delimiter. let is_first = index == 0; if is_first { append_doc_block( &doc_block.indent, &doc_block.delimiter, &content_line_updated, ); // Since this isn't a first line: } else { // * If this line is just a newline, include just // the newline. if *content_line == "\n" { append_doc_block("", "", "\n"); // * Otherwise, include spaces in place of the // delimiter. } else { append_doc_block( &doc_block.indent, &" ".repeat(doc_block.delimiter.chars().count()), &content_line_updated, ); } } } } } CodeDocBlock::CodeBlock(contents) => // This is code. Simply append it (by definition, indent and // delimiter are empty). { file_contents += contents; } } } Ok(file_contents) } #[derive(Debug, PartialEq, thiserror::Error)] pub enum SourceToCodeChatForWebError { #[error("unknown lexer {0}")] UnknownLexer(String), // Since we want `PartialEq`, we can't use `#[from] io::Error`; instead, // convert the IO error to a string. #[error("unable to parse HTML {0}")] ParseFailed(String), #[error("no lexer for this file")] NoLexer, #[error("encoding error {0}")] EncodeFailed(#[from] FromUtf8Error), } // Transform from source code to `CodeChatForWeb` // ---------------------------------------------- // // Given the contents of a file, classify it and (for CodeChat Editor files) // convert it to the `CodeChatForWeb` format. #[allow(clippy::too_many_lines)] pub fn source_to_codechat_for_web( // The file's contents. file_contents: &str, // The file's extension. file_path: &Path, // The version of this file. version: f64, // True if this file is a TOC. _is_toc: bool, // If provided, the cache for this project; otherwise, this file is not in a // project. cache: Option>>, ) -> Result { // Determine the file's extension, in order to look up a lexer. let file_ext = &file_path .extension() .unwrap_or_else(|| OsStr::new("")) .to_string_lossy() .to_string(); // Determine the lexer to use for this file. let lexer_name; // First, search for a lexer directive in the file contents. let lexer = if let Some(captures) = LEXER_DIRECTIVE.captures(file_contents) { lexer_name = captures[1].to_string(); match LEXERS.map_mode_to_lexer.get(&lexer_name) { Some(v) => v, None => { return Err(SourceToCodeChatForWebError::UnknownLexer(lexer_name)); } } } else { // Otherwise, look up the lexer by the file's extension. match LEXERS.map_ext_to_lexer_vec.get(file_ext) { Some(llc) => llc.first().unwrap(), _ => { // The file type is unknown; we can't lex it. return Err(SourceToCodeChatForWebError::NoLexer); } } }; // Transform the provided file into the `CodeChatForWeb` structure. let cache = if let Some(project_cache) = cache { project_cache } else { // A non-project file uses a throwaway cache whose "project" is the file // itself: only references within this file resolve. Arc::new(Mutex::new(Cache::new(file_path.to_path_buf()))) }; let code_doc_block_arr; let codechat_for_web = CodeChatForWeb { metadata: SourceFileMetadata { mode: lexer.language_lexer.lexer_name.to_string(), }, version, source: if lexer.language_lexer.lexer_name.as_str() == MARKDOWN_MODE { // Document-only files are easy: just encode the contents. Fragments // aren't supported in Markdown documents; `hydrate_html` reports // them as errors. let dry_html = markdown_to_html(file_contents, &[(0..file_contents.len(), 1)]); let html = hydrate_html(&dry_html, file_path, &cache) .map_err(|e| SourceToCodeChatForWebError::ParseFailed(e.to_string()))?; let html = minify(&html)?; CodeMirrorDiffable::Plain(CodeMirror { doc: html, doc_blocks: vec![], }) } else { // This is a source file. // // Create an initially-empty struct; the source code will be // translated to this. let mut code_mirror = CodeMirror { doc: String::new(), doc_blocks: Vec::new(), }; // Lex the code. code_doc_block_arr = source_lexer(file_contents, lexer); // Combine all the doc blocks into a single string, separated by a // delimiter. Transform this to markdown, then split the transformed // content back into the doc blocks they came from. This is // necessary to allow // [link reference definitions](https://spec.commonmark.org/0.31.2/#link-reference-definitions) // between doc blocks to work; for example, `[Link][1]` in one doc // block, then `[1]: http:/foo.org` in another doc block requires // both to be in the same Markdown document to translate correctly. // // Precede each doc block's contents with the separator string; the // separator contains the index of this doc block in the vec of // code/doc blocks. The separator appears before *every* doc block // (including the first), so the DOM walk always knows the current // doc block index and empty doc blocks stay aligned with their // separators. Record where each doc block's contents lie in the // result and the file line they start on, for the line markers; a // block starts after every line of the blocks before it, counted // as `render_fragment_content` counts them. // let mut doc_contents = String::new(); let mut file_ranges = Vec::new(); let mut line = 1; for (index, code_doc_block) in code_doc_block_arr.iter().enumerate() { if let CodeDocBlock::DocBlock(doc_block) = code_doc_block { doc_contents .push_str(&DOC_BLOCK_SEPARATOR_STRING.replace("{}", &index.to_string())); let start = doc_contents.len(); doc_contents.push_str(&doc_block.contents); file_ranges.push((start..doc_contents.len(), line)); } line += code_doc_block_lines(code_doc_block); } // Convert the Markdown to HTML. let html = markdown_to_html(&doc_contents, &file_ranges); // Break it back into doc blocks: // // 1. Mend broken fences. let html = DOC_BLOCK_SEPARATOR_BROKEN_FENCE .replace_all(&html, DOC_BLOCK_SEPARATOR_MENDED_FENCE); // 2. Remove good fences. let html = html.replace(DOC_BLOCK_SEPARATOR_REMOVE_FENCE, ""); // 3. Parse the cleaned HTML, then hydrate it: commit this file's // facts to the cache, then patch cross-references and fragment // backlinks. let doc_block_count = code_doc_block_arr .iter() .filter(|code_doc_block| matches!(code_doc_block, CodeDocBlock::DocBlock(_))) .count(); let dom = doc_blocks_to_dom(&html, doc_block_count) .map_err(|e| SourceToCodeChatForWebError::ParseFailed(e.to_string()))?; let (dom, walk_context) = hydrate_dom(dom, file_path, &cache, false) .map_err(|e| SourceToCodeChatForWebError::ParseFailed(e.to_string()))?; // 4. Serialize and split on the separator, giving each doc block's // hydrated HTML -- the form in which fragment contents are // stored. The piece before the first separator isn't a doc // block; discard it. let intermediate_html = dom_to_html(&dom) .map_err(|e| SourceToCodeChatForWebError::ParseFailed(e.to_string()))?; let mut chunk_iter = DOC_BLOCK_SEPARATOR_SPLIT_REGEX.split(&intermediate_html); chunk_iter.next(); // Pair the index of each doc block in `code_doc_block_arr` with its // hydrated HTML. let doc_block_html: HashMap = code_doc_block_arr .iter() .enumerate() .filter(|(_, code_doc_block)| matches!(code_doc_block, CodeDocBlock::DocBlock(_))) .map(|(index, _)| index) .zip(chunk_iter) .collect(); // 5. Store each fragment's content in the cache, which marks the // files containing gather elements listing changed fragments as // outdated. store_fragment_contents( &walk_context, Some((&code_doc_block_arr, &doc_block_html)), &cache, ); // 6. Hydrate gather lists, now that every fragment's content -- // including those defined in this file -- is in the cache. hydrate_gathers(&walk_context, &cache) .map_err(|e| SourceToCodeChatForWebError::ParseFailed(e.to_string()))?; // 7. Serialize the fully-hydrated DOM and split it into the final // doc block contents, again discarding the piece before the // first separator. let html = dom_to_html(&dom) .map_err(|e| SourceToCodeChatForWebError::ParseFailed(e.to_string()))?; let mut doc_block_contents_iter: regex::Split<'_, '_> = DOC_BLOCK_SEPARATOR_SPLIT_REGEX.split(&html); doc_block_contents_iter.next(); // Translate each `CodeDocBlock` to its `CodeMirror` equivalent. let mut len = len_utf16(&code_mirror.doc); for code_or_doc_block in code_doc_block_arr { let source = &mut code_mirror.doc; match code_or_doc_block { CodeDocBlock::CodeBlock(code_string) => { source.push_str(&code_string); len += len_utf16(&code_string); } CodeDocBlock::DocBlock(doc_block) => { // Create the doc block. code_mirror.doc_blocks.push(CodeMirrorDocBlock { from: len, // To. Note that the last doc block could be zero // length, so handle this case. to: len + max(doc_block.lines, 1), indent: doc_block.indent.clone(), delimiter: doc_block.delimiter.clone(), // Used the markdown-translated replacement for this // doc block, rather than the original string. // `doc_blocks_to_dom` checks that no separators are // missing and parses each to a top-level node, // which hydration keeps, so this can't fail. contents: minify(doc_block_contents_iter.next().unwrap())?, }); // Append newlines to the document; the doc block will // replace these in the editor. This keeps the line // numbering of non-doc blocks correct. source.push_str(&"\n".repeat(doc_block.lines)); len += doc_block.lines; } } } CodeMirrorDiffable::Plain(code_mirror) }, }; Ok(codechat_for_web) } // Options for a spec-compliant minifier. static MINIFY_OPTIONS: LazyLock = LazyLock::new(|| { let mut cfg = minify_html::Cfg::new(); cfg.allow_noncompliant_unquoted_attribute_values = false; cfg.allow_optimal_entities = false; cfg.allow_removing_spaces_between_attributes = false; cfg.keep_comments = true; cfg.keep_html_and_head_opening_tags = true; cfg.minify_doctype = false; let mut override_whitespace: HashSet> = HashSet::new(); override_whitespace.insert(b"wc-mermaid".to_vec()); override_whitespace.insert(b"graphviz-graph".to_vec()); cfg.override_whitespace = override_whitespace; cfg }); // A static config for Ammonia. static AMMONIA_OPTIONS: LazyLock = LazyLock::new(|| { let mut b = Builder::default(); // Add custom tags produced during hydration, plus `input` (task list // checkboxes produced by pulldown-cmark), `iframe` (embedded media // inserted via TinyMCE) and `l-n` (line markers produced by // `markdown_to_html`), none of which Ammonia allows by default. b.add_tags(&[ "wc-mermaid", "graphviz-graph", "xref", "fragment", "input", "iframe", "l-n", ]) // Allow any element to be assigned an ID and to be a gather element. .add_generic_attributes(&["id", "data-gather"]) // This allows math produced by pulldown-cmark and updated by the hydration // code, plus hydration error messages. .add_allowed_classes( "span", &[ "math", "math-inline", "math-display", "mceNonEditable", "cc-error", // The line number preceding each line of a code block in a rendered // fragment; see `render_fragment_content`. "cc-line-number", ], ) // Classes produced by gather-element hydration. The `cc-gather` class may // appear on any element with an `id` and `data-gather`; Ammonia only // supports per-tag class allowlists, so list the elements which plausibly // serve as gather elements. .add_allowed_classes("h1", &["cc-gather"]) .add_allowed_classes("h2", &["cc-gather"]) .add_allowed_classes("h3", &["cc-gather"]) .add_allowed_classes("h4", &["cc-gather"]) .add_allowed_classes("h5", &["cc-gather"]) .add_allowed_classes("h6", &["cc-gather"]) .add_allowed_classes("p", &["cc-gather", "cc-gather-item-link"]) // The `cc-fragment-*` classes lay out one doc block of a rendered fragment: // its source indent, then its contents. See `render_fragment_content`. .add_allowed_classes( "div", &[ "cc-gather", "cc-gather-items", "cc-fragment-doc", "cc-fragment-doc-contents", ], ) // The doc block indents and the code blocks of a rendered fragment; see // `render_fragment_content`. Listing these here rather than allowing a // `class` attribute on any `pre` (as `code` below does) keeps a doc block's // hand-written `
` from claiming the layout these name.
    .add_allowed_classes("pre", &["cc-fragment-indent", "cc-fragment-code"])
    // The gather-items list is generated content, marked non-editable.
    .add_tag_attributes("div", &["contenteditable"])
    // Math spans are marked non-editable.
    .add_tag_attributes("span", &["contenteditable"])
    // `code` tags can have `class=language-*`. Since Ammonia doesn't support a
    // regex like this, just allow anything.
    .add_tag_attributes("code", &["class"])
    // Task list checkboxes are rendered as ``.
    .add_tag_attributes("input", &["type", "checked", "disabled"])
    // Allow the attributes TinyMCE/the IDE place on embedded `