moros 0.12.0

MOROS: Obscure Rust Operating System
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
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
use crate::api;
use crate::api::console::Style;
use crate::api::process::ExitCode;
use crate::api::prompt::Prompt;
use crate::api::regex::Regex;
use crate::api::{console, fs, io};

use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec;
use alloc::vec::Vec;
use core::cmp;

enum Cmd {
    Delete,
    Open,
    Quit,
    Replace,
    Save,
}

struct EditorConfig {
    tab_size: usize,
}

#[derive(Clone)]
struct Coords {
    pub x: usize,
    pub y: usize,
}

#[derive(Clone)]
pub struct Buffer {
    pathname: String,
    lines: Vec<String>,
    cursor: Coords,
    offset: Coords,
    highlighted: Vec<(usize, usize, char)>,
}

impl From<&str> for Buffer {
    fn from(pathname: &str) -> Self {
        let p: Vec<&str> = pathname.split(':').collect();
        let pathname = p[0].to_string();
        let y = p.get(1).and_then(|s| {
            s.parse::<usize>().ok()
        }).unwrap_or(1).saturating_sub(1);
        let x = p.get(2).and_then(|s| {
            s.parse::<usize>().ok()
        }).unwrap_or(1).saturating_sub(1);

        let cursor = Coords { x: x % cols(), y: y % rows() };
        let offset = Coords { x: x - cursor.x, y: y - cursor.y };
        let highlighted = Vec::new();
        let mut lines = Vec::new();

        match fs::read_to_string(&pathname) {
            Ok(contents) => {
                for line in contents.lines() {
                    lines.push(line.into());
                }
                if lines.is_empty() {
                    lines.push(String::new());
                }
            }
            Err(_) => {
                lines.push(String::new());
            }
        };

        Self {
            pathname,
            lines,
            cursor,
            offset,
            highlighted,
        }
    }
}

impl From<&Editor> for Buffer {
    fn from(editor: &Editor) -> Self {
        Buffer {
            pathname: editor.pathname.clone(),
            lines: editor.lines.clone(),
            cursor: editor.cursor.clone(),
            offset: editor.offset.clone(),
            highlighted: editor.highlighted.clone(),
        }
    }
}

pub struct Editor {
    buffer_prompt: Prompt,
    buffers: Vec<Buffer>,
    buf: usize,

    pathname: String,
    lines: Vec<String>,
    cursor: Coords,
    offset: Coords,
    highlighted: Vec<(usize, usize, char)>,

    clipboard: Option<String>,
    config: EditorConfig,
    search_prompt: Prompt,
    search_query: String,
    command_prompt: Prompt,
    command_history: String,
}

impl Editor {
    pub fn new(pathname: &str) -> Self {
        let clipboard = None;
        let config = EditorConfig { tab_size: 4 };

        let search_query = String::new();
        let mut search_prompt = Prompt::new();
        search_prompt.eol = false;

        let mut command_prompt = Prompt::new();
        let command_history = "~/.edit-history".to_string();
        command_prompt.history.load(&command_history);
        command_prompt.eol = false;

        // TODO: Add path autocompletion
        let mut buffer_prompt = Prompt::new();
        buffer_prompt.eol = false;

        let buf = Buffer::from(pathname);

        let pathname = buf.pathname.clone();
        let lines = buf.lines.clone();
        let cursor = buf.cursor.clone();
        let offset = buf.offset.clone();
        let highlighted = buf.highlighted.clone();

        let buffers = vec![buf];
        let buf = 0;

        Self {
            buffer_prompt,
            buffers,
            buf,
            pathname,
            clipboard,
            lines,
            cursor,
            offset,
            highlighted,
            config,
            search_prompt,
            search_query,
            command_prompt,
            command_history,
        }
    }

    pub fn save(&mut self, path: &str) -> Result<(), ExitCode> {
        let contents = self.lines.join("\n") + "\n";

        if fs::write(path, contents.as_bytes()).is_ok() {
            self.pathname = path.into();
            let n = self.lines.len();
            let status = format!("Wrote {}L to '{}'", n, path);
            self.print_status(&status, "yellow");
            Ok(())
        } else {
            let status = format!("Could not write to '{}'", path);
            self.print_status(&status, "red");
            Err(ExitCode::Failure)
        }
    }

