Repository navigation
Expand file tree
/
Copy pathhyperlist
More file actions
executable file
·6836 lines (5899 loc) · 223 KB
/
Copy pathhyperlist
File metadata and controls
executable file
·6836 lines (5899 loc) · 223 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
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env ruby
# encoding: utf-8
# HyperList TUI - A terminal interface for HyperList files
# Based on hyperlist.vim by Geir Isene
# Check for help/version BEFORE loading any libraries
if ARGV[0] == '-h' || ARGV[0] == '--help'
puts <<~HELP
HyperList v1.9.4 - Terminal User Interface for HyperList files
USAGE
hyperlist [OPTIONS] [FILE]
OPTIONS
-h, --help Show this help message
-v, --version Show version information
ARGUMENTS
FILE Optional HyperList file to open (.hl extension)
If not provided, starts with a new empty HyperList
EXAMPLES
hyperlist Start with a new HyperList
hyperlist todo.hl Open todo.hl
hyperlist ~/lists/work.hl Open work.hl from home directory
KEY COMMANDS
? Show key bindings help
?? Show full HyperList documentation
q Quit (with save prompt if modified)
:w Save file
:q Quit
:wq Save and quit
FEATURES
• Full HyperList syntax support with color highlighting
• Folding/expanding of hierarchical items
• Search and navigation
• Checkboxes with date tracking
• Templates for common list structures
• Macro recording and playback
• Split view for working with multiple sections
• Export to Markdown, HTML, plain text, and PNG graphs
• Auto-save capability
• Multi-level undo
• Vim-style marks and jumping
For more information and HyperList documentation, visit:
https://github.com/isene/hyperlist
HELP
exit 0
elsif ARGV[0] == '-v' || ARGV[0] == '--version'
puts "HyperList v1.9.4"
exit 0
end
# Only load libraries if we're actually running the app
require 'io/console'
require 'date'
require 'rcurses'
require 'cgi'
require 'openssl'
require 'digest'
require 'base64'
require 'fileutils'
require 'json'
require 'shellwords'
class HyperListApp
include Rcurses
include Rcurses::Input
include Rcurses::Cursor
VERSION = "1.12.0"
def initialize(filename = nil)
@filename = filename ? File.expand_path(filename) : nil
@items = []
@current = 0
@offset = 0
@modified = false
@mode = :normal
@message = ""
@search = ""
@search_matches = [] # Track search match positions
@fold_level = 99
@config_line = nil # Store config line from file
@theme = "normal" # Default theme
@wrap = false # Line wrapping disabled by default
@show_numbers = false # Line numbers disabled by default
@command_history = load_command_history # Command history for : commands
@clipboard = nil
@tagged_items = [] # Items tagged for batch operations
@original_items = nil # Track original file state for smart modified flag
@undo_stack = []
@undo_position = [] # Stack of cursor positions for undo
@redo_stack = []
@redo_position = [] # Stack of cursor positions for redo
@last_action = nil # Store the last editing action for '.' repeat
@last_action_type = nil # Type of last action
@processed_cache = {} # Cache for processed text
@presentation_mode = false # Presentation mode flag
@last_key = nil # Track last key for double-key combos
@last_rendered_lines = [] # Track last rendered lines
@recent_files_path = File.expand_path("~/.hyperlist_recent")
@auto_save_enabled = false
@auto_save_interval = 60 # seconds
@last_auto_save = Time.now
@templates_dir = File.expand_path("~/.hyperlist/templates")
ensure_templates_dir
@templates = load_templates
@macro_recording = false
@macro_register = {} # Store macros by key
@macro_buffer = [] # Current macro being recorded
@macro_key = nil # Key for current macro
@encryption_key = nil # Store derived encryption key
@encrypted_lines = {} # Track which lines are encrypted
@st_underline_mode = 0 # 0: none, 1: underline states, 2: underline transitions
@split_view = false
@split_items = [] # Second view items
@split_current = 0 # Second view cursor
@split_offset = 0 # Second view scroll offset
@active_pane = :main # :main or :split
@message_timeout = nil # For timed message display
@file_mtime = nil # Track file modification time for external change detection
# Global configuration
@config_file = File.expand_path("~/.hyperlist/config.yml")
@indent_size = 2 # Default indentation (2-5 spaces)
load_config
# Terminal setup
if IO.console
@rows, @cols = IO.console.winsize
else
@rows = ENV['LINES']&.to_i || 24
@cols = ENV['COLUMNS']&.to_i || 80
end
# Setup terminal resize handler
setup_resize_handler
# Setup UI first (to initialize @footer) before loading file
setup_ui
# Load file if provided (after UI is set up)
if @filename && File.exist?(@filename)
load_file(@filename)
else
# Start with empty list
@items = [{"text" => "New HyperList", "level" => 0, "fold" => false}]
end
end
def setup_ui
# Only do rcurses operations if initialized
if defined?(Rcurses.instance_variable_get) && Rcurses.instance_variable_get(:@initialized)
Rcurses.clear_screen
Cursor.hide
end
# Ensure we have the latest terminal size
if IO.console
@rows, @cols = IO.console.winsize
else
@rows = ENV['LINES']&.to_i || 24
@cols = ENV['COLUMNS']&.to_i || 80
end
if @split_view
# Split view layout - no header, more space for content
split_width = @cols / 2
# Main content panes - use nil colors to act as pass-through for pre-colored text
# This is how RTFM works - it passes colored command output to panes with nil colors
@main = Pane.new(1, 1, split_width - 1, @rows - 1, nil, nil)
@split_pane = Pane.new(split_width + 1, 1, split_width - 1, @rows - 1, nil, nil)
@footer = Pane.new(1, @rows, @cols, 1, 15, 8)
# Add separator with explicit background to overwrite emoji overflow
@separator = Pane.new(split_width, 1, 1, @rows - 1, 15, 0)
# Build separator with explicit clearing
separator_lines = []
(@rows - 1).times do
separator_lines << "│"
end
@separator.text = separator_lines.join("\n")
@separator.refresh
else
# Single view layout - no header, more space for content
# Use nil colors like RTFM to avoid ANSI wrapping issues
# This prevents the corruption that happens with narrow terminals
@main = Pane.new(1, 1, @cols, @rows - 1, nil, nil)
@footer = Pane.new(1, @rows, @cols, 1, 15, 8)
end
end
def setup_resize_handler
# Catch terminal resize signal
Signal.trap('WINCH') do
refresh_on_resize
end
rescue
# Ignore if signal handling not available on this platform
end
def refresh_on_resize
# Get new terminal dimensions
if IO.console
@rows, @cols = IO.console.winsize
else
@rows = ENV['LINES']&.to_i || 24
@cols = ENV['COLUMNS']&.to_i || 80
end
# Reinitialize UI with new dimensions
setup_ui
# Force full redraw
render
rescue
# Ignore errors during resize to prevent crashes
end
def load_file(file)
@items = []
@encrypted_lines = {}
@config_line = nil # Reset config line before loading
@tagged_items = [] # Clear tags when loading new file
# Track file modification time for external change detection
@file_mtime = File.mtime(file) rescue nil
# Read file content
content = File.read(file) rescue ""
# Clear undo/redo stacks when loading a new file
@undo_stack = []
@undo_position = []
@redo_stack = []
@redo_position = []
# Parse config line if present (before processing content)
parse_config_line(content)
# Check if file is encrypted (dot file or encrypted content)
is_encrypted = false
if is_encrypted_file?(file)
if content.start_with?("ENC:")
# Whole file is encrypted
decrypted_content = decrypt_file(content)
if decrypted_content.nil?
@message = "Failed to decrypt file"
@items = [{"text" => "Failed to decrypt file", "level" => 0, "fold" => false}]
return
end
lines = decrypted_content.split("\n")
@message = "File decrypted successfully (folded for privacy)"
is_encrypted = true
else
# Dot file but not encrypted yet - just load normally
lines = content.split("\n")
end
else
lines = content.split("\n")
end
# Auto-detect indentation from the file
detect_indentation(lines)
# Check if file is large
large_file = lines.length > 10000
if large_file
@message = "Loading large file (#{lines.length} lines)..."
render_footer
end
# Process lines with optional progress updates for large files
lines.each_with_index do |line, idx|
next if line.strip.empty?
# Skip config lines (don't add them to items)
if line.strip =~ /^\(\(.+\)\)$/
next
end
# Check if this is a continuation line for a multi-line item
# According to HyperList spec: continuation lines start with space after the indent
is_continuation = false
if @items.length > 0
last_item = @items.last
# Only an Item with a Starter spans lines. Its following lines sit
# two spaces beyond its indent (HyperList 2.8 on), or one in older
# files. With a two-space indent, two spaces is a child instead.
if starter?(last_item["text"])
indent = last_item["level"] * @indent_size
extra = line[/^ */].length - indent
if extra == 1 || (extra == 2 && @indent_size >= 3)
last_item["text"] += "\n" + line[indent..]
next # Skip adding as a new item
end
end
end
# Detect level based on leading whitespace
if line.start_with?("\t")
# Tab-based indentation
level = line[/^\t*/].length
else
# Space-based indentation
spaces = line[/^ */].length
level = @indent_size > 0 ? spaces / @indent_size : 0
end
text = line.strip
# Track encrypted lines
if text.start_with?("ENC:")
@encrypted_lines[@items.length] = true
end
@items << {"text" => text, "level" => level, "fold" => false}
# Update progress for large files
if large_file && idx % 1000 == 0
progress = (idx.to_f / lines.length * 100).to_i
@message = "Loading... #{progress}%"
render_footer
end
end
@items = [{"text" => "Empty file", "level" => 0, "fold" => false}] if @items.empty?
# Auto-fold for privacy/security on encrypted files
if is_encrypted
@fold_level = 0 # Set fold level to 0 (everything folded)
# Fold all items that have children
@items.each_with_index do |item, idx|
if has_children?(idx, @items)
item["fold"] = true
end
end
end
# Auto-fold deep levels for large files
if large_file
auto_fold_deep_levels(3) # Auto-fold everything deeper than level 3
@message = "Large file loaded. Deep levels auto-folded for performance."
end
# Apply configured fold level if set (after items are loaded)
if @fold_level != 99 && !is_encrypted # Don't override encrypted file folding
apply_fold_level(@fold_level)
@message = "Applied fold level: #{@fold_level}" if @message.nil? || @message.empty?
end
# Update recent files list
add_to_recent_files(File.expand_path(file)) if file
# Save original state for smart modified flag
@original_items = @items.map { |item| item.dup }
end
def auto_fold_deep_levels(max_level)
@items.each_with_index do |item, idx|
if item["level"] >= max_level && has_children?(idx, @items)
item["fold"] = true
end
end
end
def apply_fold_level(level)
# Apply fold level: 0 = all folded, 99 = all open
# Show items up to and including the specified level
# Fold items at levels greater than specified level
@items.each_with_index do |item, idx|
if has_children?(idx, @items)
# Fold if item level is greater than or equal to the fold level
# This means: fold_level=1 shows level 0 expanded, level 1 and deeper folded
# fold_level=2 shows levels 0-1 expanded, level 2 and deeper folded
item["fold"] = item["level"] >= level
end
end
# Special cases
if level == 0
# Fold everything that has children
@items.each_with_index do |item, idx|
item["fold"] = true if has_children?(idx, @items)
end
elsif level >= 99
# Unfold everything
@items.each { |item| item["fold"] = false }
end
end
def parse_config_line(content)
# Look for config line at the bottom of the file
# Format: ((option1=value, option2=value))
lines = content.split("\n")
# Check last 10 lines for config (in case there are empty lines or other content)
config_line = nil
lines.last(10).each do |line|
# Allow indented config lines
if line.strip =~ /^\(\((.+)\)\)$/
@config_line = line.strip # Store the full line to preserve when saving
config_line = $1
break
end
end
return unless config_line
# Parse options (comma-separated)
config_options = {}
config_line.split(',').each do |option|
option = option.strip
if option =~ /(\w+)=(.+)/
key = $1.strip
value = $2.strip
# Convert values to appropriate types
case key
when "fold_level", "auto_save_interval", "tab_width", "indent_size"
config_options[key] = value.to_i
when "auto_save", "wrap", "show_numbers", "highlight_current", "checkbox_date", "backup", "encrypt"
config_options[key] = value.downcase == "true" || value.downcase == "yes"
else
config_options[key] = value
end
end
end
# Apply config options
apply_config(config_options)
end
def apply_config(options)
# Apply configuration options from config line
options.each do |key, value|
case key
when "fold_level"
@fold_level = value if value >= 0 && value <= 99
when "auto_save"
@auto_save_enabled = value
when "auto_save_interval"
@auto_save_interval = value if value > 0
when "tab_width", "indent_size"
@indent_size = value if value >= 2 && value <= 8
when "presentation_mode", "presentation"
@presentation_mode = value
setup_ui if value # Refresh UI if entering presentation mode
when "default_view"
case value
when "split"
@split_view = true
setup_ui
when "presentation"
@presentation_mode = true
setup_ui
end
when "theme"
# Apply theme setting
@theme = value if ["light", "normal", "dark"].include?(value)
when "wrap"
@wrap = value
when "show_numbers"
@show_numbers = value
when "search_case"
@search_case = value # sensitive/insensitive/smart
when "backup"
@backup_enabled = value
when "encrypt"
# Handle encryption enabling (would need password prompt)
@encrypt_enabled = value
end
end
# Show message about applied config
if options.any?
# Build message showing what was applied
msg_parts = []
msg_parts << "fold_level=#{@fold_level}" if @fold_level != 99
msg_parts << "theme=#{@theme}" if options["theme"]
msg_parts << "wrap=#{@wrap ? 'yes' : 'no'}" if options.key?("wrap")
msg_parts << "auto_save=#{@auto_save_enabled ? 'yes' : 'no'}" if options.key?("auto_save")
@message = "Applied config: #{msg_parts.join(', ')}" if msg_parts.any?
# Set a longer timeout for config message
@message_timeout = Time.now + 5.0
end
end
def add_to_recent_files(filepath)
return unless filepath && File.exist?(filepath)
# Load existing recent files
recent = load_recent_files
# Remove if already exists and add to front
recent.delete(filepath)
recent.unshift(filepath)
# Keep only last 20 files
recent = recent[0...20]
# Save back to file
File.open(@recent_files_path, 'w') do |f|
recent.each { |path| f.puts(path) }
end
rescue => e
# Silently fail if can't write recent files
end
def load_recent_files
return [] unless File.exist?(@recent_files_path)
File.readlines(@recent_files_path).map(&:strip).select do |path|
File.exist?(path)
end
rescue
[]
end
def load_command_history
history_file = File.expand_path("~/.hyperlist_command_history")
return [] unless File.exist?(history_file)
File.readlines(history_file).map(&:strip).reject(&:empty?).last(100)
rescue
[]
end
# Check if file was modified externally and prompt for reload
# Throttled to only check every 2 seconds to avoid filesystem I/O on every keypress
def check_file_changed
return unless @filename && File.exist?(@filename) && @file_mtime
# Throttle: only check every 2 seconds
now = Time.now
@last_file_check ||= Time.at(0)
return if (now - @last_file_check) < 2
@last_file_check = now
current_mtime = File.mtime(@filename) rescue nil
return unless current_mtime && current_mtime > @file_mtime
# File changed externally - prompt user
@footer.text = "File changed externally. Reload? (y/n): "
@footer.refresh
response = getchr
if response&.downcase == 'y'
# Save cursor position
saved_current = @current
saved_offset = @offset
load_file(@filename)
# Restore cursor position (clamped to new file size)
visible = get_visible_items
@current = [saved_current, visible.length - 1, 0].max
@current = [@current, visible.length - 1].min if visible.length > 0
@offset = saved_offset
@message = "File reloaded"
@modified = false
clear_cache
render
else
# Update mtime to avoid repeated prompts
@file_mtime = current_mtime
@message = "External changes ignored"
end
end
def save_command_history
history_file = File.expand_path("~/.hyperlist_command_history")
File.open(history_file, 'w') do |f|
@command_history.last(100).each { |cmd| f.puts(cmd) }
end
rescue
# Silently fail if can't write history
end
def show_recent_files
recent = load_recent_files
if recent.empty?
@message = "No recent files"
return
end
# Save current state
saved_items = @items.dup
saved_current = @current
saved_offset = @offset
saved_filename = @filename
saved_modified = @modified
saved_presentation_mode = @presentation_mode
# Disable presentation mode for recent files viewer
@presentation_mode = false
# Create items for recent files display
@items = []
@items << {"text" => "RECENT FILES (press Enter to open, q to cancel)", "level" => 0, "fold" => false, "raw" => true}
@items << {"text" => "="*50, "level" => 0, "fold" => false, "raw" => true}
recent.each_with_index do |path, idx|
display_path = path.sub(ENV['HOME'], '~') if ENV['HOME']
display_path ||= path
@items << {"text" => "#{idx+1}. #{display_path}", "level" => 0, "fold" => false, "path" => path, "raw" => true}
end
@current = 2 # Start at first file
@offset = 0
@modified = false
# Recent files viewer loop
loop do
render_main
@footer.text = "Recent Files | Enter: open | q: cancel | j/k: navigate"
@footer.refresh
c = getchr
case c
when "q", "ESC"
# Restore original state
@items = saved_items
@current = saved_current
@offset = saved_offset
@filename = saved_filename
@modified = saved_modified
@presentation_mode = saved_presentation_mode
break
when "j", "DOWN"
move_down if @current < @items.length - 1
when "k", "UP"
move_up if @current > 2 # Don't go above first file
when "ENTER", "l"
if @current >= 2 && @items[@current]["path"]
selected_file = @items[@current]["path"]
if saved_modified
@items = saved_items
@current = saved_current
@offset = saved_offset
@filename = saved_filename
@modified = saved_modified
@presentation_mode = saved_presentation_mode
@message = "Unsaved changes! Save first before opening another file"
break
else
@presentation_mode = saved_presentation_mode
@filename = File.expand_path(selected_file)
load_file(@filename)
@current = 0
@offset = 0
@modified = false
break
end
end
when /^[1-9]$/
# Allow number key selection
idx = c.to_i - 1
if idx < recent.length
selected_file = recent[idx]
if saved_modified
@items = saved_items
@current = saved_current
@offset = saved_offset
@filename = saved_filename
@modified = saved_modified
@presentation_mode = saved_presentation_mode
@message = "Unsaved changes! Save first before opening another file"
break
else
@presentation_mode = saved_presentation_mode
@filename = File.expand_path(selected_file)
load_file(@filename)
@current = 0
@offset = 0
@modified = false
break
end
end
end
end
end
def save_file
return unless @filename
# Prepare content
content = @items.map do |item|
# Handle multi-line items (those with embedded newlines)
if item["text"].include?("\n")
lines = item["text"].split("\n")
first_line = (' ' * @indent_size) * item["level"] + lines[0]
# Continuation lines get the same indent + space prefix
continuation_lines = lines[1..-1].map do |line|
(' ' * @indent_size) * item["level"] + line
end
[first_line, *continuation_lines].join("\n")
else
(' ' * @indent_size) * item["level"] + item["text"]
end
end.join("\n")
# Append config line if present
if @config_line && !@config_line.empty?
# Ensure there's a blank line before config
content += "\n" unless content.end_with?("\n")
content += "\n" + @config_line
else
if @fold_level != 99
# Rebuild config line if we have config settings but no line
update_config_line
if @config_line && !@config_line.empty?
content += "\n" unless content.end_with?("\n")
content += "\n" + @config_line
end
end
end
# Check if this should be an encrypted file
if is_encrypted_file?(@filename) && !content.empty?
# Check if any lines are already encrypted
has_encrypted_lines = @items.any? { |item| item["text"].start_with?("ENC:") }
if !has_encrypted_lines
# Ask if user wants to encrypt the whole file
@footer.text = "Encrypt entire file? (y/n): "
@footer.refresh
response = getchr
if response.downcase == 'y'
encrypted_content = encrypt_file(content)
if encrypted_content
File.write(@filename, encrypted_content)
@message = "File saved (encrypted)"
else
@message = "Encryption cancelled - file not saved"
return
end
else
# Save as plain text even though it's a dot file
File.write(@filename, content)
@message = "Saved to #{@filename} (unencrypted)"
end
else
# Has encrypted lines, save as is
File.write(@filename, content)
@message = "Saved to #{@filename}"
end
else
# Regular file, save normally
File.write(@filename, content)
@message = "Saved to #{@filename}"
end
@modified = false
@original_items = @items.map { |item| item.dup } # Save state after save
@last_auto_save = Time.now if @auto_save_enabled
@file_mtime = File.mtime(@filename) rescue nil # Update mtime after save
end
def check_auto_save
return unless @filename && @modified
if Time.now - @last_auto_save >= @auto_save_interval
save_file
@message = "Auto-saved to #{@filename}"
@last_auto_save = Time.now
end
end
def export_to(format, export_file = nil)
# Generate default filename if not provided
if export_file.nil? || export_file.empty?
base = @filename ? File.basename(@filename, '.*') : 'hyperlist'
extension = case format
when 'md', 'markdown' then '.md'
when 'html' then '.html'
when 'txt', 'text' then '.txt'
when 'latex', 'tex' then '.tex'
when 'pdf' then '.pdf'
end
export_file = base + extension
end
content = case format
when 'md', 'markdown'
export_to_markdown
when 'html'
export_to_html
when 'txt', 'text'
export_to_text
when 'latex', 'tex'
export_to_latex
when 'pdf'
export_to_latex
end
File.open(export_file, 'w') { |f| f.write(content) }
# For PDF, compile the LaTeX file
if format == 'pdf'
tex_file = export_file.sub(/\.pdf$/, '.tex')
File.open(tex_file, 'w') { |f| f.write(content) }
# Compile LaTeX to PDF
@message = "Compiling LaTeX to PDF..."
render_footer
result = system("pdflatex -interaction=nonstopmode -output-directory=#{File.dirname(tex_file)} #{tex_file} > /dev/null 2>&1")
if result
# Run twice for TOC
system("pdflatex -interaction=nonstopmode -output-directory=#{File.dirname(tex_file)} #{tex_file} > /dev/null 2>&1")
@message = "Exported to #{export_file}"
# Clean up auxiliary files
['aux', 'log', 'out', 'toc'].each do |ext|
aux_file = tex_file.sub(/\.tex$/, ".#{ext}")
File.delete(aux_file) if File.exist?(aux_file)
end
else
@message = "PDF compilation failed. Check #{tex_file}"
end
else
@message = "Exported to #{export_file}"
end
rescue => e
@message = "Export failed: #{e.message}"
end
def export_to_markdown
lines = []
@items.each do |item|
text = item["text"]
level = item["level"]
# Convert HyperList bold/italic to Markdown format
# In HyperList: *text* is bold, /text/ is italic, _text_ is underline
# In Markdown: **text** is bold, *text* is italic, no standard underline
# First, temporarily replace escaped characters to avoid conflicts
text = text.gsub('\\*', '\u0001')
.gsub('\\/', '\u0002')
.gsub('\\_', '\u0003')
# Convert HyperList formatting to Markdown
# Bold: *text* -> **text**
text = text.gsub(/\*([^*]+)\*/, '**\1**')
# Italic: /text/ -> *text*
text = text.gsub(/\/([^\/]+)\//, '*\1*')
# Underline: _text_ -> ***text*** (bold+italic as markdown doesn't have underline)
text = text.gsub(/_([^_]+)_/, '***\1***')
# Restore escaped characters
text = text.gsub('\u0001', '\\*')
.gsub('\u0002', '\\/')
.gsub('\u0003', '\\_')
# Convert checkboxes to markdown format
text = text.gsub(/^\[X\]/i, '- [x]')
.gsub(/^\[O\]/, '- [ ] *(in progress)*')
.gsub(/^\[-\]/, '- [ ] *(partial)*')
.gsub(/^\[ \]/, '- [ ]')
.gsub(/^\[_\]/, '- [ ]')
# Handle different levels with proper markdown indentation
if level == 0 && !text.start_with?('- [')
lines << "# #{text}" unless text.empty?
elsif level == 1 && !text.start_with?('- [')
lines << "## #{text}" unless text.empty?
else
# Use spaces for indentation in lists
indent = ' ' * (@indent_size * [level - 2, 0].max)
if text.start_with?('- [')
lines << indent + text
else
lines << indent + "- #{text}"
end
end
end
lines.join("\n")
end
def export_to_html
html = <<~HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>#{@filename ? File.basename(@filename, '.*') : 'HyperList'}</title>
<style>
body {
font-family: 'Courier New', monospace;
margin: 20px;
background-color: white;
color: #333;
white-space: pre;
line-height: 1.3;
}
/* Based on HyperList LaTeX color definitions */
.checked { color: #00cc00; } /* bright green */
.in-progress { color: #00cc00; } /* bright green */
.partial { color: #008800; } /* medium green */
.unchecked { color: #004400; } /* dark green */
.qualifier { color: #008000; } /* green */
.operator { color: #0000cc; font-weight: bold; } /* blue */
.property { color: #cc0000; } /* red */
.reference { color: #800080; } /* violet */
.tag { color: #cc9900; } /* orange */
.timestamp { color: #cc0000; } /* red - it's a property */
.comment { color: #008080; font-style: italic; } /* turquoise */
strong { font-weight: bold; }
em { font-style: italic; }
u { text-decoration: underline; }
</style>
</head>
<body>
HTML
@items.each do |item|
original_text = item["text"]
level = item["level"]
indent = ' ' * (@indent_size * level)
# Process the line
# We'll apply formatting BEFORE escaping HTML entities
text = original_text
# Apply all formatting with placeholder markers
# Use unique markers that won't appear in normal text
# Markdown formatting MUST come first before other replacements
# Bold *text*
text = text.gsub(/\*([^*]+)\*/) do
"\u0001BOLDSTART\u0002#{$1}\u0001BOLDEND\u0002"
end
# Italic /text/
text = text.gsub(/\/([^\/]+)\//) do
"\u0001ITALICSTART\u0002#{$1}\u0001ITALICEND\u0002"
end
# Underline _text_
text = text.gsub(/_([^_]+)_/) do
"\u0001UNDERSTART\u0002#{$1}\u0001UNDEREND\u0002"
end
# Checkboxes at start
text = text.sub(/^\[X\]/i, "\u0001CBCHECKED\u0002")
.sub(/^\[O\]/, "\u0001CBPROGRESS\u0002")
.sub(/^\[-\]/, "\u0001CBPARTIAL\u0002")
.sub(/^\[ \]/, "\u0001CBUNCHECKED\u0002")
.sub(/^\[_\]/, "\u0001CBUNCHECKED2\u0002")
# Timestamps
text = text.gsub(/(\d{4}-\d{2}-\d{2} \d{2}\.\d{2}):/) do
"\u0001TSSTART\u0002#{$1}\u0001TSEND\u0002:"
end
# Qualifiers [text] - but not checkboxes
unless text.include?("\u0001CB")
text = text.gsub(/\[([^\]]+)\]/) do
"\u0001QSTART\u0002[#{$1}]\u0001QEND\u0002"
end
end
# References <text>
text = text.gsub(/<([^>]+)>/) do
"\u0001REFSTART\u0002<#{$1}>\u0001REFEND\u0002"
end
# Properties (Word: )
text = text.gsub(/\b([A-Z][a-z][a-zA-Z]*): /) do
"\u0001PROPSTART\u0002#{$1}: \u0001PROPEND\u0002"
end
# Operators (CAPS:)
text = text.gsub(/\b([A-Z][A-Z]+):/) do
"\u0001OPSTART\u0002#{$1}:\u0001OPEND\u0002"
end
# Hash tags
text = text.gsub(/#(\w+)/) do
"\u0001TAGSTART\u0002##{$1}\u0001TAGEND\u0002"
end
# Now escape HTML entities
text = text.gsub('&', '&')
.gsub('<', '<')
.gsub('>', '>')
.gsub('"', '"')