1 //! Renders a bit of code as HTML.
3 use ide_db::base_db::SourceDatabase;
6 use syntax::{AstNode, TextRange, TextSize};
8 use crate::{syntax_highlighting::highlight, FileId, RootDatabase};
10 pub(crate) fn highlight_as_html(db: &RootDatabase, file_id: FileId, rainbow: bool) -> String {
11 let parse = db.parse(file_id);
13 fn rainbowify(seed: u64) -> String {
14 let mut rng = Rand32::new(seed);
17 h = rng.rand_range(0..361),
18 s = rng.rand_range(42..99),
19 l = rng.rand_range(40..91),
23 let ranges = highlight(db, file_id, None, false);
24 let text = parse.tree().syntax().to_string();
25 let mut prev_pos = TextSize::from(0);
26 let mut buf = String::new();
28 buf.push_str("<pre><code>");
29 for range in &ranges {
30 if range.range.start() > prev_pos {
31 let curr = &text[TextRange::new(prev_pos, range.range.start())];
32 let text = html_escape(curr);
35 let curr = &text[TextRange::new(range.range.start(), range.range.end())];
37 let class = range.highlight.to_string().replace('.', " ");
38 let color = match (rainbow, range.binding_hash) {
39 (true, Some(hash)) => {
40 format!(" data-binding-hash=\"{}\" style=\"color: {};\"", hash, rainbowify(hash))
44 format_to!(buf, "<span class=\"{}\"{}>{}</span>", class, color, html_escape(curr));
46 prev_pos = range.range.end();
48 // Add the remaining (non-highlighted) text
49 let curr = &text[TextRange::new(prev_pos, TextSize::of(&text))];
50 let text = html_escape(curr);
52 buf.push_str("</code></pre>");
56 //FIXME: like, real html escaping
57 fn html_escape(text: &str) -> String {
58 text.replace("<", "<").replace(">", ">")
64 pre { color: #DCDCCC; background: #3F3F3F; font-size: 22px; padding: 0.4em; }
66 .lifetime { color: #DFAF8F; font-style: italic; }
67 .label { color: #DFAF8F; font-style: italic; }
68 .comment { color: #7F9F7F; }
69 .documentation { color: #629755; }
70 .injected { opacity: 0.65 ; }
71 .struct, .enum { color: #7CB8BB; }
72 .enum_variant { color: #BDE0F3; }
73 .string_literal { color: #CC9393; }
74 .field { color: #94BFF3; }
75 .function { color: #93E0E3; }
76 .function.unsafe { color: #BC8383; }
77 .operator.unsafe { color: #BC8383; }
78 .parameter { color: #94BFF3; }
79 .text { color: #DCDCCC; }
80 .type { color: #7CB8BB; }
81 .builtin_type { color: #8CD0D3; }
82 .type_param { color: #DFAF8F; }
83 .attribute { color: #94BFF3; }
84 .numeric_literal { color: #BFEBBF; }
85 .bool_literal { color: #BFE6EB; }
86 .macro { color: #94BFF3; }
87 .module { color: #AFD8AF; }
88 .value_param { color: #DCDCCC; }
89 .variable { color: #DCDCCC; }
90 .format_specifier { color: #CC696B; }
91 .mutable { text-decoration: underline; }
92 .escape_sequence { color: #94BFF3; }
93 .keyword { color: #F0DFAF; font-weight: bold; }
94 .keyword.unsafe { color: #BC8383; font-weight: bold; }
95 .control { font-style: italic; }
97 .unresolved_reference { color: #FC5555; text-decoration: wavy underline; }