    fn print_status(&mut self, status: &str, background: &str) {
        // Move cursor to the bottom of the screen
        print!("\x1b[{};1H", rows() + 1);

        let color = Style::color("black").with_background(background);
        let reset = Style::reset();
        print!("{}{:cols$}{}", color, status, reset, cols = cols());

        // Move cursor back
        print!("\x1b[{};{}H", self.cursor.y + 1, self.cursor.x + 1);
    }

    fn print_editing_status(&mut self) {
        let max = 50;
        let mut path = self.pathname.clone();
        if self.pathname.chars().count() > max {
            path.truncate(max - 3);
            path.push_str("...");
        }
        let start = format!("Editing '{}'", path);

        let x = self.offset.x + self.cursor.x + 1;
        let y = self.offset.y + self.cursor.y + 1;
        let n = y * 100 / self.lines.len();
        let end = format!("{},{} {:3}%", y, x, n);

        let width = cols() - start.chars().count();
        let status = format!("{}{:>width$}", start, end, width = width);

        self.print_status(&status, "silver");
    }

    fn print_screen(&mut self) {
        let mut lines: Vec<String> = Vec::new();
        let a = self.offset.y;
        let b = self.offset.y + rows();
        for y in a..b {
            lines.push(self.render_line(y));
        }
        println!("\x1b[1;1H{}", lines.join("\n"));
    }

    fn render_line(&self, y: usize) -> String {
        // Render line into a row of the screen, or an empty row when past EOF
        let line = if y < self.lines.len() {
            &self.lines[y]
        } else {
            ""
        };

        let s = format!("{:cols$}", line, cols = self.offset.x);
        let mut row: Vec<char> = s.chars().collect();
        let n = self.offset.x + cols();
        let after = if row.len() > n {
            row.truncate(n - 1);
            truncated_line_indicator()
        } else {
            " ".repeat(n - row.len())
        };
        row.extend(after.chars());
        row[self.offset.x..].iter().collect()
    }

    fn render_char(&self, c: char) -> Option<String> {
        match c {
            '\t' => Some(" ".repeat(self.config.tab_size)),
            c if console::is_printable(c) => Some(c.to_string()),
            _ => None,
        }
    }

    fn match_chars(&mut self, opening: char, closing: char) {
        let mut stack = Vec::new();
        let ox = self.offset.x;
        let oy = self.offset.y;
        let cx = self.cursor.x;
        let cy = self.cursor.y;
        if let Some(cursor) = self.lines[oy + cy].chars().nth(ox + cx) {
            if cursor == closing {
                for (y, line) in self.lines.iter().enumerate() {
                    for (x, c) in line.chars().enumerate() {
                        if oy + cy == y && ox + cx == x {
                            // Cursor position
                            if let Some((x, y)) = stack.pop() {
                                self.highlighted.push((cx, cy, closing));
                                let is_col = ox <= x && x < ox + cols();
                                let is_row = oy <= y && y < oy + rows();
                                if is_col && is_row {
                                    self.highlighted.push(
                                        (x - ox, y - oy, opening)
                                    );
                                }
                            }
                            return;
                        }
                        if c == opening {
                            stack.push((x, y));
                        }
                        if c == closing {
                            stack.pop();
                        }
                    }
                    if oy + cy == y {
                        break;
                    }
                }
            }
            if cursor == opening {
                for (y, line) in self.lines.iter().enumerate().skip(oy + cy) {
                    for (x, c) in line.chars().enumerate() {
                        if y == oy + cy && x <= ox + cx {
                            continue; // Skip chars before cursor
                        }
                        if c == opening {
                            stack.push((x, y));
                        }
                        if c == closing {
                            if stack.pop().is_none() {
                                self.highlighted.push((cx, cy, opening));
                                let is_col = ox <= x && x < ox + cols();
                                let is_row = oy <= y && y < oy + rows();
                                if is_col && is_row {
                                    self.highlighted.push(
                                        (x - ox, y - oy, closing)
                                    );
                                }
                                return;
                            }
                        }
                    }
                }
            }
        }
    }

    fn print_highlighted(&mut self) {
        self.match_chars('(', ')');
        self.match_chars('{', '}');
        self.match_chars('[', ']');
        let color = Style::color("red");
        let reset = Style::reset();
        for (x, y, c) in &self.highlighted {
            if *x == cols() - 1 {
                continue;
            }
            print!("\x1b[{};{}H", y + 1, x + 1);
            print!("{}{}{}", color, c, reset);
        }
    }

