Parse converts a key specification like "Ctrl+A" or "F5" to tcell values. It returns the key, optional rune, and modifier mask.
(spec string)
| 26 | // Parse converts a key specification like "Ctrl+A" or "F5" to tcell values. |
| 27 | // It returns the key, optional rune, and modifier mask. |
| 28 | func Parse(spec string) (tcell.Key, rune, tcell.ModMask, error) { |
| 29 | if spec == "" { |
| 30 | return 0, 0, 0, fmt.Errorf("empty key specification") |
| 31 | } |
| 32 | |
| 33 | parts := strings.Split(spec, "+") |
| 34 | base := strings.TrimSpace(parts[len(parts)-1]) |
| 35 | |
| 36 | var mods tcell.ModMask |
| 37 | |
| 38 | for _, p := range parts[:len(parts)-1] { |
| 39 | switch strings.ToLower(strings.TrimSpace(p)) { |
| 40 | case "ctrl", "control": |
| 41 | mods |= tcell.ModCtrl |
| 42 | case "alt", "opt": |
| 43 | mods |= tcell.ModAlt |
| 44 | case "shift": |
| 45 | mods |= tcell.ModShift |
| 46 | case "meta", "win", "windows", "cmd", "super": |
| 47 | mods |= tcell.ModMeta |
| 48 | case "": |
| 49 | // ignore empty segment like "Ctrl+" |
| 50 | default: |
| 51 | return 0, 0, 0, fmt.Errorf("unknown modifier %q", p) |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | b := strings.ToUpper(base) |
| 56 | switch b { |
| 57 | case "BACKTAB": |
| 58 | // Backtab already implies Shift; don't double-count it. |
| 59 | mods &^= tcell.ModShift |
| 60 | return tcell.KeyBacktab, 0, mods, nil |
| 61 | case "TAB": |
| 62 | // In many UIs (including tview forms), Shift+Tab is treated as "back-tab". |
| 63 | // Represent that as KeyBacktab rather than KeyTab+Shift. |
| 64 | if mods == tcell.ModShift { |
| 65 | return tcell.KeyBacktab, 0, tcell.ModNone, nil |
| 66 | } |
| 67 | // "Ctrl+Tab" is not a standard combination that all terminals support |
| 68 | // sending, but we can support the string configuration. |
| 69 | return tcell.KeyTab, 0, mods, nil |
| 70 | case "ENTER", "RETURN": |
| 71 | return tcell.KeyEnter, 0, mods, nil |
| 72 | case "ESC", "ESCAPE": |
| 73 | return tcell.KeyEsc, 0, mods, nil |
| 74 | case "UP": |
| 75 | return tcell.KeyUp, 0, mods, nil |
| 76 | case "DOWN": |
| 77 | return tcell.KeyDown, 0, mods, nil |
| 78 | case "LEFT": |
| 79 | return tcell.KeyLeft, 0, mods, nil |
| 80 | case "RIGHT": |
| 81 | return tcell.KeyRight, 0, mods, nil |
| 82 | } |
| 83 | |
| 84 | if strings.HasPrefix(b, "F") { |
| 85 | if n, err := strconv.Atoi(strings.TrimPrefix(b, "F")); err == nil { |
no outgoing calls