-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathqsnotes.py
More file actions
929 lines (794 loc) · 35.1 KB
/
Copy pathqsnotes.py
File metadata and controls
929 lines (794 loc) · 35.1 KB
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
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
#!/usr/bin/env python3
"""
QSNotes - Quick & Simple Notes TUI
https://github.com/EERomeo/qsnotes
"""
__version__ = "1.1.0"
import json
import curses
import sys
import os
import time
import argparse
from datetime import datetime
from pathlib import Path
from typing import List, Dict, Any, Optional
class Note:
_next_id = 1
def __init__(self, title: str = "", body: str = "", note_id: Optional[int] = None):
if note_id is None:
self.id = Note._next_id
Note._next_id += 1
else:
self.id = note_id
if note_id >= Note._next_id:
Note._next_id = note_id + 1
self.title = title
self.body = body
self.created_at = datetime.now().isoformat()
self.updated_at = self.created_at
def to_dict(self) -> Dict[str, Any]:
return {
"id": self.id,
"title": self.title,
"body": self.body,
"created_at": self.created_at,
"updated_at": self.updated_at
}
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "Note":
note = cls(data["title"], data["body"], data["id"])
note.created_at = data.get("created_at", note.created_at)
note.updated_at = data.get("updated_at", note.updated_at)
return note
def update(self, title: str, body: str):
self.title = title
self.body = body
self.updated_at = datetime.now().isoformat()
@classmethod
def reset_id_counter(cls, notes: List["Note"]):
if notes:
max_id = max(note.id for note in notes)
cls._next_id = max_id + 1
else:
cls._next_id = 1
class NoteManager:
def __init__(self, file_path: Optional[str] = None):
if file_path is None:
script_dir = Path(__file__).parent.absolute()
self.file_path = script_dir / "notes.json"
else:
self.file_path = Path(file_path)
self.notes: List[Note] = []
self.load_notes()
Note.reset_id_counter(self.notes)
def load_notes(self) -> None:
if self.file_path.exists():
try:
with open(self.file_path, "r") as f:
data = json.load(f)
self.notes = [Note.from_dict(note_data) for note_data in data]
except (json.JSONDecodeError, FileNotFoundError):
self.notes = []
else:
self.notes = []
def save_notes(self) -> None:
data = [note.to_dict() for note in self.notes]
with open(self.file_path, "w") as f:
json.dump(data, f, indent=2)
def add_note(self, body: str) -> Note:
"""Add a new note, extracting title from first line of body"""
title = self._extract_title_from_body(body)
note = Note(title, body)
self.notes.append(note)
self.save_notes()
return note
def update_note(self, note_id: int, body: str) -> bool:
"""Update a note, extracting title from first line of body"""
for note in self.notes:
if note.id == note_id:
title = self._extract_title_from_body(body)
note.update(title, body)
self.save_notes()
return True
return False
def _extract_title_from_body(self, body: str) -> str:
"""Extract title from the first non-empty line of body"""
lines = body.strip().split('\n')
for line in lines:
if line.strip(): # First non-empty line
return line.strip()[:50] # Limit title length
return "Untitled" # Default if body is empty
def delete_note(self, note_id: int) -> bool:
self.notes = [note for note in self.notes if note.id != note_id]
self.save_notes()
return True
def get_note(self, note_id: int) -> Optional[Note]:
for note in self.notes:
if note.id == note_id:
return note
return None
def search_notes(self, search_term: str) -> List[Note]:
if not search_term:
return self.notes
results = []
search_lower = search_term.lower()
for note in self.notes:
if (search_lower in note.title.lower() or
search_lower in note.body.lower() or
search_lower in note.created_at or
search_lower in note.updated_at):
results.append(note)
return results
class QSNotes:
"""Terminal TUI using curses"""
def __init__(self, stdscr, initial_mode="list", initial_body=""):
self.stdscr = stdscr
self.note_manager = NoteManager()
self.current_note_id: Optional[int] = None
self.search_term = ""
self.selected_index = 0
self.sort_desc = True
self.last_selected_index = 0 # track last selection
self.mode = initial_mode # "list", "edit", or "new"
self.editing_body = initial_body # Pre-fill body if provided
self.show_search = False
self.notes_per_page = 0
self.cursor_pos = 0 # Cursor position in current field
self.body_cursor_row = 0 # Current row in body (for multiline)
self.body_cursor_col = 0 # Current column in body
self._last_height = 0
self._last_width = 0
self.body_scroll = 0
self.preview_scroll = 0
self.list_body_scroll = 0 # Scroll position for body in list view
self.LIST_VISIBLE_COUNT = 5
# If starting in new mode with pre-filled body, set cursor at the end
if self.mode == "new" and self.editing_body:
body_lines = self.editing_body.split("\n")
self.body_cursor_row = len(body_lines) - 1
self.body_cursor_col = len(body_lines[-1])
# Initialize curses
curses.curs_set(0) # Hide cursor
self.stdscr.nodelay(0) # Blocking input
self.stdscr.keypad(True) # Enable special keys
# Define color pairs (terminal colors)
curses.start_color()
curses.use_default_colors() # Use terminal default colors
# Create color pairs
curses.init_pair(1, curses.COLOR_BLUE, -1) #
curses.init_pair(2, curses.COLOR_WHITE, -1) #
curses.init_pair(3, curses.COLOR_CYAN, -1) #
curses.init_pair(4, -1, curses.COLOR_BLUE) #
curses.init_pair(5, curses.COLOR_GREEN, -1) #
curses.init_pair(6, curses.COLOR_RED, -1) #
curses.init_pair(7, curses.COLOR_YELLOW, -1) #
curses.init_pair(8, curses.COLOR_MAGENTA, -1) #
# Add a small delay to ensure terminal is ready
time.sleep(0.1)
def get_sorted_notes(self):
notes = self.note_manager.search_notes(self.search_term)
return sorted(notes, key=lambda x: x.updated_at, reverse=self.sort_desc)
def draw_box(self, y: int, x: int, height: int, width: int, title: str = "", color_pair: int = 0) -> None:
# Safety check - don't draw if coordinates are out of bounds
max_y, max_x = self.stdscr.getmaxyx()
# Ensure we're not drawing outside the screen
if y < 0 or x < 0 or y + height > max_y or x + width > max_x:
return
# Top border
try:
self.stdscr.attron(curses.color_pair(color_pair))
self.stdscr.addch(y, x, curses.ACS_ULCORNER)
self.stdscr.hline(y, x + 1, curses.ACS_HLINE, width - 2)
self.stdscr.addch(y, x + width - 1, curses.ACS_URCORNER)
# Title if provided
if title and len(title) < width - 4:
title_x = x + 2
if color_pair:
self.stdscr.attron(curses.color_pair(color_pair))
self.stdscr.addstr(y, title_x, title)
if color_pair:
self.stdscr.attroff(curses.color_pair(color_pair))
# Sides
self.stdscr.attron(curses.color_pair(color_pair))
for row in range(y + 1, y + height - 1):
if row < max_y:
self.stdscr.addch(row, x, curses.ACS_VLINE)
self.stdscr.addch(row, x + width - 1, curses.ACS_VLINE)
# Bottom border
if y + height - 1 < max_y:
self.stdscr.addch(y + height - 1, x, curses.ACS_LLCORNER)
self.stdscr.hline(y + height - 1, x + 1, curses.ACS_HLINE, width - 2)
self.stdscr.addch(y + height - 1, x + width - 1, curses.ACS_LRCORNER)
except curses.error:
# Ignore curses errors when drawing at screen edges
pass
def safe_addstr(self, y: int, x: int, text: str, attr=0) -> None:
"""Safely add a string at the given coordinates, truncating if necessary"""
try:
max_y, max_x = self.stdscr.getmaxyx()
if y >= 0 and y < max_y and x >= 0 and x < max_x:
# Truncate text if it would go beyond screen width
available_width = max_x - x
if len(text) > available_width:
text = text[:available_width]
self.stdscr.addstr(y, x, text, attr)
except curses.error:
# Ignore curses errors when writing at screen edges
pass
def draw_list_view(self) -> None:
self.stdscr.erase()
height, width = self.stdscr.getmaxyx()
# Ensure minimum terminal size
if height < 15 or width < 60:
self.safe_addstr(0, 0, "Terminal too small. Please resize.", curses.color_pair(6))
self.stdscr.noutrefresh()
curses.doupdate()
return
# Main box
self.draw_box(1, 2, height - 4, width - 4, " QSNotes ", 3)
# Command hints box at bottom
self.draw_box(height - 3, 2, 3, width - 4, "", 5)
hints = "n:New Enter:Edit d:Del /:Search q:Quit j/k:Scrl"
hints_x = (width - len(hints)) // 2
self.safe_addstr(height - 2, hints_x, hints, curses.color_pair(3))
# Search bar if active
if self.show_search:
search_text = f"Search: {self.search_term}"
self.safe_addstr(3, 4, "Search: ", curses.color_pair(1))
self.safe_addstr(3, 12, self.search_term, curses.color_pair(2))
curses.curs_set(1) # Show cursor for input
self.stdscr.move(3, min(12 + len(self.search_term), width - 5))
else:
curses.curs_set(0) # Hide cursor
# Notes list
sorted_notes = self.get_sorted_notes()
# Calculate display
self.notes_per_page = self.LIST_VISIBLE_COUNT
start_index = 0
if len(sorted_notes) > self.notes_per_page:
if self.selected_index >= self.notes_per_page:
start_index = self.selected_index - self.notes_per_page + 1
# Header
header = "Title Created Updated"
self.safe_addstr(4, 4, header, curses.color_pair(1))
try:
self.stdscr.hline(5, 4, curses.ACS_HLINE, min(width - 8, len(header) + 4))
except curses.error:
pass
# Notes
for i, note in enumerate(
sorted_notes[start_index:start_index + self.notes_per_page]
):
y = 6 + i
is_selected = (i + start_index) == self.selected_index
# Format data
title = (note.title[:27] + "...") if len(note.title) > 27 else note.title.ljust(30)
created = datetime.fromisoformat(note.created_at).strftime("%Y-%m-%d")
updated = datetime.fromisoformat(note.updated_at).strftime("%Y-%m-%d")
# Draw
line = f"{title:28} {created:10} {updated:10}"
if is_selected:
self.safe_addstr(y, 4, line, curses.color_pair(4))
else:
self.safe_addstr(y, 4, line, curses.color_pair(2))
preview_separator_y = 6 + self.LIST_VISIBLE_COUNT
try:
self.stdscr.hline(preview_separator_y, 4, curses.ACS_HLINE, width - 8)
except curses.error:
pass
# Draw scrollable body preview
selected_note = None
if 0 <= self.selected_index < len(sorted_notes):
selected_note = sorted_notes[self.selected_index]
preview_lines = []
max_width = width - 8
if selected_note:
# Split body into lines and wrap them
for line in selected_note.body.split("\n"):
if line == "":
preview_lines.append("")
else:
for i in range(0, len(line), max_width):
preview_lines.append(line[i:i + max_width])
preview_top = preview_separator_y + 1
preview_bottom = height - 4
preview_height = preview_bottom - preview_top
# Handle scrolling in preview
max_scroll = max(0, len(preview_lines) - preview_height)
self.list_body_scroll = max(0, min(self.list_body_scroll, max_scroll))
# Draw scroll indicator if needed
if max_scroll > 0:
scroll_percent = int((self.list_body_scroll / max_scroll) * 100)
scroll_text = f" [Scroll: {scroll_percent}%]"
self.safe_addstr(preview_top - 1, width - len(scroll_text) - 5,
scroll_text, curses.color_pair(3))
# Draw the visible portion of the body
for i in range(preview_height):
idx = self.list_body_scroll + i
if idx >= len(preview_lines):
break
# Truncate if line is too long
line = preview_lines[idx]
if len(line) > max_width:
line = line[:max_width-3] + "..."
self.safe_addstr(
preview_top + i,
4,
line,
curses.color_pair(3)
)
# No notes message
if not sorted_notes:
msg = "No notes yet. Press 'n' to create one!"
if self.search_term:
msg = f"No notes found for '{self.search_term}'"
msg_x = (width - len(msg)) // 2
self.safe_addstr(6, msg_x, msg, curses.color_pair(3))
if self.show_search:
curses.curs_set(1)
self.stdscr.move(3, min(12 + len(self.search_term), width - 5))
else:
curses.curs_set(0)
self.stdscr.noutrefresh()
curses.doupdate()
def draw_edit_view(self) -> None:
self.stdscr.erase()
height, width = self.stdscr.getmaxyx()
# Ensure minimum terminal size
if height < 10 or width < 40:
self.safe_addstr(0, 0, "Terminal too small. Please resize.", curses.color_pair(6))
self.stdscr.noutrefresh()
curses.doupdate()
return
# Layout constants
body_top = 5
body_bottom = height - 4
max_body_lines = body_bottom - body_top
max_line_width = width - 8
# Main boxes
self.draw_box(1, 2, height - 4, width - 4, " QNotes ", 3)
self.draw_box(height - 3, 2, 3, width - 4, "", 5)
hints = "Ctrl+W:Save Ctrl+O:Save&Exit Esc:Cancel&Back"
hints_x = (width - len(hints)) // 2
self.safe_addstr(height - 2, hints_x, hints, curses.color_pair(3))
# ----- BODY (full note content) -----
self.safe_addstr(4, 4, "Note:", curses.color_pair(1))
body_lines = self.editing_body.split("\n") or [""]
# Build wrapped line map: [(orig_row, start_col)]
self.wrapped_line_map = []
for row_idx, line in enumerate(body_lines):
if line == "":
self.wrapped_line_map.append((row_idx, 0))
else:
for start in range(0, len(line), max_line_width):
self.wrapped_line_map.append((row_idx, start))
if not self.wrapped_line_map:
self.wrapped_line_map.append((0, 0))
# Clamp scroll
max_scroll = max(0, len(self.wrapped_line_map) - max_body_lines)
self.body_scroll = max(0, min(self.body_scroll, max_scroll))
# Draw visible body slice
visible = self.wrapped_line_map[
self.body_scroll : self.body_scroll + max_body_lines
]
for i, (row, col) in enumerate(visible):
line = body_lines[row][col : col + max_line_width]
self.safe_addstr(body_top + i, 4, line, curses.color_pair(2))
# ----- CURSOR POSITION -----
# Find wrapped line index of cursor
wrapped_idx = 0
for i, (r, c) in enumerate(self.wrapped_line_map):
if r == self.body_cursor_row and self.body_cursor_col >= c:
wrapped_idx = i
# Auto-scroll to keep cursor visible
if wrapped_idx < self.body_scroll:
self.body_scroll = wrapped_idx
elif wrapped_idx >= self.body_scroll + max_body_lines:
self.body_scroll = wrapped_idx - max_body_lines + 1
# Re-clamp
self.body_scroll = max(0, min(self.body_scroll, max_scroll))
screen_row = wrapped_idx - self.body_scroll
start_col = self.wrapped_line_map[wrapped_idx][1]
cursor_y = body_top + screen_row
cursor_x = 4 + min(
self.body_cursor_col - start_col, max_line_width - 1
)
# Ensure cursor is within bounds
cursor_y = min(cursor_y, height - 5)
cursor_x = min(cursor_x, width - 5)
curses.curs_set(1)
self.stdscr.move(cursor_y, cursor_x)
self.stdscr.noutrefresh()
curses.doupdate()
def clamp_selection(self, notes):
if not notes:
self.selected_index = 0
else:
self.selected_index = max(
0, min(self.selected_index, len(notes) - 1)
)
def check_save_key(self, key: int) -> bool:
"""Check if key is a save key combination. Returns True if save should occur."""
save_keys = [23] # Ctrl+W (ASCII 23)
return key in save_keys
def handle_list_mode(self, key: int) -> bool:
if self.show_search:
if self.show_search:
notes = self.get_sorted_notes()
if key in (curses.KEY_UP, curses.KEY_DOWN):
if notes:
if key == curses.KEY_UP:
self.selected_index = (self.selected_index - 1) % len(notes)
else:
self.selected_index = (self.selected_index + 1) % len(notes)
self.list_body_scroll = 0 # Reset scroll when changing notes
self.draw_list_view()
return True
if key in (curses.KEY_BACKSPACE, 127):
self.search_term = self.search_term[:-1]
notes = self.get_sorted_notes()
self.clamp_selection(notes)
self.list_body_scroll = 0
self.draw_list_view()
elif key == 27: # Esc
self.show_search = False
self.search_term = ""
self.draw_list_view()
elif key == 10: # Enter
notes = self.get_sorted_notes()
sorted_notes = self.get_sorted_notes()
if 0 <= self.selected_index < len(sorted_notes):
note = sorted_notes[self.selected_index]
self.mode = "edit"
self.current_note_id = note.id
self.editing_body = note.body
# Set cursor at end of body
body_lines = self.editing_body.split("\n") or [""]
self.body_cursor_row = len(body_lines) - 1
self.body_cursor_col = len(body_lines[-1])
# Reset body scroll
self.body_scroll = 0
self.last_selected_index = self.selected_index
self.draw_edit_view()
elif 32 <= key <= 126:
self.search_term += chr(key)
notes = self.get_sorted_notes()
self.selected_index = 0
self.list_body_scroll = 0
self.draw_list_view()
return True
# Handle keys in list mode. Returns True if should continue, False if quit.
if key == ord('q'):
return False
elif key == ord('n'):
self.mode = "new"
self.current_note_id = None
self.editing_body = ""
self.body_cursor_row = 0
self.body_cursor_col = 0
self.draw_edit_view()
elif key == ord('/'):
self.show_search = True
self.search_term = ""
self.selected_index = 0
self.list_body_scroll = 0
self.draw_list_view()
elif key == ord('s'):
self.sort_desc = not self.sort_desc
self.selected_index = 0
self.list_body_scroll = 0
self.draw_list_view()
elif key == 10: # Enter
notes = self.get_sorted_notes()
sorted_notes = self.get_sorted_notes()
if 0 <= self.selected_index < len(sorted_notes):
note = sorted_notes[self.selected_index]
self.mode = "edit"
self.current_note_id = note.id
self.editing_body = note.body
# Set cursor at end of body
body_lines = self.editing_body.split("\n") or [""]
self.body_cursor_row = len(body_lines) - 1
self.body_cursor_col = len(body_lines[-1])
# Reset body scroll
self.body_scroll = 0
self.last_selected_index = self.selected_index
self.draw_edit_view()
elif key == ord('d'):
notes = self.get_sorted_notes()
sorted_notes = self.get_sorted_notes()
if 0 <= self.selected_index < len(sorted_notes):
note = sorted_notes[self.selected_index]
self.note_manager.delete_note(note.id)
if self.selected_index >= len(sorted_notes) - 1:
self.selected_index = max(0, len(sorted_notes) - 2)
self.draw_list_view()
self.list_body_scroll = 0
elif key == curses.KEY_UP:
notes = self.get_sorted_notes()
if notes:
self.selected_index = (self.selected_index - 1) % len(notes)
self.list_body_scroll = 0 # Reset scroll when changing notes
self.draw_list_view()
elif key == curses.KEY_DOWN:
notes = self.get_sorted_notes()
if notes:
self.selected_index = (self.selected_index + 1) % len(notes)
self.list_body_scroll = 0 # Reset scroll when changing notes
self.draw_list_view()
# Handle preview scrolling with j/k keys
elif key == ord('j') or key == ord('J'):
notes = self.get_sorted_notes()
if notes and 0 <= self.selected_index < len(notes):
# Calculate max scroll for current note
note = notes[self.selected_index]
height, width = self.stdscr.getmaxyx()
max_width = width - 8
# Count wrapped lines
preview_lines = []
for line in note.body.split("\n"):
if line == "":
preview_lines.append("")
else:
for i in range(0, len(line), max_width):
preview_lines.append(line[i:i + max_width])
preview_height = (height - 4) - (6 + self.LIST_VISIBLE_COUNT + 1)
max_scroll = max(0, len(preview_lines) - preview_height)
self.list_body_scroll = min(max_scroll, self.list_body_scroll + 1)
self.draw_list_view()
elif key == ord('k') or key == ord('K'):
notes = self.get_sorted_notes()
if notes and 0 <= self.selected_index < len(notes):
self.list_body_scroll = max(0, self.list_body_scroll - 1)
self.draw_list_view()
elif self.show_search:
if key == curses.KEY_BACKSPACE or key == 127:
self.search_term = self.search_term[:-1]
self.draw_list_view()
elif key == 27: # Escape
self.show_search = False
self.search_term = ""
self.draw_list_view()
elif 32 <= key <= 126: # Printable ASCII
self.search_term += chr(key)
self.draw_list_view()
self.selected_index = min(
self.selected_index,
len(self.note_manager.notes) - 1
)
self.list_body_scroll = 0
return True
def handle_edit_mode(self, key: int):
# First check for control keys
if key == 27: # Escape - Cancel
self.mode = "list"
self.draw_list_view()
return
# Ctrl+O - Save and exit app
if key == 15: # Ctrl+O
if self.editing_body.strip():
if self.current_note_id:
self.note_manager.update_note(
self.current_note_id,
self.editing_body
)
else:
self.note_manager.add_note(self.editing_body)
# Cleanly exit curses and then exit
raise KeyboardInterrupt
# Check for save keys
if self.check_save_key(key):
if self.editing_body.strip():
if self.current_note_id:
# Update existing note - keep selection
self.note_manager.update_note(
self.current_note_id,
self.editing_body
)
else:
# Create new note - select the new note
new_note = self.note_manager.add_note(self.editing_body)
# Find the index of the new note
notes = self.get_sorted_notes()
sorted_notes = self.get_sorted_notes()
for i, note in enumerate(sorted_notes):
if note.id == new_note.id:
self.selected_index = i
break
self.mode = "list"
self.draw_list_view()
return
# Handle text editing in body
self.handle_body_input(key)
def handle_body_input(self, key: int):
body_lines = self.editing_body.split('\n')
# Ensure we have at least one line
if not body_lines:
body_lines = [""]
# Make sure body_cursor_row is within bounds
if self.body_cursor_row >= len(body_lines):
self.body_cursor_row = max(0, len(body_lines) - 1)
# Ensure body_cursor_row is not negative
if self.body_cursor_row < 0:
self.body_cursor_row = 0
# Get current line
if self.body_cursor_row < len(body_lines):
current_line = body_lines[self.body_cursor_row]
else:
current_line = ""
# Ensure body_cursor_col is within bounds
if self.body_cursor_col > len(current_line):
self.body_cursor_col = len(current_line)
if self.body_cursor_col < 0:
self.body_cursor_col = 0
# Handle backspace (delete left)
if key == curses.KEY_BACKSPACE or key == 127:
if self.body_cursor_col > 0:
# Delete character before cursor
new_line = current_line[:self.body_cursor_col-1] + current_line[self.body_cursor_col:]
body_lines[self.body_cursor_row] = new_line
self.editing_body = '\n'.join(body_lines)
self.body_cursor_col -= 1
elif self.body_cursor_row > 0:
# Join with previous line
prev_line = body_lines[self.body_cursor_row-1]
body_lines[self.body_cursor_row-1] = prev_line + current_line
del body_lines[self.body_cursor_row]
self.editing_body = '\n'.join(body_lines)
self.body_cursor_row -= 1
self.body_cursor_col = len(prev_line)
self.draw_edit_view()
# Handle delete (delete right)
elif key == curses.KEY_DC:
if self.body_cursor_col < len(current_line):
# Delete character at cursor
new_line = current_line[:self.body_cursor_col] + current_line[self.body_cursor_col+1:]
body_lines[self.body_cursor_row] = new_line
self.editing_body = '\n'.join(body_lines)
elif self.body_cursor_row < len(body_lines) - 1:
# Join with next line
next_line = body_lines[self.body_cursor_row+1]
body_lines[self.body_cursor_row] = current_line + next_line
del body_lines[self.body_cursor_row+1]
self.editing_body = '\n'.join(body_lines)
self.draw_edit_view()
elif key == 10: # Enter - new line
# Split current line at cursor
left_part = current_line[:self.body_cursor_col]
right_part = current_line[self.body_cursor_col:]
body_lines[self.body_cursor_row] = left_part
body_lines.insert(self.body_cursor_row + 1, right_part)
self.editing_body = '\n'.join(body_lines)
self.body_cursor_row += 1
self.body_cursor_col = 0
self.draw_edit_view()
elif key == curses.KEY_LEFT:
if self.body_cursor_col > 0:
self.body_cursor_col -= 1
elif self.body_cursor_row > 0:
self.body_cursor_row -= 1
# Get the new current line
if self.body_cursor_row < len(body_lines):
self.body_cursor_col = len(body_lines[self.body_cursor_row])
else:
self.body_cursor_col = 0
self.draw_edit_view()
elif key == curses.KEY_RIGHT:
if self.body_cursor_col < len(current_line):
self.body_cursor_col += 1
elif self.body_cursor_row < len(body_lines) - 1:
self.body_cursor_row += 1
self.body_cursor_col = 0
self.draw_edit_view()
elif key == curses.KEY_UP:
if self.body_cursor_row > 0:
self.body_cursor_row -= 1
# Get the new current line
if self.body_cursor_row < len(body_lines):
# Keep cursor column within bounds of new line
new_line_len = len(body_lines[self.body_cursor_row])
self.body_cursor_col = min(self.body_cursor_col, new_line_len)
else:
self.body_cursor_col = 0
self.draw_edit_view()
elif key == curses.KEY_DOWN:
if self.body_cursor_row < len(body_lines) - 1:
self.body_cursor_row += 1
# Get the new current line
if self.body_cursor_row < len(body_lines):
# Keep cursor column within bounds of new line
new_line_len = len(body_lines[self.body_cursor_row])
self.body_cursor_col = min(self.body_cursor_col, new_line_len)
else:
self.body_cursor_col = 0
self.draw_edit_view()
elif key == curses.KEY_HOME:
self.body_cursor_col = 0
self.draw_edit_view()
elif key == curses.KEY_END:
if self.body_cursor_row < len(body_lines):
self.body_cursor_col = len(body_lines[self.body_cursor_row])
self.draw_edit_view()
elif 32 <= key <= 126:
# Insert character at cursor position
new_line = current_line[:self.body_cursor_col] + chr(key) + current_line[self.body_cursor_col:]
body_lines[self.body_cursor_row] = new_line
self.editing_body = '\n'.join(body_lines)
self.body_cursor_col += 1
self.draw_edit_view()
def run(self) -> None:
# Initial draw based on mode
try:
if self.mode == "list":
self.draw_list_view()
else: # "new" or "edit"
self.draw_edit_view()
except curses.error:
# If we get an error on first draw, wait a bit and try again
time.sleep(0.2)
if self.mode == "list":
self.draw_list_view()
else:
self.draw_edit_view()
while True:
try:
key = self.stdscr.getch()
if self.mode == "list":
if not self.handle_list_mode(key):
# Quit from list mode (q key)
break
elif self.mode in ["edit", "new"]:
self.handle_edit_mode(key)
except KeyboardInterrupt:
break
except curses.error:
# If we get a curses error, just redraw
if self.mode == "list":
self.draw_list_view()
else:
self.draw_edit_view()
return
def parse_arguments():
parser = argparse.ArgumentParser(description="QSNotes - Quick & Simple Notes TUI")
parser.add_argument('-n', '--new', action='store_true',
help='Start in new note mode')
parser.add_argument('-b', '--body', type=str, default='',
help='Pre-fill note body with text')
parser.add_argument('-q', '--quick', type=str, metavar='TEXT',
help='Quick note: create a new note with the given text and exit')
parser.add_argument('-p', '--pipe', action='store_true',
help='Read note content from stdin')
return parser.parse_args()
def main(stdscr):
"""Main entry point for curses"""
args = parse_arguments()
# Handle piped input
if args.pipe and not sys.stdin.isatty():
content = sys.stdin.read().strip()
note_manager = NoteManager()
note_manager.add_note(content)
print(f"Note added from pipe: {content[:50]}...")
return
# Handle quick note mode (create and exit immediately)
if args.quick:
# Initialize note manager (no curses needed)
note_manager = NoteManager()
note_manager.add_note(args.quick)
print(f"Quick note added: {args.quick[:50]}...")
return
# Determine initial mode
initial_mode = "new" if args.new else "list"
initial_body = args.body if args.body else ""
# Start the TUI with the specified mode
app = QSNotes(stdscr, initial_mode, initial_body)
app.run()
if __name__ == "__main__":
# Parse arguments first
args = parse_arguments()
# If it's a quick note, run without curses
if args.quick:
main(None)
else:
# Run the curses application normally
curses.wrapper(main)