    fn clear_highlighted(&mut self) {
        let reset = Style::reset();
        for (x, y, c) in &self.highlighted {
            if *x == cols() - 1 {
                continue;
            }
            print!("\x1b[{};{}H", y + 1, x + 1);
            print!("{}{}", reset, c);
        }
        self.highlighted.clear();
    }

    // Align cursor that is past the end of the line, to the end
    // of the line.
    //
    // If the cursor is somewhere on the long line on the second
    // screen in the following diagram, going down should move
    // the cursor to the end of the short line and display the
    // first screen instead of the second screen.
    //
    // +----------------------------+----------------------------+
    // |                            |                            |
    // | This is a loooooooooooooooo|oooooong line               |
    // | This is a short line       |          ^                 |
    // |                     ^      |                            |
    // +----------------------------+----------------------------+
    fn align_cursor(&mut self) {
        let x = self.offset.x + self.cursor.x;
        let y = self.offset.y + self.cursor.y;
        let eol = self.lines[y].chars().count();
        if x > eol {
            let n = cols();
            self.offset.x = (eol / n) * n;
            self.cursor.x = eol % n;
        }
    }

    pub fn run(&mut self) -> Result<(), ExitCode> {
        print!("\x1b[2J\x1b[1;1H"); // Clear screen and move to top
        self.print_screen();
        self.print_editing_status();
        self.print_highlighted();
        print!("\x1b[{};{}H", self.cursor.y + 1, self.cursor.x + 1);

        let mut escape = false;
        let mut csi = false;
        let mut csi_params = String::new();
        loop {
            let c = io::stdin().read_char().unwrap_or('\0');
            print!("\x1b[?25l"); // Disable cursor
            self.clear_highlighted();
            print!("\x1b[{};{}H", self.cursor.y + 1, self.cursor.x + 1);

            match c {
                '\x1B' => { // Esc
                    escape = true;
                    continue;
                }
                '[' if escape => {
                    csi = true;
                    csi_params.clear();
                    continue;
                }
                '\0' => {
                    continue;
                }
                '\x11' | '\x03' => { // Ctrl + Q or Ctrl + C
                    print!("\x1b[2J\x1b[1;1H"); // Clear screen and move to top
                    print!("\x1b[?25h"); // Enable cursor
                    break;
                }
                '\x17' => { // Ctrl + W
                    self.save(&self.pathname.clone()).ok();
                    print!("\x1b[?25h"); // Enable cursor
                    continue;
                }
                '\x18' => { // Ctrl + X
                    let res = self.save(&self.pathname.clone());
                    print!("\x1b[2J\x1b[1;1H"); // Clear screen and move to top
                    print!("\x1b[?25h"); // Enable cursor
                    return res;
                }
                '\n' => { // Newline
                    self.handle_newline();
                }
                '~' if csi && csi_params == "5" => { // Page Up
                    self.handle_page_up();
                }
                '~' if csi && csi_params == "6" => { // Page Down
                    self.handle_page_down();
                }
                'A' if csi => { // Arrow Up
                    self.handle_arrow_up();
                }
                'B' if csi => { // Arrow Down
                    self.handle_arrow_down();
                }
                'C' if csi => { // Arrow Right
                    let line = &self.lines[self.offset.y + self.cursor.y];
                    let x = self.cursor.x + self.offset.x;
                    let n = line.chars().count();
                    if line.is_empty() || x >= n {
                        print!("\x1b[?25h"); // Enable cursor
                        escape = false;
                        csi = false;
                        continue;
                    } else if self.cursor.x == cols() - 1 {
                        self.offset.x += cols();
                        self.cursor.x -= cols() - 1;
                        self.print_screen();
                    } else {
                        self.cursor.x += 1;
                    }
                }
                'D' if csi => { // Arrow Left
                    if self.cursor.x + self.offset.x == 0 {
                        print!("\x1b[?25h"); // Enable cursor
                        escape = false;
                        csi = false;
                        continue;
                    } else if self.cursor.x == 0 {
                        self.offset.x -= cols();
                        self.cursor.x += cols() - 1;
                        self.align_cursor();
                        self.print_screen();
                    } else {
                        self.cursor.x -= 1;
                    }
                }
                'Z' if csi => { // Backtab (Shift + Tab)
                     // Do nothing
                }
                'I' if csi && csi_params == "1;5" => { // Ctrl + Tab
                    self.next_buffer();
                    self.print_screen();
                }
                'I' if csi && csi_params == "1;6" => { // Ctrl + Shift + Tab
                    self.previous_buffer();
                    self.print_screen();
                }
                '\x14' => { // Ctrl + T -> Go to top of file
                    self.cursor.x = 0;
                    self.cursor.y = 0;
                    self.offset.x = 0;
                    self.offset.y = 0;
                    self.print_screen();
                }
                '\x02' => { // Ctrl + B -> Go to bottom of file
                    self.cursor.x = 0;
                    self.cursor.y = cmp::min(rows(), self.lines.len()) - 1;
                    self.offset.x = 0;
                    self.offset.y = self.lines.len() - 1 - self.cursor.y;
                    self.print_screen();
                }
                '\x01' => { // Ctrl + A -> Go to beginning of line
                    self.cursor.x = 0;
                    self.offset.x = 0;
                    self.print_screen();
                }
                '\x05' => { // Ctrl + E -> Go to end of line
                    let line = &self.lines[self.offset.y + self.cursor.y];
                    let n = line.chars().count();
                    let w = cols();
                    self.cursor.x = n % w;
                    self.offset.x = w * (n / w);
                    self.print_screen();
                }
                '\x04' => { // Ctrl + D -> Delete (cut) line
                    self.cut_line();
                }
                '\x19' => { // Ctrl + Y -> Yank (copy) line
                    self.copy_line();
                }
                '\x10' => { // Ctrl + P -> Put (paste) line
                    self.paste_line();
                }
                '\x06' => { // Ctrl + F -> Find
                    self.find();
                    self.print_screen();
                }
                '\x0E' => { // Ctrl + N -> Find next
                    self.find_next();
                    self.print_screen();
                }
                '\x0F' => { // Ctrl + O -> Open buffer
                    self.open();
                    self.print_screen();
                }
                '\x0B' => { // Ctrl + X -> Kill buffer
                    self.kill_buffer();
                    self.print_screen();
                }
                '\x0C' => { // Ctrl + L -> Line mode
                    match self.exec() {
                        Some(Cmd::Quit) => {
                            print!("\x1b[2J"); // Clear screen
                            print!("\x1b[1;1H"); // Move to top
                            print!("\x1b[?25h"); // Enable cursor
                            break;
                        }
                        Some(Cmd::Save) => {
                            print!("\x1b[?25h"); // Enable cursor
                            continue;
                        }
                        Some(_) => {
                            self.print_screen();
                        }
                        None => {
                        }
                    }
                }
                '\x08' => { // Backspace
                    let y = self.offset.y + self.cursor.y;
                    if self.offset.x + self.cursor.x > 0 {
                        // Remove char from line
                        let mut row: Vec<_> = self.lines[y].chars().collect();
                        row.remove(self.offset.x + self.cursor.x - 1);
                        self.lines[y] = row.into_iter().collect();

                        if self.cursor.x == 0 {
                            self.offset.x -= cols();
                            self.cursor.x = cols() - 1;
                            self.print_screen();
                        } else {
                            self.cursor.x -= 1;
                            let line = self.render_line(y);
                            print!("\x1b[2K\x1b[1G{}", line);
                        }
                    } else {
                        // Remove newline from previous line
                        if self.cursor.y == 0 && self.offset.y == 0 {
                            print!("\x1b[?25h"); // Enable cursor
                            escape = false;
                            csi = false;
                            continue;
                        }

                        // Move cursor below the end of the previous line
                        let n = self.lines[y - 1].chars().count();
                        let w = cols();
                        self.cursor.x = n % w;
                        self.offset.x = w * (n / w);

                        // Move line to the end of the previous line
                        let line = self.lines.remove(y);
                        self.lines[y - 1].push_str(&line);

                        // Move cursor up to the previous line
                        if self.cursor.y > 0 {
                            self.cursor.y -= 1;
                        } else {
                            self.offset.y -= 1;
                        }

                        self.print_screen();
                    }
                }
                '\x7f' => {
                    // Delete
                    let y = self.offset.y + self.cursor.y;
                    let n = self.lines[y].chars().count();
                    if self.offset.x + self.cursor.x >= n {
                        // Remove newline from line
                        if y + 1 < self.lines.len() {
                            let line = self.lines.remove(y + 1);
                            self.lines[y].push_str(&line);
                            self.print_screen();
                        }
                    } else {
                        // Remove char from line
                        self.lines[y].remove(self.offset.x + self.cursor.x);
                        let line = self.render_line(y);
                        print!("\x1b[2K\x1b[1G{}", line);
                    }
                }
                c if csi => {
                    csi_params.push(c);
                    continue;
                }
                c => {
                    if let Some(s) = self.render_char(c) {
                        let y = self.offset.y + self.cursor.y;
                        let mut row: Vec<_> = self.lines[y].chars().collect();
                        for c in s.chars() {
                            row.insert(self.offset.x + self.cursor.x, c);
                            self.cursor.x += 1;
                        }
                        self.lines[y] = row.into_iter().collect();
                        if self.cursor.x >= cols() {
                            self.offset.x += cols();
                            self.cursor.x -= cols();
                            self.print_screen();
                        } else {
                            let line = self.render_line(y);
                            print!("\x1b[2K\x1b[1G{}", line);
                        }
                    }
                }
            }
            self.print_editing_status();
            self.print_highlighted();
            print!("\x1b[{};{}H", self.cursor.y + 1, self.cursor.x + 1);
            print!("\x1b[?25h"); // Enable cursor
            escape = false;
            csi = false;
        }
        Ok(())
    }

