jarq 0.7.1

An interactive jq-like JSON query tool with a TUI
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
/// A text buffer with cursor position management for filter editing.
#[derive(Debug, Clone)]
pub struct TextBuffer {
    text: String,
    cursor: usize, // char position (not byte position)
}

impl TextBuffer {
    pub fn new(initial: &str) -> Self {
        let cursor = initial.chars().count();
        Self {
            text: initial.to_string(),
            cursor,
        }
    }

    pub fn text(&self) -> &str {
        &self.text
    }

    #[cfg(test)]
    pub fn cursor(&self) -> usize {
        self.cursor
    }

    #[cfg(test)]
    pub fn set_cursor(&mut self, pos: usize) {
        self.cursor = pos.min(self.len());
    }

    pub fn len(&self) -> usize {
        self.text.chars().count()
    }

    /// Insert a character at the current cursor position.
    pub fn insert(&mut self, c: char) {
        let byte_pos = self.cursor_byte_pos();
        self.text.insert(byte_pos, c);
        self.cursor += 1;
    }

    /// Delete the character before the cursor. Returns true if a character was deleted.
    pub fn backspace(&mut self) -> bool {
        if self.cursor > 0 {
            self.cursor -= 1;
            let byte_pos = self.cursor_byte_pos();
            self.text.remove(byte_pos);
            true
        } else {
            false
        }
    }

    /// Delete the character at the cursor. Returns true if a character was deleted.
    pub fn delete(&mut self) -> bool {
        if self.cursor < self.len() {
            let byte_pos = self.cursor_byte_pos();
            self.text.remove(byte_pos);
            true
        } else {
            false
        }
    }

    /// Move cursor one character left.
    pub fn move_left(&mut self) {
        self.cursor = self.cursor.saturating_sub(1);
    }

    /// Move cursor one character right.
    pub fn move_right(&mut self) {
        self.cursor = (self.cursor + 1).min(self.len());
    }

    /// Move cursor to start of text.
    pub fn move_to_start(&mut self) {
        self.cursor = 0;
    }

    /// Move cursor to end of text.
    pub fn move_to_end(&mut self) {
        self.cursor = self.len();
    }

    /// Convert char position to byte index in the underlying string.
    pub fn cursor_byte_pos(&self) -> usize {
        self.char_to_byte_index(self.cursor)
    }

    fn char_to_byte_index(&self, char_index: usize) -> usize {
        self.text
            .char_indices()
            .nth(char_index)
            .map(|(i, _)| i)
            .unwrap_or(self.text.len())
    }

    /// Delete the word before the cursor (Ctrl+W behavior).
    /// Treats `.` and spaces as word boundaries.
    pub fn delete_word_back(&mut self) -> bool {
        if self.cursor == 0 {
            return false;
        }

        let chars: Vec<char> = self.text.chars().collect();
        let mut new_cursor = self.cursor;

        // Skip trailing whitespace/dots
        while new_cursor > 0 && (chars[new_cursor - 1] == '.' || chars[new_cursor - 1] == ' ') {
            new_cursor -= 1;
        }

        // Delete back to previous dot, space, or start
        while new_cursor > 0 && chars[new_cursor - 1] != '.' && chars[new_cursor - 1] != ' ' {
            new_cursor -= 1;
        }

        if new_cursor < self.cursor {
            let start_byte = self.char_to_byte_index(new_cursor);
            let end_byte = self.char_to_byte_index(self.cursor);
            self.text.replace_range(start_byte..end_byte, "");
            self.cursor = new_cursor;
            true
        } else {
            false
        }
    }

    /// Get valid cursor positions for word-based navigation.
    /// Positions are after `.`, after `]`, or after identifiers.
    pub fn navigation_positions(&self) -> Vec<usize> {
        Self::compute_navigation_positions(&self.text)
    }

