1use anyhow::Result;
2use std::io::{BufRead, Write};
3use std::path::PathBuf;
4use std::{fs::File, io::BufReader};
5use tui_textarea::TextArea;
6
7pub fn save_textareas(textareas: &[TextArea], titles: &[String], file_path: PathBuf) -> Result<()> {
8 let mut file = File::create(file_path)?;
9 for (textarea, title) in textareas.iter().zip(titles.iter()) {
10 writeln!(file, "# {}", title)?;
11 let content = textarea.lines().join("\n");
12 let mut in_code_block = false;
13 for line in content.lines() {
14 if line.trim().starts_with("```") {
15 in_code_block = !in_code_block;
16 }
17 if in_code_block || !line.starts_with('#') {
18 writeln!(file, "{}", line)?;
19 } else {
20 writeln!(file, "\\{}", line)?;
21 }
22 }
23 }
24 Ok(())
25}
26
27pub fn load_textareas(file_path: PathBuf) -> Result<(Vec<TextArea<'static>>, Vec<String>)> {
28 let file = File::open(file_path)?;
29 let reader = BufReader::new(file);
30 let mut textareas = Vec::with_capacity(10);
31 let mut titles = Vec::with_capacity(10);
32 let mut current_textarea = TextArea::default();
33 let mut current_title = String::new();
34 let mut in_code_block = false;
35 let mut is_first_line = true;
36
37 for line in reader.lines() {
38 let line = line?;
39 if !in_code_block && line.starts_with("# ") && is_first_line {
40 current_title = line[2..].to_string();
41 is_first_line = false;
42 } else {
43 if line.trim().starts_with("```") {
44 in_code_block = !in_code_block;
45 }
46 if in_code_block {
47 current_textarea.insert_str(&line);
48 } else if let Some(strip) = line.strip_prefix('\\') {
49 current_textarea.insert_str(strip);
50 } else if line.starts_with("# ") && !is_first_line {
51 if !current_title.is_empty() {
52 textareas.push(current_textarea);
53 titles.push(current_title);
54 }
55 current_textarea = TextArea::default();
56 current_title = line[2..].to_string();
57 is_first_line = true;
58 continue;
59 } else {
60 current_textarea.insert_str(&line);
61 }
62 current_textarea.insert_newline();
63 is_first_line = false;
64 }
65 }
66
67 if !current_title.is_empty() {
68 textareas.push(current_textarea);
69 titles.push(current_title);
70 }
71
72 Ok((textareas, titles))
73}