File: parsyncat.rs

package info (click to toggle)
rustc 1.85.0%2Bdfsg3-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental, sid, trixie
  • size: 893,396 kB
  • sloc: xml: 158,127; python: 35,830; javascript: 19,497; cpp: 19,002; sh: 17,245; ansic: 13,127; asm: 4,376; makefile: 1,051; perl: 29; lisp: 29; ruby: 19; sql: 11
file content (61 lines) | stat: -rw-r--r-- 2,073 bytes parent folder | download | duplicates (5)
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
//! Highlights the files given on the command line, in parallel.
//! Prints the highlighted output to stdout.

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

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

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).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::util::as_24_bit_terminal_escaped(&file_regions[..], true));
    }
}