cli-text-reader-online 0.1.15

A less like CLI text reader
Documentation
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
use crossterm::{
  cursor::{Hide, MoveTo, Show},
  event::{self, Event as CEvent, KeyCode},
  execute,
  style::{Color, ResetColor, SetBackgroundColor, SetForegroundColor},
  terminal::{self, Clear, ClearType},
};
use std::io::{self, IsTerminal, Write};

use crate::config::load_config;
use crate::progress::{generate_hash, load_progress, save_progress};
use crate::tutorial::get_tutorial_text;

#[derive(PartialEq)]
pub enum EditorMode {
  Normal,
  Command,
  Search,
  ReverseSearch,
}

pub struct EditorState {
  pub mode: EditorMode,
  pub command_buffer: String,
  pub search_query: String,
  pub search_direction: bool, // true for forward, false for backward
  pub last_search_index: Option<usize>,
  pub current_match: Option<(usize, usize, usize)>, // (line_index, start, end)
}

impl EditorState {
  pub fn new() -> Self {
    Self {
      mode: EditorMode::Normal,
      command_buffer: String::new(),
      search_query: String::new(),
      search_direction: true,
      last_search_index: None,
      current_match: None,
    }
  }
}

pub struct Editor {
  lines: Vec<String>,
  col: usize,
  offset: usize,
  width: usize,
  height: usize,
  show_highlighter: bool,
  editor_state: EditorState,
  document_hash: u64,
  total_lines: usize,
  progress_display_until: Option<std::time::Instant>,
  show_progress: bool,
  progress_callback: Option<Box<dyn Fn(usize) + Send>>,
  read_only: bool,
}

impl Editor {
  pub fn new(lines: Vec<String>, col: usize) -> Self {
    let document_hash = generate_hash(&lines);
    let total_lines = lines.len();
    let (width, height) = terminal::size()
      .map(|(w, h)| (w as usize, h as usize))
      .unwrap_or((80, 24));

    Self {
      lines,
      col,
      offset: 0,
      width,
      height,
      show_highlighter: true,
      editor_state: EditorState::new(),
      document_hash,
      total_lines,
      progress_display_until: None,
      show_progress: false,
      progress_callback: None,
      read_only: false,
    }
  }

  pub fn set_position(&mut self, position: usize) {
    self.offset = position.min(self.total_lines.saturating_sub(1));
  }

  pub fn set_read_only(&mut self, read_only: bool) {
    self.read_only = read_only;
  }

  pub fn run_with_progress<F>(
    &mut self,
    callback: F,
  ) -> Result<(), Box<dyn std::error::Error>>
  where
    F: Fn(usize) + Send + 'static,
  {
    self.progress_callback = Some(Box::new(callback));
    self.run()
  }

  pub fn run(&mut self) -> Result<(), Box<dyn std::error::Error>> {
    let mut stdout = io::stdout();
    let config = load_config();

    self.show_highlighter = config.enable_line_highlighter.unwrap_or(true);

    let show_tutorial = match config.enable_tutorial {
      Some(false) => false,
      _ => self.lines.is_empty(),
    };

    if show_tutorial {
      self.show_tutorial(&mut stdout)?;
    }

    // If the file is empty, exit after tutorial
    if self.lines.is_empty() {
      self.cleanup(&mut stdout)?;
      return Ok(());
    }

    if std::io::stdout().is_terminal() {
      execute!(stdout, terminal::EnterAlternateScreen, Hide)?;
      terminal::enable_raw_mode()?;
    }

    self.main_loop(&mut stdout)?;

    self.cleanup(&mut stdout)?;
    Ok(())
  }

