1 //! Renders a bit of code as HTML.
3 use ra_db::SourceDatabase;
4 use ra_syntax::{AstNode, TextRange, TextSize};
6 use crate::{syntax_highlighting::highlight, FileId, RootDatabase};
8 pub(crate) fn highlight_as_html(db: &RootDatabase, file_id: FileId, rainbow: bool) -> String {
9 let parse = db.parse(file_id);
11 fn rainbowify(seed: u64) -> String {
13 let mut rng = SmallRng::seed_from_u64(seed);
16 h = rng.gen_range::<u16, _, _>(0, 361),
17 s = rng.gen_range::<u16, _, _>(42, 99),
18 l = rng.gen_range::<u16, _, _>(40, 91),
22 let ranges = highlight(db, file_id, None);
23 let text = parse.tree().syntax().to_string();
24 let mut prev_pos = TextSize::from(0);
25 let mut buf = String::new();
27 buf.push_str("<pre><code>");
28 for range in &ranges {
29 if range.range.start() > prev_pos {
30 let curr = &text[TextRange::new(prev_pos, range.range.start())];
31 let text = html_escape(curr);
34 let curr = &text[TextRange::new(range.range.start(), range.range.end())];
36 let class = range.highlight.to_string().replace('.', " ");
37 let color = match (rainbow, range.binding_hash) {
38 (true, Some(hash)) => {
39 format!(" data-binding-hash=\"{}\" style=\"color: {};\"", hash, rainbowify(hash))
43 buf.push_str(&format!("<span class=\"{}\"{}>{}</span>", class, color, html_escape(curr)));
45 prev_pos = range.range.end();
47 // Add the remaining (non-highlighted) text
48 let curr = &text[TextRange::new(prev_pos, TextSize::of(&text))];
49 let text = html_escape(curr);
51 buf.push_str("</code></pre>");
55 //FIXME: like, real html escaping
56 fn html_escape(text: &str) -> String {
57 text.replace("<", "<").replace(">", ">")
63 pre { color: #DCDCCC; background: #3F3F3F; font-size: 22px; padding: 0.4em; }
65 .lifetime { color: #DFAF8F; font-style: italic; }
66 .comment { color: #7F9F7F; }
67 .struct, .enum { color: #7CB8BB; }
68 .enum_variant { color: #BDE0F3; }
69 .string_literal { color: #CC9393; }
70 .field { color: #94BFF3; }
71 .function { color: #93E0E3; }
72 .parameter { color: #94BFF3; }
73 .text { color: #DCDCCC; }
74 .type { color: #7CB8BB; }
75 .builtin_type { color: #8CD0D3; }
76 .type_param { color: #DFAF8F; }
77 .attribute { color: #94BFF3; }
78 .numeric_literal { color: #BFEBBF; }
79 .bool_literal { color: #BFE6EB; }
80 .macro { color: #94BFF3; }
81 .module { color: #AFD8AF; }
82 .variable { color: #DCDCCC; }
83 .format_specifier { color: #CC696B; }
84 .mutable { text-decoration: underline; }
86 .keyword { color: #F0DFAF; font-weight: bold; }
87 .keyword.unsafe { color: #BC8383; font-weight: bold; }
88 .control { font-style: italic; }