excel-cli 1.3.2

Excel CLI for AI, scripting, and terminal users. Headless JSON API for automation, plus a Vim-like TUI for interactive browsing and editing.
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
use crate::actions::{
    ActionCommand, ColumnAction, MultiColumnAction, MultiRowAction, RowAction, SheetAction,
    SheetOperation,
};
use crate::app::AppState;
use crate::utils::index_to_col_name;
use anyhow::Result;

impl AppState<'_> {
    pub fn next_sheet(&mut self) -> Result<()> {
        let sheet_count = self.workbook.get_sheet_names().len();
        let current_index = self.workbook.get_current_sheet_index();

        if current_index >= sheet_count - 1 {
            self.add_notification("Already at the last sheet".to_string());
            return Ok(());
        }

        self.switch_sheet_by_index(current_index + 1)
    }

    pub fn prev_sheet(&mut self) -> Result<()> {
        let current_index = self.workbook.get_current_sheet_index();

        if current_index == 0 {
            self.add_notification("Already at the first sheet".to_string());
            return Ok(());
        }

        self.switch_sheet_by_index(current_index - 1)
    }

    pub fn switch_sheet_by_index(&mut self, index: usize) -> Result<()> {
        let current_sheet_name = self.workbook.get_current_sheet_name();

        // Save current column widths if they've changed
        if !self.sheet_column_widths.contains_key(&current_sheet_name)
            || self.sheet_column_widths[&current_sheet_name] != self.column_widths
        {
            self.sheet_column_widths
                .insert(current_sheet_name.clone(), self.column_widths.clone());
        }

        // Save current cell position and view position
        let current_position = crate::app::CellPosition {
            selected: self.selected_cell,
            view: (self.start_row, self.start_col),
        };
        self.sheet_cell_positions
            .insert(current_sheet_name, current_position);

        self.workbook.switch_sheet(index)?;

        let new_sheet_name = self.workbook.get_current_sheet_name();

        // Restore column widths for the new sheet
        if let Some(saved_widths) = self.sheet_column_widths.get(&new_sheet_name) {
            if &self.column_widths != saved_widths {
                self.column_widths = saved_widths.clone();
            }
        } else {
            let max_cols = self.workbook.get_current_sheet().max_cols;
            let default_width = 15;
            self.column_widths = vec![default_width; max_cols + 1];

            self.sheet_column_widths
                .insert(new_sheet_name.clone(), self.column_widths.clone());
        }

        // Restore cell position and view position for the new sheet
        if let Some(saved_position) = self.sheet_cell_positions.get(&new_sheet_name) {
            self.selected_cell = Self::clamp_cell_to_excel_bounds(saved_position.selected);
            self.start_row = saved_position.view.0;
            self.start_col = saved_position.view.1;
            self.clamp_selected_cell_to_excel_bounds();

            // Make sure the view position is valid relative to the selected cell
            self.handle_scrolling();
        } else {
            // If no saved position exists, use default position
            self.selected_cell = (1, 1);
            self.start_row = 1;
            self.start_col = 1;
        }

        // Clear search results as they're specific to the previous sheet
        if !self.search_results.is_empty() {
            self.search_results.clear();
            self.current_search_idx = None;
        }

        self.update_row_number_width();

        // Check if the new sheet is loaded when using lazy loading
        let is_lazy_loading = self.workbook.is_lazy_loading();
        let is_sheet_loaded = self.workbook.is_sheet_loaded(index);

        if is_lazy_loading && !is_sheet_loaded {
            // If the sheet is not loaded, switch to LazyLoading mode
            self.input_mode = crate::app::InputMode::LazyLoading;
            self.add_notification(format!(
                "Switched to sheet: {new_sheet_name} (press Enter to load)"
            ));
        } else {
            self.add_notification(format!("Switched to sheet: {new_sheet_name}"));
        }

        Ok(())
    }

    pub fn switch_to_sheet(&mut self, name_or_index: &str) {
        // Get all sheet names
        let sheet_names = self.workbook.get_sheet_names();

        // Try to parse as index first
        if let Ok(index) = name_or_index.parse::<usize>() {
            // Convert to 0-based index
            let zero_based_index = index.saturating_sub(1);

            if zero_based_index < sheet_names.len() {
                match self.switch_sheet_by_index(zero_based_index) {
                    Ok(()) => return,
                    Err(e) => {
                        self.add_notification(format!("Failed to switch to sheet {index}: {e}"));
                        return;
                    }
                }
            }
        }

        // Try to find by name
        for (i, name) in sheet_names.iter().enumerate() {
            if name.eq_ignore_ascii_case(name_or_index) {
                match self.switch_sheet_by_index(i) {
                    Ok(()) => return,
                    Err(e) => {
                        self.add_notification(format!(
                            "Failed to switch to sheet '{name_or_index}': {e}"
                        ));
                        return;
                    }
                }
            }
        }

        // If we get here, no matching sheet was found
        self.add_notification(format!("Sheet '{name_or_index}' not found"));
    }

    pub fn create_sheet(&mut self, name: &str) {
        let insert_index = self.workbook.get_current_sheet_index() + 1;

        match self.workbook.add_sheet(name, insert_index) {
            Ok(sheet_name) => {
                let default_width = 15;
                let max_cols = self
                    .workbook
                    .get_sheet_by_index(insert_index)
                    .map(|sheet| sheet.max_cols)
                    .unwrap_or(1);

                self.sheet_column_widths
                    .insert(sheet_name.clone(), vec![default_width; max_cols + 1]);
                self.sheet_cell_positions.insert(
                    sheet_name.clone(),
                    crate::app::CellPosition {
                        selected: (1, 1),
                        view: (1, 1),
                    },
                );

                if let Err(e) = self.switch_sheet_by_index(insert_index) {
                    self.sheet_column_widths.remove(&sheet_name);
                    self.sheet_cell_positions.remove(&sheet_name);
                    let _ = self.workbook.delete_sheet_at_index(insert_index);
                    self.add_notification(format!("Failed to switch to new sheet: {e}"));
                    return;
                }

                self.notification_messages.pop();

                let sheet_action = SheetAction {
                    sheet_index: insert_index,
                    sheet_name: sheet_name.clone(),
                    sheet_data: self.workbook.get_current_sheet().clone(),
                    column_widths: self.column_widths.clone(),
                    operation: SheetOperation::Create,
                };

                self.undo_history.push(ActionCommand::Sheet(sheet_action));
                self.input_mode = crate::app::InputMode::Normal;
                self.add_notification(format!("Created sheet: {sheet_name}"));
            }
            Err(e) => {
                self.add_notification(format!("Failed to add sheet: {e}"));
            }
        }
    }

    pub fn delete_current_sheet(&mut self) {
        let current_sheet_name = self.workbook.get_current_sheet_name();
        let sheet_index = self.workbook.get_current_sheet_index();

        // Save the sheet data for undo
        let sheet_data = self.workbook.get_current_sheet().clone();
        let column_widths = self.column_widths.clone();

        match self.workbook.delete_current_sheet() {
            Ok(()) => {
                // Create the undo action
                let sheet_action = SheetAction {
                    sheet_index,
                    sheet_name: current_sheet_name.clone(),
                    sheet_data,
                    column_widths,
                    operation: SheetOperation::Delete,
                };

                self.undo_history.push(ActionCommand::Sheet(sheet_action));
                self.sheet_column_widths.remove(&current_sheet_name);
                self.sheet_cell_positions.remove(&current_sheet_name);

                let new_sheet_name = self.workbook.get_current_sheet_name();
                let new_sheet_index = self.workbook.get_current_sheet_index();
                let is_new_sheet_loaded = self.workbook.is_sheet_loaded(new_sheet_index);

                // Restore saved cell position for the new current sheet or use default
                if let Some(saved_position) = self.sheet_cell_positions.get(&new_sheet_name) {
                    self.selected_cell = Self::clamp_cell_to_excel_bounds(saved_position.selected);
                    self.start_row = saved_position.view.0;
                    self.start_col = saved_position.view.1;
                    self.clamp_selected_cell_to_excel_bounds();

                    // Make sure the view position is valid relative to the selected cell
                    self.handle_scrolling();
                } else {
                    // If no saved position exists, use default position
                    self.selected_cell = (1, 1);
                    self.start_row = 1;
                    self.start_col = 1;
                }

                if let Some(saved_widths) = self.sheet_column_widths.get(&new_sheet_name) {
                    self.column_widths = saved_widths.clone();
                } else {
                    let max_cols = self.workbook.get_current_sheet().max_cols;
                    let default_width = 15;
                    self.column_widths = vec![default_width; max_cols + 1];

                    self.sheet_column_widths
                        .insert(new_sheet_name.clone(), self.column_widths.clone());
                }

                // Clear search results as they're specific to the previous sheet
                self.search_results.clear();
                self.current_search_idx = None;
                self.update_row_number_width();

                // Check if the new current sheet is loaded when using lazy loading
                if self.workbook.is_lazy_loading() && !is_new_sheet_loaded {
                    // If the sheet is not loaded, switch to LazyLoading mode
                    self.input_mode = crate::app::InputMode::LazyLoading;
                    self.add_notification(format!(
                        "Deleted sheet: {current_sheet_name}. Switched to sheet: {new_sheet_name} (press Enter to load)"
                    ));
                } else {
                    self.add_notification(format!("Deleted sheet: {current_sheet_name}"));
                }
            }
            Err(e) => {
                self.add_notification(format!("Failed to delete sheet: {e}"));
            }
        }
    }

    pub fn delete_current_row(&mut self) -> Result<()> {
        let row = self.selected_cell.0;
        let sheet = self.workbook.get_current_sheet();

        // If row is outside the valid range, return success
        if row < 1 || row > sheet.max_rows {
            return Ok(());
        }

        // Save row data for undo
        let sheet_index = self.workbook.get_current_sheet_index();
        let sheet_name = self.workbook.get_current_sheet_name();

        // Create a copy of the row data before deletion
        let row_data = if row < sheet.data.len() {
            sheet.data[row].clone()
        } else {
            Vec::new()
        };

        // Create and add undo action
        let row_action = RowAction {
            sheet_index,
            sheet_name,
            row,
            row_data,
        };

        self.undo_history.push(ActionCommand::Row(row_action));
        self.workbook.delete_row(row)?;

        self.workbook.recalculate_max_rows();
        self.workbook.recalculate_max_cols();
        self.clamp_selected_cell_to_excel_bounds();

        self.handle_scrolling();
        self.search_results.clear();
        self.current_search_idx = None;

        self.add_notification(format!("Deleted row {row}"));
        Ok(())
    }

    pub fn delete_row(&mut self, row: usize) -> Result<()> {
        let sheet = self.workbook.get_current_sheet();

        // If row is outside the valid range, return success
        if row < 1 || row > sheet.max_rows {
            return Ok(());
        }

        // Save row data for undo
        let sheet_index = self.workbook.get_current_sheet_index();
        let sheet_name = self.workbook.get_current_sheet_name();

        // Create a copy of the row data before deletion
        let row_data = if row < sheet.data.len() {
            sheet.data[row].clone()
        } else {
            Vec::new()
        };

        // Create and add undo action
        let row_action = RowAction {
            sheet_index,
            sheet_name,
            row,
            row_data,
        };

        self.undo_history.push(ActionCommand::Row(row_action));
        self.workbook.delete_row(row)?;

        self.workbook.recalculate_max_rows();
        self.workbook.recalculate_max_cols();
        self.clamp_selected_cell_to_excel_bounds();

        self.handle_scrolling();
        self.search_results.clear();
        self.current_search_idx = None;

        self.add_notification(format!("Deleted row {row}"));
        Ok(())
    }

    pub fn delete_rows(&mut self, start_row: usize, end_row: usize) -> Result<()> {
        if start_row == end_row {
            return self.delete_row(start_row);
        }

        let sheet = self.workbook.get_current_sheet();

        // If the entire range is outside the valid range, return success
        if start_row < 1 || start_row > sheet.max_rows || start_row > end_row {
            return Ok(());
        }

        // If start_row is valid but end_row exceeds max_rows, adjust end_row to max_rows
        let effective_end_row = end_row.min(sheet.max_rows);

        // Save all row data for batch undo
        let sheet_index = self.workbook.get_current_sheet_index();
        let sheet_name = self.workbook.get_current_sheet_name();

        // Save row data in the original order from top to bottom
        let rows_to_save = effective_end_row - start_row + 1;
        let mut rows_data = Vec::with_capacity(rows_to_save);

        for row in start_row..=effective_end_row {
            if row < sheet.data.len() {
                rows_data.push(sheet.data[row].clone());
            } else {
                rows_data.push(Vec::new());
            }
        }

        // Create and add batch undo action
        let multi_row_action = MultiRowAction {
            sheet_index,
            sheet_name,
            start_row,
            end_row: effective_end_row,
            rows_data,
        };

        self.undo_history
            .push(ActionCommand::MultiRow(multi_row_action));
        self.workbook.delete_rows(start_row, effective_end_row)?;

        self.workbook.recalculate_max_rows();
        self.workbook.recalculate_max_cols();
        self.clamp_selected_cell_to_excel_bounds();

        self.handle_scrolling();
        self.search_results.clear();
        self.current_search_idx = None;

        self.add_notification(format!("Deleted rows {start_row} to {effective_end_row}"));
        Ok(())
    }

    pub fn delete_current_column(&mut self) -> Result<()> {
        let col = self.selected_cell.1;
        let sheet = self.workbook.get_current_sheet();

        // If column is outside the valid range, return success
        if col < 1 || col > sheet.max_cols {
            return Ok(());
        }

        // Save column data for undo
        let sheet_index = self.workbook.get_current_sheet_index();
        let sheet_name = self.workbook.get_current_sheet_name();

        // Extract the column data from each row
        let mut column_data = Vec::with_capacity(sheet.data.len());
        for row in &sheet.data {
            if col < row.len() {
                column_data.push(row[col].clone());
            } else {
                column_data.push(crate::excel::Cell::empty());
            }
        }

        // Save the column width
        let column_width = if col < self.column_widths.len() {
            self.column_widths[col]
        } else {
            15 // Default width
        };

        let column_action = ColumnAction {
            sheet_index,
            sheet_name,
            col,
            column_data,
            column_width,
        };

        self.undo_history.push(ActionCommand::Column(column_action));
        self.workbook.delete_column(col)?;

        self.workbook.recalculate_max_rows();
        self.workbook.recalculate_max_cols();
        let max_cols = self.workbook.get_current_sheet().max_cols;
        self.clamp_selected_cell_to_excel_bounds();

        if self.column_widths.len() > col {
            self.column_widths.remove(col);
        }

        self.adjust_column_widths(max_cols);

        self.handle_scrolling();
        self.search_results.clear();
        self.current_search_idx = None;

        let col_name = index_to_col_name(col);
        self.add_notification(format!("Deleted column {col_name}"));
        Ok(())
    }

    pub fn delete_column(&mut self, col: usize) -> Result<()> {
        let sheet = self.workbook.get_current_sheet();

        // If column is outside the valid range, return success
        if col < 1 || col > sheet.max_cols {
            return Ok(());
        }

        // Save column data for undo
        let sheet_index = self.workbook.get_current_sheet_index();
        let sheet_name = self.workbook.get_current_sheet_name();

        // Extract the column data from each row
        let mut column_data = Vec::with_capacity(sheet.data.len());
        for row in &sheet.data {
            if col < row.len() {
                column_data.push(row[col].clone());
            } else {
                column_data.push(crate::excel::Cell::empty());
            }
        }

        // Save the column width
        let column_width = if col < self.column_widths.len() {
            self.column_widths[col]
        } else {
            15 // Default width
        };

        let column_action = ColumnAction {
            sheet_index,
            sheet_name,
            col,
            column_data,
            column_width,
        };

        self.undo_history.push(ActionCommand::Column(column_action));
        self.workbook.delete_column(col)?;

        self.workbook.recalculate_max_rows();
        self.workbook.recalculate_max_cols();
        let max_cols = self.workbook.get_current_sheet().max_cols;
        self.clamp_selected_cell_to_excel_bounds();

        if self.column_widths.len() > col {
            self.column_widths.remove(col);
        }

        self.adjust_column_widths(max_cols);

        self.handle_scrolling();
        self.search_results.clear();
        self.current_search_idx = None;

        let col_name = index_to_col_name(col);
        self.add_notification(format!("Deleted column {col_name}"));
        Ok(())
    }

    pub fn delete_columns(&mut self, start_col: usize, end_col: usize) -> Result<()> {
        if start_col == end_col {
            return self.delete_column(start_col);
        }

        let sheet = self.workbook.get_current_sheet();

        // If the entire range is outside the valid range, return success
        if start_col < 1 || start_col > sheet.max_cols || start_col > end_col {
            return Ok(());
        }

        // If start_col is valid but end_col exceeds max_cols, adjust end_col to max_cols
        let effective_end_col = end_col.min(sheet.max_cols);

        // For multiple columns, save all column data for batch undo
        let sheet_index = self.workbook.get_current_sheet_index();
        let sheet_name = self.workbook.get_current_sheet_name();

        // Save column data and widths for batch undo
        let cols_to_save = effective_end_col - start_col + 1;
        let mut columns_data = Vec::with_capacity(cols_to_save);
        let mut column_widths = Vec::with_capacity(cols_to_save);

        for col in start_col..=effective_end_col {
            // Extract the column data from each row
            let mut column_data = Vec::with_capacity(sheet.data.len());
            for row in &sheet.data {
                if col < row.len() {
                    column_data.push(row[col].clone());
                } else {
                    column_data.push(crate::excel::Cell::empty());
                }
            }
            columns_data.push(column_data);

            // Save the column width
            let column_width = if col < self.column_widths.len() {
                self.column_widths[col]
            } else {
                15 // Default width
            };
            column_widths.push(column_width);
        }

        // Create and add batch undo action
        let multi_column_action = MultiColumnAction {
            sheet_index,
            sheet_name,
            start_col,
            end_col: effective_end_col,
            columns_data,
            column_widths,
        };

        self.undo_history
            .push(ActionCommand::MultiColumn(multi_column_action));
        self.workbook.delete_columns(start_col, effective_end_col)?;

        self.workbook.recalculate_max_rows();
        self.workbook.recalculate_max_cols();
        let max_cols = self.workbook.get_current_sheet().max_cols;
        self.clamp_selected_cell_to_excel_bounds();

        for col in (start_col..=effective_end_col).rev() {
            if self.column_widths.len() > col {
                self.column_widths.remove(col);
            }
        }

        self.adjust_column_widths(max_cols);

        self.handle_scrolling();
        self.search_results.clear();
        self.current_search_idx = None;

        self.add_notification(format!(
            "Deleted columns {} to {}",
            index_to_col_name(start_col),
            index_to_col_name(effective_end_col)
        ));
        Ok(())
    }

    pub fn auto_adjust_column_width(&mut self, col: Option<usize>) {
        // Get sheet information before any mutable operations
        let is_loaded = self.workbook.get_current_sheet().is_loaded;
        let max_cols = self.workbook.get_current_sheet().max_cols;
        let default_min_width = 5;

        if !is_loaded && max_cols == 0 {
            self.add_notification(
                "Cannot adjust column widths in lazy loading mode until sheet is loaded"
                    .to_string(),
            );
            return;
        }

        match col {
            // Adjust specific column
            Some(column) => {
                // Ensure column_widths is large enough
                self.ensure_column_widths();

                if column < self.column_widths.len() {
                    // Calculate and set new column width
                    let width = self.calculate_column_width(column);
                    self.column_widths[column] = width.max(default_min_width);

                    self.ensure_column_visible(column);

                    self.add_notification(format!(
                        "Column {} width adjusted",
                        index_to_col_name(column)
                    ));
                }
            }
            // Adjust all columns
            None => {
                // Ensure column_widths is large enough
                self.ensure_column_widths();

                // Only process columns if there are any
                if max_cols > 0 {
                    for col_idx in 1..=max_cols {
                        let width = self.calculate_column_width(col_idx);
                        self.column_widths[col_idx] = width.max(default_min_width);
                    }

                    let column = self.selected_cell.1;
                    self.ensure_column_visible(column);

                    self.add_notification("All column widths adjusted".to_string());
                }
            }
        }
    }

    fn calculate_column_width(&self, col: usize) -> usize {
        let sheet = self.workbook.get_current_sheet();

        // Start with minimum width and header width
        let col_name = index_to_col_name(col);
        let mut max_width = 3.max(col_name.len());

        // Calculate max width from all cells in the column
        for row in 1..=sheet.max_rows {
            if row >= sheet.data.len() || col >= sheet.data[row].len() {
                continue;
            }

            let content = &sheet.data[row][col].value;
            if content.is_empty() {
                continue;
            }

            let mut display_width = 0;

            for c in content.chars() {
                if c.is_ascii() {
                    display_width += 1;
                } else {
                    display_width += 2;
                }
            }

            max_width = max_width.max(display_width);
        }
        max_width
    }

    pub fn get_column_width(&self, col: usize) -> usize {
        if col < self.column_widths.len() {
            self.column_widths[col]
        } else {
            15 // Default width
        }
    }

    pub fn ensure_column_widths(&mut self) {
        let sheet = self.workbook.get_current_sheet();
        self.adjust_column_widths(sheet.max_cols);
    }

    fn adjust_column_widths(&mut self, max_cols: usize) {
        match self.column_widths.len().cmp(&(max_cols + 1)) {
            std::cmp::Ordering::Greater => {
                self.column_widths.truncate(max_cols + 1);
            }
            std::cmp::Ordering::Less => {
                let additional = max_cols + 1 - self.column_widths.len();
                self.column_widths.extend(vec![15; additional]);
            }
            std::cmp::Ordering::Equal => {
                // Column widths are already correct, do nothing
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::app::AppState;
    use crate::excel::{Sheet, Workbook};
    use std::path::PathBuf;

    #[test]
    fn create_sheet_can_be_undone_and_redone() {
        let workbook = Workbook::from_sheets_for_test(vec![Sheet::blank("Sheet1".to_string())]);
        let mut app = AppState::new(workbook, PathBuf::from("test.xlsx")).unwrap();

        app.create_sheet("Report");
        assert_eq!(app.workbook.get_sheet_names(), vec!["Sheet1", "Report"]);
        assert_eq!(app.workbook.get_current_sheet_name(), "Report");
        assert!(app.workbook.is_modified());

        app.undo().unwrap();
        assert_eq!(app.workbook.get_sheet_names(), vec!["Sheet1"]);
        assert_eq!(app.workbook.get_current_sheet_name(), "Sheet1");
        assert!(!app.workbook.is_modified());

        app.redo().unwrap();
        assert_eq!(app.workbook.get_sheet_names(), vec!["Sheet1", "Report"]);
        assert_eq!(app.workbook.get_current_sheet_name(), "Report");
        assert!(app.workbook.is_modified());
    }
}