  pub fn show_tutorial(
    &self,
    stdout: &mut io::Stdout,
  ) -> Result<(), Box<dyn std::error::Error>> {
    let tutorial_lines = get_tutorial_text();

    if std::io::stdout().is_terminal() {
      // Save current state
      // let was_alternate = terminal::is_alternate_screen_active()?;
      let was_raw = terminal::is_raw_mode_enabled()?;

      // Setup tutorial display
      // if !was_alternate {
      //     execute!(stdout, terminal::EnterAlternateScreen)?;
      // }
      if !was_raw {
        terminal::enable_raw_mode()?;
      }
      execute!(stdout, Hide)?;

      let mut tutorial_offset = 0;
      loop {
        // Display tutorial with scrolling
        execute!(stdout, Clear(ClearType::All))?;
        let center_offset = if self.width > self.col {
          (self.width / 2) - self.col / 2
        } else {
          0
        };

        for (i, line) in tutorial_lines
          .iter()
          .skip(tutorial_offset)
          .take(self.height)
          .enumerate()
        {
          execute!(stdout, MoveTo(center_offset as u16, i as u16))?;
          println!("{line}");
        }

        stdout.flush()?;

        // Handle scrolling input
        if let CEvent::Key(key_event) = event::read()? {
          match key_event.code {
            KeyCode::Char('j') | KeyCode::Down => {
              if tutorial_offset + self.height < tutorial_lines.len() {
                tutorial_offset += 1;
              }
            }
            KeyCode::Char('k') | KeyCode::Up => {
              if tutorial_offset > 0 {
                tutorial_offset -= 1;
              }
            }
            KeyCode::PageDown => {
              tutorial_offset = (tutorial_offset + self.height)
                .min(tutorial_lines.len().saturating_sub(self.height));
            }
            KeyCode::PageUp => {
              tutorial_offset = tutorial_offset.saturating_sub(self.height);
            }
            _ => break,
          }
        }
      }

      // Restore original state
      execute!(stdout, Clear(ClearType::All))?;
      // if !was_alternate {
      //     execute!(stdout, terminal::LeaveAlternateScreen)?;
      // }
      if !was_raw {
        terminal::disable_raw_mode()?;
      }
    }

    Ok(())
  }

  fn cleanup(
    &self,
    stdout: &mut io::Stdout,
  ) -> Result<(), Box<dyn std::error::Error>> {
    if std::io::stdout().is_terminal() {
      execute!(stdout, Show, terminal::LeaveAlternateScreen)?;
      terminal::disable_raw_mode()?;
    }
    Ok(())
  }