    fn compute_navigation_positions(filter_text: &str) -> Vec<usize> {
        let mut positions = vec![0];
        let mut in_string = false;
        let mut prev_char = ' ';
        let chars: Vec<char> = filter_text.chars().collect();
        let len = chars.len();

        for (i, &c) in chars.iter().enumerate() {
            if c == '"' && prev_char != '\\' {
                in_string = !in_string;
            }

            if !in_string {
                // After ']' (end of bracket expression)
                if prev_char == ']' && !positions.contains(&i) {
                    positions.push(i);
                }
                // At '|' (before pipe)
                if c == '|' && !positions.contains(&i) {
                    positions.push(i);
                }
                // After '|' and whitespace (start of next segment)
                if (prev_char == '|' || (prev_char == ' ' && i > 1 && chars[i - 2] == '|'))
                    && c != ' '
                    && !positions.contains(&i)
                {
                    positions.push(i);
                }
                // After identifier following '.'
                if i > 0 && !c.is_alphanumeric() && c != '_' {
                    // Check if previous chars were an identifier after '.'
                    let mut j = i;
                    while j > 0 && (chars[j - 1].is_alphanumeric() || chars[j - 1] == '_') {
                        j -= 1;
                    }
                    if j > 0 && chars[j - 1] == '.' && j < i && !positions.contains(&i) {
                        positions.push(i);
                    }
                }
            }
            prev_char = c;
        }

        // Add end position based on what the filter ends with
        if len > 0 && !positions.contains(&len) {
            let last = chars.last().copied().unwrap_or(' ');
            // Identity (just "."), ends with ], or ends with identifier
            if (len == 1 && last == '.') || last == ']' || last.is_alphanumeric() || last == '_' {
                positions.push(len);
            }
        }

        // Also add position 1 if filter starts with '.' and len > 1 (after initial dot)
        if len > 1 && filter_text.starts_with('.') && !positions.contains(&1) {
            positions.push(1);
        }

        positions.sort();
        positions.dedup();
        positions
    }

    /// Jump cursor to the previous word boundary.
    pub fn jump_word_back(&mut self) {
        if self.cursor == 0 {
            return;
        }

        let positions = self.navigation_positions();

        // Find largest position less than current cursor
        let mut target = 0;
        for &pos in &positions {
            if pos < self.cursor {
                target = pos;
            }
        }

        self.cursor = target;
    }

