From ddcae106a51e29820a2ee2010fc9f88aaabd470c Mon Sep 17 00:00:00 2001 From: mia Date: Sun, 7 Apr 2024 04:29:21 -0700 Subject: escape html, buffer stdout --- src/main.rs | 30 +++++++++++++++++++++++------- 1 file changed, 23 insertions(+), 7 deletions(-) diff --git a/src/main.rs b/src/main.rs index 74db5cd..22ea865 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,4 +1,8 @@ -use std::{path::PathBuf, str::FromStr}; +use std::{ + io::{stdout, BufWriter, Write}, + path::PathBuf, + str::FromStr, +}; use syntect::{ dumps::{dump_to_uncompressed_file, from_uncompressed_dump_file}, @@ -158,7 +162,9 @@ fn highlight() { .or_else(|| set.find_syntax_by_first_line(&line)) .unwrap_or_else(|| set.find_syntax_plain_text()); - print!(r#"
"#);
+    let mut stdout = BufWriter::new(stdout().lock());
+
+    write!(&mut stdout, r#"
"#).unwrap();
 
     let mut parse = ParseState::new(syntax);
     let mut stack = ScopeStack::new();
@@ -191,17 +197,27 @@ fn highlight() {
 
         for (section, class) in spans {
             if let Some(idx) = class {
-                print!(r#""#)
+                write!(&mut stdout, r#""#).unwrap();
+            }
+            for ch in section.chars() {
+                match ch {
+                    '>' => write!(&mut stdout, ">").unwrap(),
+                    '<' => write!(&mut stdout, "<").unwrap(),
+                    '&' => write!(&mut stdout, "&").unwrap(),
+                    '\'' => write!(&mut stdout, "'").unwrap(),
+                    '"' => write!(&mut stdout, """).unwrap(),
+                    _ => write!(&mut stdout, "{ch}").unwrap(),
+                }
             }
-            print!("{section}");
             if class.is_some() {
-                print!("");
+                write!(&mut stdout, "").unwrap();
             }
         }
 
+        stdout.flush().unwrap();
         line.clear();
         if std::io::stdin().read_line(&mut line).unwrap() == 0 {
-            println!();
+            write!(&mut stdout, "\n").unwrap();
             break;
         }
         if !line.ends_with('\n') {
@@ -209,5 +225,5 @@ fn highlight() {
         }
     }
 
-    print!("
"); + write!(&mut stdout, "
").unwrap(); } -- cgit 1.4.1