Skip to main content

ratatui_code_editor/
utils.rs

1pub fn get_lang(filename: &str) -> String {
2    let extension = std::path::Path::new(filename)
3        .extension()
4        .and_then(|ext| ext.to_str())
5        .unwrap_or("");
6
7    match extension {
8        "rs" => "rust",
9        "js" | "jsx" => "javascript",
10        "ts" | "tsx" => "typescript",
11        "py" => "python",
12        "go" => "go",
13        "java" => "java",
14        "cpp" => "cpp",
15        "c" => "c",
16        "cs" => "c_sharp",
17        "html" => "html",
18        "css" => "css",
19        "json" => "json",
20        "toml" => "toml",
21        "yaml" | "yml" => "yaml",
22        "sh" | "bash" => "shell",
23        "md" => "markdown",
24        _ => "unknown",
25    }
26    .to_string()
27}
28
29pub fn indent(lang: &str) -> String {
30    match lang {
31        "rust" | "python" | "php" | "toml" | "c" | "cpp" | "zig" | "kotlin" | "erlang" | "html"
32        | "sql" => "    ".to_string(),
33        "go" | "c_sharp" => "\t".to_string(),
34
35        _ => "  ".to_string(),
36    }
37}
38
39pub fn comment(lang: &str) -> &'static str {
40    match lang {
41        "python" | "shell" => "#",
42        "lua" => "--",
43        _ => "//",
44    }
45}
46
47pub fn count_indent_units(
48    line: ropey::RopeSlice<'_>,
49    indent_unit: &str,
50    max_col: Option<usize>,
51) -> usize {
52    if indent_unit.is_empty() {
53        return 0;
54    }
55
56    let mut chars = line.chars();
57    let mut count = 0;
58    let mut col = 0;
59    let indent_chars: Vec<char> = indent_unit.chars().collect();
60
61    'outer: loop {
62        for &ch in &indent_chars {
63            match chars.next() {
64                Some(c) if c == ch => col += 1,
65                _ => break 'outer,
66            }
67        }
68        count += 1;
69        if let Some(max) = max_col {
70            if col >= max {
71                break;
72            }
73        }
74    }
75
76    count
77}
78
79pub fn rgb(hex: &str) -> (u8, u8, u8) {
80    let hex = hex.trim_start_matches('#');
81    let r = u8::from_str_radix(&hex[0..2], 16).unwrap_or(0);
82    let g = u8::from_str_radix(&hex[2..4], 16).unwrap_or(0);
83    let b = u8::from_str_radix(&hex[4..6], 16).unwrap_or(0);
84    (r, g, b)
85}
86
87/// Calculate end position by walking through the text
88/// Returns (end_row, end_col) starting from (start_row, start_col)
89pub fn calculate_end_position(start_row: usize, start_col: usize, text: &str) -> (usize, usize) {
90    let mut end_row = start_row;
91    let mut end_col = start_col;
92
93    for ch in text.chars() {
94        if ch == '\n' {
95            end_row += 1;
96            end_col = 0;
97        } else {
98            end_col += 1;
99        }
100    }
101
102    (end_row, end_col)
103}