    fn handle_newline(&mut self) {
        let x = self.offset.x + self.cursor.x;
        let y = self.offset.y + self.cursor.y;

        let old_line = self.lines[y].clone();
        let mut row: Vec<char> = old_line.chars().collect();
        let new_line = row.split_off(x).into_iter().collect();
        self.lines[y] = row.into_iter().collect();
        self.lines.insert(y + 1, new_line);
        if self.cursor.y == rows() - 1 {
            self.offset.y += 1;
        } else {
            self.cursor.y += 1;
        }
        self.cursor.x = 0;
        self.offset.x = 0;
        self.print_screen();
    }

    fn handle_page_up(&mut self) {
        let scroll = rows() - 1; // Keep one line on screen
        self.offset.y -= cmp::min(scroll, self.offset.y);
        self.align_cursor();
        self.print_screen();
    }

    fn handle_page_down(&mut self) {
        let scroll = rows() - 1; // Keep one line on screen
        let n = cmp::max(self.lines.len(), 1);
        let remaining = n - self.offset.y - 1;
        self.offset.y += cmp::min(scroll, remaining);
        if self.cursor.y + scroll > remaining {
            self.cursor.y = 0;
        }
        self.align_cursor();
        self.print_screen();
    }

    fn handle_arrow_up(&mut self) {
        if self.cursor.y > 0 {
            self.cursor.y -= 1
        } else if self.offset.y > 0 {
            self.offset.y -= 1;
        }
        self.align_cursor();
        self.print_screen();
    }