  fn main_loop(
    &mut self,
    stdout: &mut io::Stdout,
  ) -> Result<(), Box<dyn std::error::Error>> {
    loop {
      if std::io::stdout().is_terminal() {
        execute!(stdout, MoveTo(0, 0), Clear(ClearType::All))?;
      }

      let center = true;
      let term_width = terminal::size()?.0 as u16;
      let center_offset =
        if self.width > self.col { (self.width / 2) - self.col / 2 } else { 0 };
      let center_offset_string =
        if center { " ".repeat(center_offset) } else { "".to_string() };

      for (i, line_orig) in
        self.lines.iter().skip(self.offset).take(self.height).enumerate()
      {
        let line = line_orig.clone();
        execute!(stdout, MoveTo(0, i as u16))?;

        if self.show_highlighter && i == self.height / 2 {
          execute!(
            stdout,
            SetBackgroundColor(Color::Rgb { r: 40, g: 40, b: 40 })
          )?;
          print!("{}", " ".repeat(term_width as usize));
          execute!(stdout, MoveTo(0, i as u16))?;
        }

        // Handle search highlight
        if let Some((line_idx, start, end)) = self.editor_state.current_match {
          if line_idx == self.offset + i {
            print!("{center_offset_string}");
            print!("{}", &line[..start]);
            execute!(
              stdout,
              SetBackgroundColor(Color::Yellow),
              SetForegroundColor(Color::Black)
            )?;
            print!("{}", &line[start..end]);
            execute!(stdout, ResetColor)?;
            println!("{}", &line[end..]);
            continue;
          }
        }

        println!("{center_offset_string}{line}");

        if self.show_highlighter && i == self.height / 2 {
          execute!(stdout, SetBackgroundColor(Color::Reset))?;
        }
      }

      if self.editor_state.mode == EditorMode::Command {
        execute!(stdout, MoveTo(0, (self.height - 1) as u16))?;
        print!(":{}", self.editor_state.command_buffer);
      } else if self.editor_state.mode == EditorMode::Search {
        execute!(stdout, MoveTo(0, (self.height - 1) as u16))?;
        print!("/{}", self.editor_state.command_buffer);
      } else if self.editor_state.mode == EditorMode::ReverseSearch {
        execute!(stdout, MoveTo(0, (self.height - 1) as u16))?;
        print!("?{}", self.editor_state.command_buffer);
      }

      // Show progress if enabled
      if self.show_progress {
        let progress =
          (self.offset as f64 / self.total_lines as f64 * 100.0).round();
        let message = format!("{progress}%");
        let x = self.width as u16 - message.len() as u16 - 2;
        let y = self.height as u16 - 2;
        execute!(stdout, MoveTo(x, y))?;
        print!("{message}");
      }

      // Show read-only indicator if in read-only mode
      if self.read_only {
        let message = "READ-ONLY";
        let x = 2;
        let y = self.height as u16 - 2;
        execute!(stdout, MoveTo(x, y), SetForegroundColor(Color::Yellow))?;
        print!("{message}");
        execute!(stdout, ResetColor)?;
      }

      stdout.flush()?;

      if std::io::stdout().is_terminal() {
        match event::read()? {
          CEvent::Key(key_event) => match self.editor_state.mode {
            EditorMode::Normal => match key_event.code {
              KeyCode::Char(':') => {
                self.editor_state.mode = EditorMode::Command;
                self.editor_state.command_buffer.clear();
              }
              KeyCode::Char('/') => {
                self.editor_state.mode = EditorMode::Search;
                self.editor_state.command_buffer.clear();
                self.editor_state.search_direction = true;
              }
              KeyCode::Char('?') => {
                self.editor_state.mode = EditorMode::ReverseSearch;
                self.editor_state.command_buffer.clear();
                self.editor_state.search_direction = false;
              }
              KeyCode::Char('n') => {
                if !self.editor_state.search_query.is_empty() {
                  // Use the original search direction
                  self.find_next_match(self.editor_state.search_direction);
                  self.center_on_match();
                }
              }
              KeyCode::Char('N') => {
                if !self.editor_state.search_query.is_empty() {
                  // Use opposite of original search direction
                  self.find_next_match(!self.editor_state.search_direction);
                  self.center_on_match();
                }
              }
              KeyCode::Char('j') | KeyCode::Down => {
                if self.offset + self.height < self.total_lines {
                  self.offset += 1;

                  // If we have a progress callback and we're not in read-only
                  // mode, call it
                  if let Some(callback) = &self.progress_callback {
                    if !self.read_only {
                      callback(self.offset);
                    }
                  }
                }
              }
              KeyCode::Char('k') | KeyCode::Up => {
                if self.offset > 0 {
                  self.offset -= 1;

                  // If we have a progress callback and we're not in read-only
                  // mode, call it
                  if let Some(callback) = &self.progress_callback {
                    if !self.read_only {
                      callback(self.offset);
                    }
                  }
                }
              }
              KeyCode::PageDown => {
                if self.offset + self.height < self.total_lines {
                  self.offset += self.height - 3;

                  // If we have a progress callback and we're not in read-only
                  // mode, call it
                  if let Some(callback) = &self.progress_callback {
                    if !self.read_only {
                      callback(self.offset);
                    }
                  }
                }
              }
              KeyCode::PageUp => {
                if self.offset as i32 - self.height as i32 > 0 {
                  self.offset -= self.height - 3;
                } else {
                  self.offset = 0;
                }

                // If we have a progress callback and we're not in read-only
                // mode, call it
                if let Some(callback) = &self.progress_callback {
                  if !self.read_only {
                    callback(self.offset);
                  }
                }
              }
              _ => {}
            },
            EditorMode::Search | EditorMode::ReverseSearch => {
              match key_event.code {
                KeyCode::Esc => {
                  self.editor_state.mode = EditorMode::Normal;
                  self.editor_state.command_buffer.clear();
                }
                KeyCode::Enter => {
                  self.editor_state.search_query =
                    self.editor_state.command_buffer.clone();
                  // Start from current position
                  self.find_next_match(
                    self.editor_state.mode == EditorMode::Search,
                  );
                  self.center_on_match();
                  self.editor_state.mode = EditorMode::Normal;
                  self.editor_state.command_buffer.clear();
                }
                KeyCode::Backspace => {
                  self.editor_state.command_buffer.pop();
                }
                KeyCode::Char(c) => {
                  self.editor_state.command_buffer.push(c);
                }
                _ => {}
              }
            }
            EditorMode::Command => match key_event.code {
              KeyCode::Esc => {
                self.editor_state.mode = EditorMode::Normal;
                self.editor_state.command_buffer.clear();
              }
              KeyCode::Enter => {
                if self.execute_command(stdout)? {
                  return Ok(());
                }
                self.editor_state.mode = EditorMode::Normal;
                self.editor_state.command_buffer.clear();
              }
              KeyCode::Backspace => {
                self.editor_state.command_buffer.pop();
              }
              KeyCode::Char(c) => {
                self.editor_state.command_buffer.push(c);
              }
              _ => {}
            },
          },
          CEvent::Resize(w, h) => {
            self.width = w as usize;
            self.height = h as usize;
          }
          _ => {}
        }
      } else {
        break;
      }

      save_progress(self.document_hash, self.offset, self.total_lines)?;
    }

    Ok(())
  }

