//! Renders a bit of code as HTML. use ide_db::base_db::SourceDatabase; use oorandom::Rand32; use stdx::format_to; use syntax::AstNode; use crate::{ syntax_highlighting::{highlight, HighlightConfig}, FileId, RootDatabase, }; pub(crate) fn highlight_as_html(db: &RootDatabase, file_id: FileId, rainbow: bool) -> String { let parse = db.parse(file_id); fn rainbowify(seed: u64) -> String { let mut rng = Rand32::new(seed); format!( "hsl({h},{s}%,{l}%)", h = rng.rand_range(0..361), s = rng.rand_range(42..99), l = rng.rand_range(40..91), ) } let hl_ranges = highlight( db, HighlightConfig { strings: true, punctuation: true, specialize_punctuation: true, specialize_operator: true, operator: true, inject_doc_comment: true, macro_bang: true, syntactic_name_ref_highlighting: false, }, file_id, None, ); let text = parse.tree().syntax().to_string(); let mut buf = String::new(); buf.push_str(STYLE); buf.push_str("
");
    for r in &hl_ranges {
        let chunk = html_escape(&text[r.range]);
        if r.highlight.is_empty() {
            format_to!(buf, "{}", chunk);
            continue;
        }

        let class = r.highlight.to_string().replace('.', " ");
        let color = match (rainbow, r.binding_hash) {
            (true, Some(hash)) => {
                format!(" data-binding-hash=\"{}\" style=\"color: {};\"", hash, rainbowify(hash))
            }
            _ => "".into(),
        };
        format_to!(buf, "{}", class, color, chunk);
    }
    buf.push_str("
"); buf } //FIXME: like, real html escaping fn html_escape(text: &str) -> String { text.replace('<', "<").replace('>', ">") } const STYLE: &str = " ";