    fn handle_arrow_down(&mut self) {
        let n = self.lines.len() - 1;
        let is_eof = n == (self.offset.y + self.cursor.y);
        let is_bottom = self.cursor.y == rows() - 1;
        if self.cursor.y < cmp::min(rows(), n) {
            if is_bottom || is_eof {
                if !is_eof {
                    self.offset.y += 1;
                }
            } else {
                self.cursor.y += 1;
            }
            self.align_cursor();
            self.print_screen();
        }
    }

    fn cut_line(&mut self) {
        let i = self.offset.y + self.cursor.y;
        self.clipboard = Some(self.lines.remove(i));
        if self.lines.is_empty() {
            self.lines.push(String::new());
        }
        if i == self.lines.len() {
            self.handle_arrow_up();
        } else {
            self.align_cursor();
            self.print_screen();
        }
    }

    fn copy_line(&mut self) {
        let i = self.offset.y + self.cursor.y;
        self.clipboard = Some(self.lines[i].clone());
    }

    fn paste_line(&mut self) {
        let i = self.offset.y + self.cursor.y;
        if let Some(line) = self.clipboard.clone() {
            self.lines.insert(i + 1, line);
            self.cursor.x = 0;
            self.offset.x = 0;
            self.handle_arrow_down(); // Move cursor to pasted line
        }
    }

