-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathprocessing.rs
More file actions
1845 lines (1733 loc) · 74.6 KB
/
processing.rs
File metadata and controls
1845 lines (1733 loc) · 74.6 KB
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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (C) 2025 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
/// ============================================================================
// Imports
// -----------------------------------------------------------------------------
//
// ### Standard library
//
// For commented-out caching code.
/**
use std::collections::{HashMap, HashSet};
use std::fs::Metadata;
use std::io;
use std::ops::Deref;
use std::rc::{Rc, Weak};
*/
use std::{
borrow::Cow,
cell::RefCell,
cmp::{max, min},
ffi::OsStr,
io,
iter::Map,
ops::Range,
path::{Path, PathBuf},
rc::Rc,
slice::Iter,
};
// ### Third-party
use dprint_plugin_markdown::{
configuration::{
Configuration, ConfigurationBuilder, EmphasisKind, HeadingKind, StrongKind, TextWrap,
UnorderedListKind,
},
format_text,
};
use htmd::{
HtmlToMarkdown,
options::{LinkStyle, TranslationMode},
};
use html5ever::{
Attribute, LocalName, Namespace, ParseOpts, QualName, parse_document, serialize,
serialize::{SerializeOpts, TraversalScope},
tendril::TendrilSink,
tree_builder::TreeBuilderOpts,
};
use imara_diff::{Algorithm, Diff, Hunk, InternedInput, TokenSource};
use lazy_static::lazy_static;
use markup5ever_rcdom::{Node, NodeData, RcDom, SerializableHandle};
use phf::phf_map;
use pulldown_cmark::{Options, Parser, 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,
};
// 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.
/// <a id="LexedSourceFile"></a>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),
}
/// <a id="SourceFileMetadata"></a>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<CodeMirrorDocBlock>;
/// 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<StringDiff>,
pub doc_blocks: Vec<CodeMirrorDocBlockTransaction>,
}
/// 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<usize>,
/// The ending character this doc block is anchored to.
#[serde(skip_serializing_if = "Option::is_none")]
pub to: Option<usize>,
/// `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<String>,
/// Delimiter.
#[serde(skip_serializing_if = "Option::is_none")]
pub delimiter: Option<String>,
/// Contents, as a diff of the previous contents.
pub contents: Vec<StringDiff>,
}
#[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<usize>,
/// The text to insert/replace; an empty string indicates deletion.
pub insert: String,
}
/// This enum contains the results of translating a source file to the CodeChat
/// Editor format.
#[derive(Debug, PartialEq)]
pub enum TranslationResults {
/// This file is unknown to and therefore not supported by the CodeChat
/// Editor.
Unknown,
/// A CodeChat Editor file; the struct contains the file's contents
/// translated to CodeMirror.
CodeChat(CodeChatForWeb),
}
/// 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\<CodeDocBlocks> -> source code.
//
// Globals
// -----------------------------------------------------------------------------
lazy_static! {
/// Match the lexer directive in a source file.
static ref LEXER_DIRECTIVE: Regex = Regex::new(r"CodeChat Editor lexer: (\w+)").unwrap();
/// <a class="fence-mending-start"></a>If this matches, it means an
/// unterminated fenced code block. This should be replaced with the
/// `</code></pre>` terminator.
static ref DOC_BLOCK_SEPARATOR_BROKEN_FENCE: Regex = Regex::new(concat!(
// Allow the `.` wildcard to match newlines.
"(?s)",
// The first `<CodeChatEditor-fence>` 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.
".*?",
"<CodeChatEditor-separator></CodeChatEditor-separator>\n")).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.
r#"
<CodeChatEditor-fence>
</pre></script></style></textarea>-->?>]]>
"#,
// 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#"<CodeChatEditor-fence>
```````````````````````
"#,
// Repeat for the other style of fenced code block.
r#"<CodeChatEditor-fence>
~~~~~~~~~~~~~~~~~~~~~~~
</CodeChatEditor-fence>
<CodeChatEditor-separator></CodeChatEditor-separator>
"#
);
// After converting Markdown to HTML, this can be used to split doc blocks
// apart. Since this is post hydration, the element names are normalized to
// lower case.
const DOC_BLOCK_SEPARATOR_SPLIT_STRING: &str =
"<codechateditor-separator></codechateditor-separator>\n";
// 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#"<CodeChatEditor-fence>
</pre></script></style></textarea>-->?>]]>
<CodeChatEditor-fence>
```````````````````````
<CodeChatEditor-fence>
~~~~~~~~~~~~~~~~~~~~~~~
</CodeChatEditor-fence>
"#;
// The replacement string for the `DOC_BLOCK_SEPARATOR_BROKEN_FENCE` regex.
const DOC_BLOCK_SEPARATOR_MENDED_FENCE: &str =
"</code></pre>\n<CodeChatEditor-separator></CodeChatEditor-separator>\n";
// <a class="fence-mending-end"></a>
// 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<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
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<D>(deserializer: D) -> Result<Self, D::Error>
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
// -----------------------------------------------------------------------------
pub fn find_path_to_toc(file_path: &Path) -> Option<PathBuf> {
// 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("../");
}
}
#[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<String, CodechatForWebToSourceError> {
let lexer_name = &codechat_for_web.metadata.mode;
// Given the mode, find the lexer.
let lexer: &std::sync::Arc<crate::lexer::LanguageLexerCompiled> =
match LEXERS.map_mode_to_lexer.get(lexer_name) {
Some(v) => v,
None => {
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 converter = HtmlToMarkdownWrapped::new();
let tree = html_to_tree(&code_mirror.doc)?;
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 code_doc_block_vec = doc_block_html_to_markdown(code_doc_block_vec_html)
.map_err(CodechatForWebToSourceError::HtmlToMarkdownFailed)?;
code_doc_block_vec_to_source(&code_doc_block_vec, lexer)
.map_err(CodechatForWebToSourceError::CannotTranslateCodeChat)
}
/// Return the byte index of `s[u16_16_index]`, where the indexing operation is
/// in UTF-16 code units.
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<CodeDocBlock> {
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<CodeDocBlock> = 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`.
let byte_index_prev = byte_index;
byte_index += byte_index_of(
&code_mirror.doc[byte_index..],
codemirror_doc_block.from - utf16_index,
);
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.to_string(),
delimiter: codemirror_doc_block.delimiter.to_string(),
contents: codemirror_doc_block.contents.to_string(),
lines: 0,
}));
let byte_index_prev = byte_index;
// Translate `to`.
byte_index += byte_index_of(
&code_mirror.doc[byte_index..],
codemirror_doc_block.to - utf16_index,
);
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
}
/// This converts HTML to Markdown then word wraps the result.
struct HtmlToMarkdownWrapped {
html_to_markdown: HtmlToMarkdown,
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] anyhow::Error),
}
impl HtmlToMarkdownWrapped {
fn new() -> Self {
HtmlToMarkdownWrapped {
// Most of the options don't need to be specified here, since the
// line wrapper will override them.
html_to_markdown: HtmlToMarkdown::builder()
.options(htmd::options::Options {
link_style: LinkStyle::Inlined,
translation_mode: TranslationMode::Faithful,
..Default::default()
})
.build(),
// TODO: numbered list formatting should be improved in the dprint
// library.
word_wrap_config: ConfigurationBuilder::new()
.emphasis_kind(EmphasisKind::Asterisks)
.strong_kind(StrongKind::Asterisks)
.unordered_list_kind(UnorderedListKind::Asterisks)
.text_wrap(TextWrap::Always)
.heading_kind(HeadingKind::Setext)
.build(),
}
}
fn set_line_width(&mut self, line_width: usize) {
self.word_wrap_config.line_width = line_width as u32;
}
/// 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<Node>) -> Result<String, HtmlToMarkdownWrappedError> {
let converted = self.html_to_markdown.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_else(|| converted.to_string()),
)
}
fn last(&self) -> Result<String, HtmlToMarkdownWrappedError> {
let converted = self.html_to_markdown.finalize_conversion();
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_else(|| converted.to_string()),
)
}
/// Convert HTML to markdown.
fn convert(&self, tree: &Rc<Node>) -> Result<String, HtmlToMarkdownWrappedError> {
let mut converted = self.next(tree)?;
converted.push_str(&self.last()?);
Ok(converted)
}
}
// Transform HTML in doc blocks to Markdown.
fn doc_block_html_to_markdown(
mut code_doc_block_vec: Vec<CodeDocBlock>,
) -> Result<Vec<CodeDocBlock>, HtmlToMarkdownWrappedError> {
let mut converter = HtmlToMarkdownWrapped::new();
for code_doc_block in &mut code_doc_block_vec {
if let CodeDocBlock::DocBlock(doc_block) = code_doc_block {
let tree = html_to_tree(&doc_block.contents)?;
dehydrating_walk_node(&tree);
// 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,
// The +1 factor is for the space separating the delimiter and
// the comment text. Use `min` to avoid overflow with unsigned
// subtraction.
WORD_WRAP_COLUMN
- min(
doc_block.delimiter.chars().count() + 1 + doc_block.indent.chars().count(),
WORD_WRAP_COLUMN,
),
));
doc_block.contents = converter.next(&tree)?;
}
}
// Output the finalized conversion.
if let Some(code_doc_block) = code_doc_block_vec.last_mut()
&& let CodeDocBlock::DocBlock(doc_block) = code_doc_block
{
let last = converter.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: &Vec<CodeDocBlock>,
lexer: &LanguageLexerCompiled,
) -> Result<String, CodeDocBlockVecToSourceError> {
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(),
),
);
}
};
// 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),
}
// 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.
pub fn source_to_codechat_for_web(
// The file's contents.
file_contents: &str,
// The file's extension.
file_ext: &String,
// The version of this file.
version: f64,
// True if this file is a TOC.
_is_toc: bool,
// True if this file is part of a project.
_is_project: bool,
) -> Result<TranslationResults, SourceToCodeChatForWebError> {
// 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; treat it as plain text.
return Ok(TranslationResults::Unknown);
}
}
};
// Transform the provided file into the `CodeChatForWeb` structure.
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.
let dry_html = markdown_to_html(file_contents);
let html = hydrate_html(&dry_html)
.map_err(|e| SourceToCodeChatForWebError::ParseFailed(e.to_string()))?;
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: "".to_string(),
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.
//
// Walk through the code/doc blocks, ...
let doc_contents = code_doc_block_arr
.iter()
// ...selcting only the doc block contents...
.filter_map(|cdb| {
if let CodeDocBlock::DocBlock(db) = cdb {
Some(db.contents.as_str())
} else {
None
}
})
// ...then collect them, separated by the doc block separator
// string.
.collect::<Vec<_>>()
.join(DOC_BLOCK_SEPARATOR_STRING);
// Convert the Markdown to HTML.
let html = markdown_to_html(&doc_contents);
// <a class="fence-mending-start"></a>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. Hydrate the cleaned HTML.
let html = hydrate_html(&html)
.map_err(|e| SourceToCodeChatForWebError::ParseFailed(e.to_string()))?;
// 3. Split on the separator.
let mut doc_block_contents_iter = html.split(DOC_BLOCK_SEPARATOR_SPLIT_STRING);
// <a class="fence-mending-end"></a>
// Translate each `CodeDocBlock` to its `CodeMirror` equivalent.
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),
CodeDocBlock::DocBlock(doc_block) => {
// Create the doc block.
//
// Get the length of the string in characters (not
// bytes, which is what `len()` returns).
let len = source.chars().count();
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.to_string(),
delimiter: doc_block.delimiter.to_string(),
// Used the markdown-translated replacement for this
// doc block, rather than the original string.
contents: doc_block_contents_iter.next().unwrap().to_string(),
});
// 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));
}
}
}
CodeMirrorDiffable::Plain(code_mirror)
},
};
Ok(TranslationResults::CodeChat(codechat_for_web))
}
// Like `source_to_codechat_for_web`, translate a source file to the CodeChat
// Editor client format. This wraps a call to that function with additional
// processing (determine if this is part of a project, encode the output as
// necessary, etc.).
pub fn source_to_codechat_for_web_string(
// The file's contents.
file_contents: &str,
// The path to this file.
file_path: &Path,
// The version to assign to this file.
version: f64,
// True if this file is a TOC.
is_toc: bool,
) -> Result<
(
// The resulting translation.
TranslationResultsString,
// Path to the TOC, if found; otherwise, None.
Option<PathBuf>,
),
SourceToCodeChatForWebError,
> {
// Determine the file's extension, in order to look up a lexer.
let ext = &file_path
.extension()
.unwrap_or_else(|| OsStr::new(""))
.to_string_lossy();
// 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 path_to_toc = find_path_to_toc(file_path);
let is_project = path_to_toc.is_some();
Ok((
match source_to_codechat_for_web(
file_contents,
&ext.to_string(),
version,