excel-cli 0.4.2

A lightweight terminal-based Excel viewer with Vim-like navigation for viewing, editing, and exporting Excel data to JSON format.
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
use std::path::Path;

use crate::app::AppState;
use crate::json_export::{export_all_sheets_json, export_json, HeaderDirection};
use crate::utils::col_name_to_index;

impl AppState<'_> {
    pub fn execute_command(&mut self) {
        let command = self.input_buffer.clone();
        self.input_mode = crate::app::InputMode::Normal;
        self.input_buffer = String::new();

        if command.is_empty() {
            return;
        }

        // Handle cell navigation (e.g., :A1, :B10)
        if let Some(cell_ref) = parse_cell_reference(&command) {
            self.jump_to_cell(cell_ref);
            return;
        }

        // Handle commands
        match command.as_str() {
            "w" => {
                if let Err(e) = self.save() {
                    self.add_notification(format!("Save failed: {e}"));
                }
            }
            "wq" | "x" => self.save_and_exit(),
            "q" => {
                if self.workbook.is_modified() {
                    self.add_notification(
                        "File has unsaved changes. Use :q! to force quit or :wq to save and quit."
                            .to_string(),
                    );
                } else {
                    self.should_quit = true;
                }
            }
            "q!" => self.exit_without_saving(),
            "y" => self.copy_cell(),
            "d" => {
                if let Err(e) = self.cut_cell() {
                    self.add_notification(format!("Cut failed: {e}"));
                }
            }
            "put" | "pu" => {
                if let Err(e) = self.paste_cell() {
                    self.add_notification(format!("Paste failed: {e}"));
                }
            }
            "nohlsearch" | "noh" => self.disable_search_highlight(),
            "help" => self.show_help(),
            "delsheet" => self.delete_current_sheet(),
            "addsheet" => self.add_notification("Usage: :addsheet <name>".to_string()),
            _ => {
                // Handle commands with parameters
                if command.starts_with("cw ") {
                    self.handle_column_width_command(&command);
                } else if command.starts_with("ej") {
                    self.handle_json_export_command(&command);
                } else if let Some(sheet_name) = command.strip_prefix("addsheet ") {
                    self.create_sheet(sheet_name.trim());
                } else if command.starts_with("sheet ") {
                    let sheet_name = command.strip_prefix("sheet ").unwrap().trim();
                    self.switch_to_sheet(sheet_name);
                } else if command.starts_with("dr") {
                    self.handle_delete_row_command(&command);
                } else if command.starts_with("dc") {
                    self.handle_delete_column_command(&command);
                } else {
                    self.add_notification(format!("Unknown command: {}", command));
                }
            }
        }
    }

    fn handle_column_width_command(&mut self, cmd: &str) {
        let parts: Vec<&str> = cmd.split_whitespace().collect();

        if parts.len() < 2 {
            self.add_notification("Usage: :cw [fit|min|number] [all]".to_string());
            return;
        }

        let action = parts[1];
        let apply_to_all = parts.len() > 2 && parts[2] == "all";

        match action {
            "fit" => {
                if apply_to_all {
                    self.auto_adjust_column_width(None);
                } else {
                    self.auto_adjust_column_width(Some(self.selected_cell.1));
                }
            }
            "min" => {
                if apply_to_all {
                    // Set all columns to minimum width
                    let sheet = self.workbook.get_current_sheet();
                    for col in 1..=sheet.max_cols {
                        self.column_widths[col] = 5; // Minimum width
                    }
                    self.add_notification("All columns set to minimum width".to_string());
                } else {
                    // Set current column to minimum width
                    let col = self.selected_cell.1;
                    self.column_widths[col] = 5; // Minimum width
                    self.add_notification(format!("Column {} set to minimum width", col));
                }
            }
            _ => {
                // Try to parse as a number
                if let Ok(width) = action.parse::<usize>() {
                    let col = self.selected_cell.1;
                    self.column_widths[col] = width.clamp(5, 50); // Clamp between 5 and 50
                    self.add_notification(format!("Column {} width set to {}", col, width));
                } else {
                    self.add_notification(format!("Invalid column width: {}", action));
                }
            }
        }
    }

    fn handle_delete_row_command(&mut self, cmd: &str) {
        let parts: Vec<&str> = cmd.split_whitespace().collect();

        if parts.len() == 1 {
            // Delete current row
            if let Err(e) = self.delete_current_row() {
                self.add_notification(format!("Failed to delete row: {e}"));
            }
            return;
        }

        if parts.len() == 2 {
            // Delete specific row
            if let Ok(row) = parts[1].parse::<usize>() {
                if let Err(e) = self.delete_row(row) {
                    self.add_notification(format!("Failed to delete row {}: {}", row, e));
                }
            } else {
                self.add_notification(format!("Invalid row number: {}", parts[1]));
            }
            return;
        }

        if parts.len() == 3 {
            // Delete range of rows
            if let (Ok(start_row), Ok(end_row)) =
                (parts[1].parse::<usize>(), parts[2].parse::<usize>())
            {
                if let Err(e) = self.delete_rows(start_row, end_row) {
                    self.add_notification(format!(
                        "Failed to delete rows {} to {}: {}",
                        start_row, end_row, e
                    ));
                }
            } else {
                self.add_notification("Invalid row range".to_string());
            }
            return;
        }

        self.add_notification("Usage: :dr [row] [end_row]".to_string());
    }

    fn handle_delete_column_command(&mut self, cmd: &str) {
        let parts: Vec<&str> = cmd.split_whitespace().collect();

        if parts.len() == 1 {
            // Delete current column
            if let Err(e) = self.delete_current_column() {
                self.add_notification(format!("Failed to delete column: {e}"));
            }
            return;
        }

        if parts.len() == 2 {
            // Delete specific column
            let col_str = parts[1].to_uppercase();

            // Try to parse as a column letter (A, B, C, etc.)
            if let Some(col) = col_name_to_index(&col_str) {
                if let Err(e) = self.delete_column(col) {
                    self.add_notification(format!("Failed to delete column {}: {}", col_str, e));
                }
                return;
            }

            // Try to parse as a column number
            if let Ok(col) = col_str.parse::<usize>() {
                if let Err(e) = self.delete_column(col) {
                    self.add_notification(format!("Failed to delete column {}: {}", col, e));
                }
                return;
            }

            self.add_notification(format!("Invalid column: {}", col_str));
            return;
        }

        if parts.len() == 3 {
            // Delete range of columns
            let start_col_str = parts[1].to_uppercase();
            let end_col_str = parts[2].to_uppercase();

            let start_col =
                col_name_to_index(&start_col_str).or_else(|| start_col_str.parse::<usize>().ok());
            let end_col =
                col_name_to_index(&end_col_str).or_else(|| end_col_str.parse::<usize>().ok());

            if let (Some(start), Some(end)) = (start_col, end_col) {
                if let Err(e) = self.delete_columns(start, end) {
                    self.add_notification(format!(
                        "Failed to delete columns {} to {}: {}",
                        start_col_str, end_col_str, e
                    ));
                }
            } else {
                self.add_notification("Invalid column range".to_string());
            }
            return;
        }

        self.add_notification("Usage: :dc [col] [end_col]".to_string());
    }

    fn handle_json_export_command(&mut self, cmd: &str) {
        // Check if this is an export all command
        let export_all = cmd.starts_with("eja ") || cmd == "eja";

        // Parse command
        let parts: Vec<&str> = if cmd.starts_with("ej ") {
            cmd.strip_prefix("ej ")
                .unwrap()
                .split_whitespace()
                .collect()
        } else if cmd == "ej" {
            // No arguments provided, use default values
            vec!["h", "1"] // Default to horizontal headers with 1 header row
        } else if cmd.starts_with("eja ") {
            cmd.strip_prefix("eja ")
                .unwrap()
                .split_whitespace()
                .collect()
        } else if cmd == "eja" {
            // No arguments provided, use default values
            vec!["h", "1"] // Default to horizontal headers with 1 header row
        } else {
            self.add_notification("Invalid JSON export command".to_string());
            return;
        };

        // Check if we have enough arguments for direction and header count
        if parts.len() < 2 {
            if export_all {
                self.add_notification("Usage: :eja [h|v] [rows]".to_string());
            } else {
                self.add_notification("Usage: :ej [h|v] [rows]".to_string());
            }
            return;
        }

        let direction_str = parts[0];
        let header_count_str = parts[1];

        let direction = match direction_str.parse::<HeaderDirection>() {
            Ok(dir) => dir,
            Err(_) => {
                self.add_notification(format!(
                    "Invalid header direction: {}. Use 'h' or 'v'",
                    direction_str
                ));
                return;
            }
        };

        let header_count = match header_count_str.parse::<usize>() {
            Ok(count) => count,
            Err(_) => {
                self.add_notification(format!("Invalid header count: {}", header_count_str));
                return;
            }
        };

        let sheet_name = self.workbook.get_current_sheet_name();

        let file_path = self.workbook.get_file_path().to_string();
        let original_file = Path::new(&file_path);
        let file_stem = original_file
            .file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or("export");

        let parent_dir = original_file.parent().unwrap_or_else(|| Path::new(""));

        let now = chrono::Local::now();
        let timestamp = now.format("%Y%m%d_%H%M%S").to_string();

        let filename = if export_all {
            format!("{}_all_sheets_{}.json", file_stem, timestamp)
        } else {
            format!("{}_sheet_{}_{}.json", file_stem, sheet_name, timestamp)
        };

        // Create the full path in the same directory as the original Excel file
        let new_filepath = parent_dir.join(filename);

        // Export to JSON
        let result = if export_all {
            export_all_sheets_json(&self.workbook, direction, header_count, &new_filepath)
        } else {
            export_json(
                self.workbook.get_current_sheet(),
                direction,
                header_count,
                &new_filepath,
            )
        };

        match result {
            Ok(_) => {
                self.add_notification(format!("Exported to {}", new_filepath.display()));
            }
            Err(e) => {
                self.add_notification(format!("Export failed: {e}"));
            }
        }
    }

    fn jump_to_cell(&mut self, cell_ref: (usize, usize)) {
        let (row, col) = cell_ref; // Fixed: cell_ref is already (row, col)

        let sheet = self.workbook.get_current_sheet();

        // Validate row and column
        if row > sheet.max_rows || col > sheet.max_cols {
            self.add_notification(format!(
                "Cell reference out of range: {}{}",
                crate::utils::index_to_col_name(col),
                row
            ));
            return;
        }

        self.selected_cell = (row, col);
        // Handle scrolling
        if self.selected_cell.0 < self.start_row {
            self.start_row = self.selected_cell.0;
        } else if self.selected_cell.0 >= self.start_row + self.visible_rows {
            self.start_row = self.selected_cell.0 - self.visible_rows + 1;
        }

        self.ensure_column_visible(self.selected_cell.1);

        self.add_notification(format!(
            "Jumped to cell {}{}",
            crate::utils::index_to_col_name(col),
            row
        ));
    }
}

// Parse a cell reference like "A1", "B10", etc.
fn parse_cell_reference(input: &str) -> Option<(usize, usize)> {
    // Cell references should have at least 2 characters (e.g., A1)
    if input.chars().count() < 2 {
        return None;
    }

    // Find the first digit to separate column and row parts
    let col_end = input
        .char_indices()
        .find(|(_, c)| c.is_ascii_digit())
        .map(|(index, _)| index)?;

    if col_end == 0 {
        return None; // No digits found
    }

    let (col_part, row_part) = input.split_at(col_end);

    // Convert column letters to index
    let col = col_name_to_index(&col_part.to_uppercase())?;

    // Parse row number
    let row = row_part.parse::<usize>().ok()?;

    Some((row, col))
}

#[cfg(test)]
mod tests {
    use super::parse_cell_reference;

    #[test]
    fn parses_valid_cell_references() {
        assert_eq!(parse_cell_reference("A1"), Some((1, 1)));
        assert_eq!(parse_cell_reference("BC12"), Some((12, 55)));
    }

    #[test]
    fn ignores_commands_with_non_ascii_arguments() {
        assert_eq!(parse_cell_reference("addsheet 测试1"), None);
        assert_eq!(parse_cell_reference("测试1"), None);
    }
}