    fn exec(&mut self) -> Option<Cmd> {
        if let Some(cmd) = prompt(&mut self.command_prompt, ":") {
            // The cursor is disabled at the beginning of the loop in the `run`
            // method to avoid seeing it jump around during screen operations.
            // The `prompt` method above re-enable the cursor so we need to
            // disable it again until the end of the loop in the `run` method.
            print!("\x1b[?25l");

            self.exec_command(&cmd)
        } else {
            None
        }
    }

    fn exec_command(&mut self, cmd: &str) -> Option<Cmd> {
        let mut res = None;
        let params: Vec<&str> = match cmd.chars().next() {
            Some('w') | Some('o') =>  {
                cmd.split(' ').collect()
            }
            _ => {
                cmd.split('/').collect()
            }
        };
        // TODO: Display line numbers on screen and support command range
        match params[0] {
            "d" if params.len() == 1 => { // Delete current line
                let y = self.offset.y + self.cursor.y;
                self.lines.remove(y);
                res = Some(Cmd::Delete);
            }
            "%d" if params.len() == 1 => { // Delete all lines
                self.lines = vec![String::new()];
                res = Some(Cmd::Delete);
            }
            "g" if params.len() == 3 => { // Global command
                let re = Regex::new(params[1]);
                if params[2] == "d" { // Delete all matching lines
                    self.lines.retain(|line| !re.is_match(line));
                    res = Some(Cmd::Delete);
                }
            }
            "o" | "open" if params.len() == 2 => { // Open
                self.open_buffer(params[1]);
                res = Some(Cmd::Open);
            }
            "q" | "quit" if params.len() == 1 => { // Quit
                res = Some(Cmd::Quit);
            }
            "s" if params.len() == 4 => { // Substitute current line
                let re = Regex::new(params[1]);
                let s = params[2];
                let y = self.offset.y + self.cursor.y;
                if params[3] == "g" { // Substitute all occurrences
                    self.lines[y] = re.replace_all(&self.lines[y], s);
                } else {
                    self.lines[y] = re.replace(&self.lines[y], s);
                }
                res = Some(Cmd::Replace);
            }
            "%s" if params.len() == 4 => { // Substitute all lines
                let re = Regex::new(params[1]);
                let s = params[2];
                let n = self.lines.len();
                for y in 0..n {
                    if params[3] == "g" { // Substitute all occurrences
                        self.lines[y] = re.replace_all(&self.lines[y], s);
                    } else {
                        self.lines[y] = re.replace(&self.lines[y], s);
                    }
                }
                res = Some(Cmd::Replace);
            }
            "w" | "write" => { // Save file
                let path = if params.len() == 2 {
                    params[1]
                } else {
                    &self.pathname.clone()
                };
                self.save(path).ok();
                res = Some(Cmd::Save);
            }
            _ => {}
        }

        if res.is_some() {
            let mut y = self.offset.y + self.cursor.y;
            let n = self.lines.len() - 1;
            if y > n {
                self.cursor.y = n % rows();
                self.offset.y = n - self.cursor.y;
                y = n;
            }
            let n = self.lines[y].len();
            if self.offset.x + self.cursor.x > n {
                self.cursor.x = n % cols();
                self.offset.x = n - self.cursor.x;
            }

            self.command_prompt.history.add(cmd);
            self.command_prompt.history.save(&self.command_history);
        }

        res
    }

    pub fn find(&mut self) {
        if let Some(query) = prompt(&mut self.search_prompt, "Find: ") {
            if !query.is_empty() {
                self.search_prompt.history.add(&query);
                self.search_query = query;
                self.find_next();
            }
        }
    }

    pub fn find_next(&mut self) {
        let dx = self.offset.x + self.cursor.x;
        let dy = self.offset.y + self.cursor.y;
        for (y, line) in self.lines.iter().enumerate() {
            let mut o = 0;
            if y < dy {
                continue;
            }
            if y == dy {
                o = cmp::min(dx + 1, line.len());
            }
            if let Some(i) = line[o..].find(&self.search_query) {
                let x = o + i;
                self.cursor.x = x % cols();
                self.cursor.y = y % rows();
                self.offset.x = x - self.cursor.x;
                self.offset.y = y - self.cursor.y;
                break;
            }
        }
    }

