File: parsyncat.rs

package info (click to toggle)
rust-syntect-no-panic 6.0.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,080 kB
  • sloc: makefile: 2
file content (72 lines) | stat: -rw-r--r-- 2,326 bytes parent folder | download
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
//! Highlights the files given on the command line, in parallel.
//! Prints the highlighted output to stdout.

use rayon::prelude::*;
use syntect_no_panic::easy::{HighlightFile, HighlightOptions};
use syntect_no_panic::highlighting::{Style, ThemeSet};
use syntect_no_panic::parsing::SyntaxSet;

use std::fs::File;
use std::io::{BufRead, BufReader};

fn main() {
    let files: Vec<String> = std::env::args().skip(1).collect();

    if files.is_empty() {
        println!("Please provide some files to highlight.");
        return;
    }

    let syntax_set = SyntaxSet::load_defaults_newlines();
    let theme_set = ThemeSet::load_defaults();

    // We first collect the contents of the files...
    let contents: Vec<Vec<String>> = files
        .par_iter()
        .map(|filename| {
            let mut lines = Vec::new();
            // We use `String::new()` and `read_line()` instead of `BufRead::lines()`
            // in order to preserve the newlines and get better highlighting.
            let mut line = String::new();
            let mut reader = BufReader::new(File::open(filename).unwrap());
            while reader.read_line(&mut line).unwrap() > 0 {
                lines.push(line);
                line = String::new();
            }
            lines
        })
        .collect();

    // ...so that the highlighted regions have valid lifetimes...
    let regions: Vec<Vec<(Style, &str)>> = files
        .par_iter()
        .zip(&contents)
        .map(|(filename, contents)| {
            let mut regions = Vec::new();
            let theme = &theme_set.themes["base16-ocean.dark"];
            let mut highlighter =
                HighlightFile::new(filename, &syntax_set, theme, HighlightOptions::default())
                    .unwrap();

            for line in contents {
                for region in highlighter
                    .highlight_lines
                    .highlight_line(line, &syntax_set)
                    .unwrap()
                {
                    regions.push(region);
                }
            }

            regions
        })
        .collect();

    // ...and then print them all out.
    for file_regions in regions {
        print!(
            "{}",
            syntect_no_panic::util::as_24_bit_terminal_escaped(&file_regions[..], true)
        );
    }
}