    /// Jump cursor to the next word boundary.
    pub fn jump_word_forward(&mut self) {
        let len = self.len();
        if self.cursor >= len {
            return;
        }

        let positions = self.navigation_positions();

        // Find smallest position greater than current cursor
        for &pos in &positions {
            if pos > self.cursor {
                self.cursor = pos;
                return;
            }
        }

        self.cursor = len;
    }
}

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

    #[test]
    fn test_new() {
        let buf = TextBuffer::new("hello");
        assert_eq!(buf.text(), "hello");
        assert_eq!(buf.cursor(), 5);
        assert_eq!(buf.len(), 5);
    }

    #[test]
    fn test_insert() {
        let mut buf = TextBuffer::new(".");
        buf.insert('f');
        assert_eq!(buf.text(), ".f");
        buf.insert('o');
        buf.insert('o');
        assert_eq!(buf.text(), ".foo");
        assert_eq!(buf.cursor(), 4);
    }

    #[test]
    fn test_backspace() {
        let mut buf = TextBuffer::new(".foo");
        assert!(buf.backspace());
        assert_eq!(buf.text(), ".fo");
        assert_eq!(buf.cursor(), 3);
    }

    #[test]
    fn test_backspace_at_start() {
        let mut buf = TextBuffer::new(".");
        buf.set_cursor(0);
        assert!(!buf.backspace());
        assert_eq!(buf.text(), ".");
    }

    #[test]
    fn test_delete() {
        let mut buf = TextBuffer::new(".foo");
        buf.set_cursor(1);
        assert!(buf.delete());
        assert_eq!(buf.text(), ".oo");
        assert_eq!(buf.cursor(), 1);
    }

    #[test]
    fn test_delete_at_end() {
        let mut buf = TextBuffer::new(".foo");
        assert!(!buf.delete());
        assert_eq!(buf.text(), ".foo");
    }

    #[test]
    fn test_move_left_right() {
        let mut buf = TextBuffer::new(".foo");
        assert_eq!(buf.cursor(), 4);
        buf.move_left();
        assert_eq!(buf.cursor(), 3);
        buf.move_right();
        assert_eq!(buf.cursor(), 4);
        buf.move_right(); // Should not go past end
        assert_eq!(buf.cursor(), 4);
    }

    #[test]
    fn test_move_to_start_end() {
        let mut buf = TextBuffer::new(".foo");
        buf.move_to_start();
        assert_eq!(buf.cursor(), 0);
        buf.move_to_end();
        assert_eq!(buf.cursor(), 4);
    }

    #[test]
    fn test_delete_word_back() {
        let mut buf = TextBuffer::new(".foo.bar");
        assert!(buf.delete_word_back());
        assert_eq!(buf.text(), ".foo.");
        assert_eq!(buf.cursor(), 5);
    }

    #[test]
    fn test_delete_word_back_at_start() {
        let mut buf = TextBuffer::new(".");
        buf.set_cursor(0);
        assert!(!buf.delete_word_back());
        assert_eq!(buf.text(), ".");
    }

    #[test]
    fn test_navigation_positions_identity() {
        let buf = TextBuffer::new(".");
        assert_eq!(buf.navigation_positions(), vec![0, 1]);
    }

    #[test]
    fn test_navigation_positions_field() {
        let buf = TextBuffer::new(".foo");
        assert_eq!(buf.navigation_positions(), vec![0, 1, 4]);
    }

    #[test]
    fn test_navigation_positions_iterate() {
        let buf = TextBuffer::new(".[]");
        assert_eq!(buf.navigation_positions(), vec![0, 1, 3]);
    }

    #[test]
    fn test_navigation_positions_multiple_iterate() {
        let buf = TextBuffer::new(".[][][]");
        assert_eq!(buf.navigation_positions(), vec![0, 1, 3, 5, 7]);
    }

    #[test]
    fn test_navigation_positions_index() {
        let buf = TextBuffer::new(".[0]");
        assert_eq!(buf.navigation_positions(), vec![0, 1, 4]);
    }

    #[test]
    fn test_navigation_positions_field_chain() {
        let buf = TextBuffer::new(".foo.bar");
        assert_eq!(buf.navigation_positions(), vec![0, 1, 4, 8]);
    }

    #[test]
    fn test_navigation_positions_mixed() {
        let buf = TextBuffer::new(".foo[0].bar");
        assert_eq!(buf.navigation_positions(), vec![0, 1, 4, 7, 11]);
    }

    #[test]
    fn test_navigation_positions_quoted_field() {
        let buf = TextBuffer::new(".[\"foo\"]");
        assert_eq!(buf.navigation_positions(), vec![0, 1, 8]);
    }

    #[test]
    fn test_jump_word_back() {
        let mut buf = TextBuffer::new(".foo.bar");
        buf.jump_word_back();
        assert_eq!(buf.cursor(), 4);
        buf.jump_word_back();
        assert_eq!(buf.cursor(), 1);
        buf.jump_word_back();
        assert_eq!(buf.cursor(), 0);
    }

    #[test]
    fn test_jump_word_forward() {
        let mut buf = TextBuffer::new(".foo.bar");
        buf.set_cursor(0);
        buf.jump_word_forward();
        assert_eq!(buf.cursor(), 1);
        buf.jump_word_forward();
        assert_eq!(buf.cursor(), 4);
        buf.jump_word_forward();
        assert_eq!(buf.cursor(), 8);
    }

    #[test]
    fn test_unicode_handling() {
        let mut buf = TextBuffer::new(".héllo");
        assert_eq!(buf.len(), 6);
        assert_eq!(buf.cursor(), 6);
        buf.move_left();
        assert_eq!(buf.cursor(), 5);
        buf.insert('!');
        assert_eq!(buf.text(), ".héll!o");
    }

    #[test]
    fn test_navigation_positions_with_pipes() {
        // ". | sort | reverse"
        // 0  12 4    9 11
        let buf = TextBuffer::new(". | sort | reverse");
        let positions = buf.navigation_positions();
        assert!(positions.contains(&0)); // start
        assert!(positions.contains(&1)); // after .
        assert!(positions.contains(&2)); // at first |
        assert!(positions.contains(&4)); // start of sort
        assert!(positions.contains(&9)); // at second |
        assert!(positions.contains(&11)); // start of reverse
        assert!(positions.contains(&18)); // end
    }

    #[test]
    fn test_jump_word_back_with_pipes() {
        let mut buf = TextBuffer::new(". | sort | reverse");
        // cursor at end (18)
        buf.jump_word_back();
        assert_eq!(buf.cursor(), 11); // start of reverse
        buf.jump_word_back();
        assert_eq!(buf.cursor(), 9); // at second |
        buf.jump_word_back();
        assert_eq!(buf.cursor(), 4); // start of sort
        buf.jump_word_back();
        assert_eq!(buf.cursor(), 2); // at first |
        buf.jump_word_back();
        assert_eq!(buf.cursor(), 1); // after .
        buf.jump_word_back();
        assert_eq!(buf.cursor(), 0); // start
    }
}