    pub fn open(&mut self) {
        if let Some(path) = prompt(&mut self.buffer_prompt, "Open: ") {
            if !path.is_empty() {
                self.buffer_prompt.history.add(&path);
                self.open_buffer(&path);
            }
        }
    }

    pub fn open_buffer(&mut self, path: &str) {
        // Copy current buffer
        self.buffers[self.buf] = Buffer::from(&*self);

        // Open new buffer
        let buffer = Buffer::from(path);
        self.load_buffer(&buffer);
        self.buf += 1;
        self.buffers.insert(self.buf, buffer);
    }

    pub fn next_buffer(&mut self) {
        self.buffers[self.buf] = Buffer::from(&*self);
        self.buf = (self.buf + 1) % self.buffers.len();
        self.load_buffer(&self.buffers[self.buf].clone());
    }

    pub fn previous_buffer(&mut self) {
        self.buffers[self.buf] = Buffer::from(&*self);
        if self.buffers.len() > 1 {
            if self.buf == 0 {
                self.buf = self.buffers.len();
            }
            self.buf -= 1;
        }
        self.load_buffer(&self.buffers[self.buf].clone());
    }

    pub fn kill_buffer(&mut self) {
        if self.buffers.len() > 1 {
            self.previous_buffer();
            self.buffers.remove((self.buf + 1) % self.buffers.len());
        }
    }

    pub fn load_buffer(&mut self, buffer: &Buffer) {
        self.lines = buffer.lines.clone();
        self.pathname = buffer.pathname.clone();
        self.cursor = buffer.cursor.clone();
        self.offset = buffer.offset.clone();
        self.highlighted = buffer.highlighted.clone();
    }
}

pub fn prompt(prompt: &mut Prompt, label: &str) -> Option<String> {
    let color = Style::color("black").with_background("silver");
    let reset = Style::reset();

    // Set up the bottom line for the prompt
    print!("\x1b[{};1H", rows() + 1);
    print!("{}{}", color, " ".repeat(cols()));
    print!("\x1b[{};1H", rows() + 1);
    print!("\x1b[?25h"); // Enable cursor

    let res = prompt.input(label);
    print!("{}", reset);
    res
}

pub fn rows() -> usize {
    api::console::rows() - 1 // Leave out one line for status line
}

pub fn cols() -> usize {
    api::console::cols()
}

fn truncated_line_indicator() -> String {
    let color = Style::color("black").with_background("silver");
    let reset = Style::reset();
    format!("{}>{}", color, reset)
}

fn help() {
    let csi_option = Style::color("aqua");
    let csi_title = Style::color("yellow");
    let csi_reset = Style::reset();
    println!(
        "{}Usage:{} edit {}<options> (<path>[:row[:col]])+{1}",
        csi_title, csi_reset, csi_option
    );
    println!();
    println!("{}Options:{}", csi_title, csi_reset);
    println!(
        "  {0}-c{1}, {0}--command <cmd>{1}    Execute command",
        csi_option, csi_reset
    );
}

pub fn main(args: &[&str]) -> Result<(), ExitCode> {
    let mut paths = Vec::new();
    let mut cmd = "";
    let mut i = 1;
    let n = args.len();
    while i < n {
        match args[i] {
            "-h" | "--help" => {
                help();
                return Ok(());
            }
            "-c" | "--command" => {
                if i + 1 < n {
                    i += 1;
                    cmd = args[i];
                } else {
                    error!("Missing command");
                    return Err(ExitCode::UsageError);
                }
            }
            _ => {
                if args[i].starts_with('-') {
                    error!("Invalid option '{}'", args[i]);
                    return Err(ExitCode::UsageError);
                } else {
                    paths.push(args[i])
                }
            }
        }
        i += 1;
    }
    if paths.is_empty() {
        help();
        return Err(ExitCode::UsageError);
    }

    let mut editor = Editor::new(paths[0]);
    let n = paths.len();
    for i in 1..n {
        editor.open_buffer(paths[i]);
    }

    if !cmd.is_empty() {
        for _ in 0..n {
            editor.next_buffer();
            editor.exec_command(cmd);
            for line in &editor.lines {
                println!("{}", line);
            }
        }
        return Ok(());
    }

    editor.run()
}