  fn execute_command(
    &mut self,
    stdout: &mut io::Stdout,
  ) -> Result<bool, Box<dyn std::error::Error>> {
    match self.editor_state.command_buffer.trim() {
      "p" => {
        self.show_progress = !self.show_progress;
        self.editor_state.mode = EditorMode::Normal;
        self.editor_state.command_buffer.clear();
        Ok(false)
      }
      "help" | "tutorial" => {
        self.show_tutorial(stdout)?;
        self.editor_state.mode = EditorMode::Normal;
        self.editor_state.command_buffer.clear();
        Ok(false)
      }
      cmd => Ok(handle_command(cmd, &mut self.show_highlighter)),
    }
  }

  fn find_next_match(&mut self, forward: bool) {
    if self.editor_state.search_query.is_empty() {
      return;
    }

    let query = self.editor_state.search_query.to_lowercase();
    let start_idx = if let Some((idx, _, _)) = self.editor_state.current_match {
      idx
    } else {
      self.offset
    };

    let find_in_line = |line: &str, query: &str| -> Option<(usize, usize)> {
      line.to_lowercase().find(query).map(|start| (start, start + query.len()))
    };

    if forward {
      // Forward search
      for i in start_idx + 1..self.lines.len() {
        if let Some((start, end)) = find_in_line(&self.lines[i], &query) {
          self.editor_state.current_match = Some((i, start, end));
          return;
        }
      }
      // Wrap around to beginning
      for i in 0..=start_idx {
        if let Some((start, end)) = find_in_line(&self.lines[i], &query) {
          self.editor_state.current_match = Some((i, start, end));
          return;
        }
      }
    } else {
      // Backward search
      for i in (0..start_idx).rev() {
        if let Some((start, end)) = find_in_line(&self.lines[i], &query) {
          self.editor_state.current_match = Some((i, start, end));
          return;
        }
      }
      // Wrap around to end
      for i in (start_idx..self.lines.len()).rev() {
        if let Some((start, end)) = find_in_line(&self.lines[i], &query) {
          self.editor_state.current_match = Some((i, start, end));
          return;
        }
      }
    }
  }

  fn center_on_match(&mut self) {
    if let Some((line_idx, _, _)) = self.editor_state.current_match {
      let half_height = (self.height / 2) as i32;
      let new_offset = line_idx as i32 - half_height;
      self.offset = if new_offset < 0 {
        0
      } else if new_offset + self.height as i32 > self.total_lines as i32 {
        self.total_lines - self.height
      } else {
        new_offset as usize
      };
    }
  }
}

pub fn handle_command(command: &str, show_highlighter: &mut bool) -> bool {
  match command.trim() {
    "q" => true,
    "z" => {
      *show_highlighter = !*show_highlighter;
      false
    }
    "p" | "help" | "tutorial" => false,
    _ => false,
  }
}