-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathneoshell.lua
More file actions
executable file
·2280 lines (2010 loc) · 54.4 KB
/
neoshell.lua
File metadata and controls
executable file
·2280 lines (2010 loc) · 54.4 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 lua
package.path = package.path .. ";/home/jadu/.luarocks/share/lua/5.4/?.lua"
package.cpath = package.cpath .. ";/home/jadu/.local/share/luarocks/lib/lua/5.4/?.so"
local lfs_available, lfs = pcall(require, "lfs")
local linenoise_available, linenoise = pcall(require, "linenoise")
local function get_home()
return os.getenv("HOME") or "/"
end
local function set_env(name, value)
if value then
os.execute("export " .. name .. "='" .. value:gsub("'", "'\\''") .. "' >/dev/null 2>&1")
else
os.execute("unset " .. name .. " >/dev/null 2>&1")
end
end
local config = {
prompt = "%u@%h %w $ ",
rprompt = "", -- Right prompt support
aliases = {},
global_aliases = {},
colors = true,
syntax_highlighting = true, -- Syntax highlighting while typing
auto_suggestions = true, -- Grey suggestions from history
fuzzy_completion = true, -- Fuzzy tab completion
auto_cd = true, -- Auto-cd when typing directory
theme = {
base = "#b4befe",
},
cdpath = { ".", "..", "~" },
path = {},
history_file = get_home() .. "/.neoshell_history",
history_size = 500,
syntax_colors = {
command = "green",
argument = "text",
string = "yellow",
variable = "pink",
comment = "overlay0",
error = "red",
suggestion = "overlay0",
},
}
local current_dir = os.getenv("PWD") or get_home()
local dir_stack = { current_dir }
local aliases = {}
local global_aliases = {}
local shell_vars = {}
local jobs = {}
local job_id_counter = 1
local history = {}
local history_index = 0
-- External commands cache for syntax highlighting
local external_commands = {}
local function refresh_external_commands()
external_commands = {}
local handle = io.popen("compgen -c 2>/dev/null | sort -u")
if handle then
for line in handle:lines() do
if line and line ~= "" then
external_commands[line] = true
end
end
handle:close()
end
-- Also add builtins
for cmd, _ in pairs(builtin_cmds or {}) do
external_commands[cmd] = true
end
end
-- Git info cache
local git_info = { branch = "", dirty = false, ahead = 0, behind = 0 }
local function get_git_info()
local handle = io.popen(
"git symbolic-ref --short HEAD 2>/dev/null || git describe --tags --exact-match 2>/dev/null || git rev-parse --short HEAD 2>/dev/null"
)
if handle then
git_info.branch = handle:read("*l") or ""
handle:close()
if git_info.branch ~= "" then
local status_handle = io.popen("git status --porcelain 2>/dev/null | wc -l")
if status_handle then
local dirty_count = tonumber(status_handle:read("*l")) or 0
git_info.dirty = dirty_count > 0
status_handle:close()
end
local ahead_handle = io.popen("git rev-list --count HEAD@{upstream}..HEAD 2>/dev/null || echo 0")
if ahead_handle then
git_info.ahead = tonumber(ahead_handle:read("*l")) or 0
ahead_handle:close()
end
local behind_handle = io.popen("git rev-list --count HEAD..HEAD@{upstream} 2>/dev/null || echo 0")
if behind_handle then
git_info.behind = tonumber(behind_handle:read("*l")) or 0
behind_handle:close()
end
end
end
end
-- Levenshtein distance for typo suggestions
local function levenshtein(a, b)
local len_a, len_b = #a, #b
if len_a == 0 then
return len_b
end
if len_b == 0 then
return len_a
end
local matrix = {}
for i = 0, len_a do
matrix[i] = {}
matrix[i][0] = i
end
for j = 0, len_b do
matrix[0][j] = j
end
for i = 1, len_a do
for j = 1, len_b do
local cost = (a:sub(i, i) == b:sub(j, j)) and 0 or 1
matrix[i][j] = math.min(matrix[i - 1][j] + 1, matrix[i][j - 1] + 1, matrix[i - 1][j - 1] + cost)
end
end
return matrix[len_a][len_b]
end
local function find_closest_command(cmd)
local best_match = nil
local best_distance = math.huge
for known_cmd, _ in pairs(external_commands) do
local dist = levenshtein(cmd, known_cmd)
if dist < best_distance and dist <= 3 then
best_distance = dist
best_match = known_cmd
end
end
return best_match
end
local function get_theme_color(color_name)
local base = config.theme and config.theme.base or "#b4befe"
local r = tonumber(base:sub(2, 3), 16)
local g = tonumber(base:sub(4, 5), 16)
local b = tonumber(base:sub(6, 7), 16)
local adjustments = {
rosewater = { 0, -20, -20 },
flamingo = { 0, -15, -15 },
pink = { 10, -10, 20 },
mauve = { 20, 0, 30 },
red = { 20, -30, -30 },
maroon = { 20, -20, -20 },
peach = { 20, -10, -10 },
yellow = { 30, 10, -20 },
green = { -20, 30, -20 },
teal = { -20, 30, 30 },
sky = { -20, 10, 30 },
sapphire = { -10, 5, 30 },
blue = { 0, 0, 0 },
lavender = { 20, 10, 30 },
text = { 0, -10, -10 },
subtext1 = { -10, -5, -10 },
subtext0 = { -15, -10, -10 },
overlay2 = { -15, -10, -5 },
overlay1 = { -20, -15, -10 },
overlay0 = { -25, -20, -15 },
surface2 = { -30, -25, -20 },
surface1 = { -35, -30, -25 },
surface0 = { -40, -35, -30 },
base = { -50, -45, -40 },
mantle = { -55, -50, -45 },
crust = { -60, -55, -50 },
white = { 30, 30, 30 },
black = { -30, -30, -30 },
reset = { 0, 0, 0 },
bright_red = { 40, -20, -20 },
bright_green = { -20, 40, -20 },
bright_yellow = { 40, 40, -10 },
bright_blue = { -10, -10, 40 },
bright_magenta = { 40, -10, 40 },
bright_cyan = { -10, 40, 40 },
bright_white = { 40, 40, 40 },
}
local adj = adjustments[color_name] or { 0, 0, 0 }
local nr = math.min(255, math.max(0, r + adj[1]))
local ng = math.min(255, math.max(0, g + adj[2]))
local nb = math.min(255, math.max(0, b + adj[3]))
return string.format("38;2;%d;%d;%d", nr, ng, nb)
end
local colors = {}
local function init_colors()
colors = {
rosewater = get_theme_color("rosewater"),
flamingo = get_theme_color("flamingo"),
pink = get_theme_color("pink"),
mauve = get_theme_color("mauve"),
red = get_theme_color("red"),
maroon = get_theme_color("maroon"),
peach = get_theme_color("peach"),
yellow = get_theme_color("yellow"),
green = get_theme_color("green"),
teal = get_theme_color("teal"),
sky = get_theme_color("sky"),
sapphire = get_theme_color("sapphire"),
blue = get_theme_color("blue"),
lavender = get_theme_color("lavender"),
text = get_theme_color("text"),
subtext1 = get_theme_color("subtext1"),
subtext0 = get_theme_color("subtext0"),
overlay2 = get_theme_color("overlay2"),
overlay1 = get_theme_color("overlay1"),
overlay0 = get_theme_color("overlay0"),
surface2 = get_theme_color("surface2"),
surface1 = get_theme_color("surface1"),
surface0 = get_theme_color("surface0"),
base = get_theme_color("base"),
mantle = get_theme_color("mantle"),
crust = get_theme_color("crust"),
white = get_theme_color("white"),
black = get_theme_color("black"),
reset = "0",
bright_red = get_theme_color("bright_red"),
bright_green = get_theme_color("bright_green"),
bright_yellow = get_theme_color("bright_yellow"),
bright_blue = get_theme_color("bright_blue"),
bright_magenta = get_theme_color("bright_magenta"),
bright_cyan = get_theme_color("bright_cyan"),
bright_white = get_theme_color("bright_white"),
}
end
local function c(color)
if not config.colors then
return ""
end
return "\27[" .. colors[color] .. "m"
end
local function expand_tilde(path)
if path:sub(1, 1) == "~" then
if path == "~" then
return get_home()
end
return get_home() .. path:sub(2)
end
return path
end
local function resolve_path(path, silent)
if path == "" then
return get_home()
elseif path == "-" then
return os.getenv("OLDPWD") or get_home()
end
local target = expand_tilde(path)
if lfs_available then
local attr = lfs.attributes(target)
if attr and attr.mode == "directory" then
return target
end
else
local handle = io.popen("test -d '" .. target .. "' 2>/dev/null && echo 'yes'")
if handle then
local result = handle:read("*a"):match("^%s*(.-)%s*$")
handle:close()
if result == "yes" then
return target
end
end
end
if not silent then
for _, p in ipairs(config.cdpath) do
local base = expand_tilde(p)
local full_path = base .. "/" .. path
if lfs_available then
local attr = lfs.attributes(full_path)
if attr and attr.mode == "directory" then
return full_path
end
else
local handle = io.popen("test -d '" .. full_path .. "' 2>/dev/null && echo 'yes'")
if handle then
local result = handle:read("*a"):match("^%s*(.-)%s*$")
handle:close()
if result == "yes" then
return full_path
end
end
end
end
end
return target
end
local function load_history()
local file = io.open(config.history_file, "r")
if not file then
return
end
for line in file:lines() do
if line ~= "" then
table.insert(history, line)
end
end
file:close()
if #history > config.history_size then
local new_history = {}
for i = #history - config.history_size + 1, #history do
table.insert(new_history, history[i])
end
history = new_history
end
history_index = #history + 1
end
local function save_history()
local file = io.open(config.history_file, "w")
if not file then
return
end
for _, line in ipairs(history) do
file:write(line .. "\n")
end
file:close()
end
local function add_to_history(line)
line = line:gsub("^%s+", ""):gsub("%s+$", "")
if line == "" then
return
end
if history[#history] == line then
return
end
table.insert(history, line)
history_index = #history + 1
if #history > config.history_size then
table.remove(history, 1)
history_index = #history + 1
end
end
local function history_search(search_str)
for i = #history, 1, -1 do
if history[i]:match(search_str) then
return history[i], i
end
end
return nil
end
-- Config parsers for different formats
local function parse_toml(content)
local result = {}
local current_section = result
local in_array = false
local array_name = nil
local array_values = {}
for line in content:gmatch("[^\r\n]+") do
line = line:gsub("%s*#.*$", "") -- Remove comments
line = line:gsub("^%s+", ""):gsub("%s+$", "") -- Trim
if line == "" then goto continue end
-- Section headers
local section = line:match("^%[([^%]]+)%]$")
if section then
if array_name then
current_section[array_name] = array_values
array_name = nil
array_values = {}
end
result[section] = result[section] or {}
current_section = result[section]
goto continue
end
-- Arrays like aliases = ["ll = ls -la", "la = ls -a"]
local array_start = line:match("^(%w+)%s*=%s*%[")
if array_start then
array_name = array_start
in_array = true
array_values = {}
local values = line:match("%[(.*)%]")
if values then
for val in values:gmatch('"([^"]+)"') do
table.insert(array_values, val)
end
current_section[array_name] = array_values
array_name = nil
in_array = false
end
goto continue
end
-- Inline tables like theme = { base = "#b4befe" }
local key, inline_table = line:match("^(%w+)%s*=%s*{(.+)}")
if key and inline_table then
local tbl = {}
for k, v in inline_table:gmatch("(%w+)%s*=%s*\"?([^\"},]+)\"?") do
tbl[k] = v:gsub("^%s+", ""):gsub("%s+$", "")
end
current_section[key] = tbl
goto continue
end
-- Key-value pairs
local key, value = line:match("^([^=]+)%s*=%s*(.+)$")
if key then
key = key:gsub("^%s+", ""):gsub("%s+$", "")
value = value:gsub("^%s+", ""):gsub("%s+$", "")
-- Remove quotes
if value:match("^%'") and value:match("%'.$") then
value = value:sub(2, -2)
elseif value:match('^"') and value:match('"$') then
value = value:sub(2, -2)
elseif value == "true" then
value = true
elseif value == "false" then
value = false
elseif tonumber(value) then
value = tonumber(value)
end
-- Handle nested keys like syntax_colors.command
local parent, child = key:match("^([^.]+)%.(.+)$")
if parent then
result[parent] = result[parent] or {}
result[parent][child] = value
else
result[key] = value
end
end
::continue::
end
return result
end
local function parse_yaml(content)
-- Simple YAML parser (subset)
local result = {}
local current_section = nil
local indent_stack = {}
for line in content:gmatch("[^\r\n]+") do
-- Skip comments and empty lines
if line:match("^%s*#") or line:match("^%s*$") then goto continue end
local indent = #line:match("^( *)")
line = line:gsub("^%s+", ""):gsub("%s+$", "")
-- Remove inline comments
line = line:gsub("%s*#.*$", "")
-- Section
if line:match("^%w+:$") then
local section = line:gsub(":", "")
result[section] = {}
current_section = result[section]
goto continue
end
-- Array item under current section
if current_section and line:match("^%- ") then
local value = line:gsub("^%- ", "")
value = value:gsub("^%s*\"?", ""):gsub("\"?%s*$", "")
if not current_section.array then
current_section.array = {}
end
table.insert(current_section.array, value)
goto continue
end
-- Key-value pairs
local key, value = line:match("^([^:]+):%s*(.+)$")
if key then
key = key:gsub("^%s+", ""):gsub("%s+$", "")
value = value:gsub("^%s+", ""):gsub("%s+$", "")
-- Handle "key: [" or "key: {" starts
if value == "[" then
if current_section then
current_section[key] = {}
else
result[key] = {}
end
goto continue
end
-- Remove quotes
if value:match("^%'") and value:match("%'.$") then
value = value:sub(2, -2)
elseif value:match('^"') and value:match('"$') then
value = value:sub(2, -2)
elseif value == "true" then
value = true
elseif value == "false" then
value = false
elseif tonumber(value) then
value = tonumber(value)
end
if current_section then
-- Parse alias definitions
if key == "aliases" or key == "global_aliases" then
local alias_key, alias_val = value:match("^(%S+)%s*=%s*(.+)$")
if alias_key then
if type(current_section) == "table" then
if not current_section[key] then
current_section[key] = {}
end
current_section[key][alias_key] = alias_val
end
else
current_section[key] = value
end
else
current_section[key] = value
end
else
result[key] = value
end
end
::continue::
end
return result
end
local function parse_json(content)
-- Very basic JSON parser for simple config
local result = {}
-- Remove whitespace
content = content:gsub("%s+", " ")
-- Parse top-level object
for key, value in content:gmatch('"([^"]+)":%s*([^,{]+)') do
value = value:gsub("^%s+", ""):gsub("%s+$", "")
if value:match('^"') then
value = value:gsub('"', "")
elseif value == "true" then
value = true
elseif value == "false" then
value = false
elseif tonumber(value) then
value = tonumber(value)
end
result[key] = value
end
-- Parse arrays
for key, arr_content in content:gmatch('"([^"]+)":%s*(%[[^%]]+%])') do
local arr = {}
for val in arr_content:gmatch('"([^"]+)"') do
table.insert(arr, val)
end
result[key] = arr
end
-- Parse nested objects (simple)
for key, obj_content in content:gmatch('"([^"]+)":%s*({[^}]+})') do
local obj = {}
for k, v in obj_content:gmatch('"([^"]+)":%s*"?([^",}]+)"?') do
obj[k] = v
end
result[key] = obj
end
return result
end
local function parse_ini(content)
local result = {}
local current_section = result
for line in content:gmatch("[^\r\n]+") do
line = line:gsub("%s*;.*$", ""):gsub("^%s+", ""):gsub("%s+$", "")
if line == "" then goto continue end
-- Section
local section = line:match("^%[([^%]]+)%]$")
if section then
if section == "aliases" then
result.aliases = {}
current_section = result.aliases
elseif section == "global_aliases" then
result.global_aliases = {}
current_section = result.global_aliases
elseif section == "theme" then
result.theme = {}
current_section = result.theme
elseif section == "syntax_colors" then
result.syntax_colors = {}
current_section = result.syntax_colors
else
result[section] = result[section] or {}
current_section = result[section]
end
goto continue
end
-- Key-value pairs
local key, value = line:match("^([^=]+)%s*=%s*(.+)$")
if key then
key = key:gsub("^%s+", ""):gsub("%s+$", "")
value = value:gsub("^%s+", ""):gsub("%s+$", "")
-- Handle quotes
if value:match('^"') and value:match('"$') then
value = value:sub(2, -2)
elseif value:match("^%'") and value:match("%'.$") then
value = value:sub(2, -2)
elseif value == "true" then
value = true
elseif value == "false" then
value = false
elseif tonumber(value) then
value = tonumber(value)
end
current_section[key] = value
end
::continue::
end
return result
end
local function load_config()
local home = get_home()
local config_files = {
{ path = home .. "/.shell.toml", parser = parse_toml },
{ path = home .. "/.shell.yaml", parser = parse_yaml },
{ path = home .. "/.shell.yml", parser = parse_yaml },
{ path = home .. "/.shell.json", parser = parse_json },
{ path = home .. "/.shell.conf", parser = parse_ini },
{ path = home .. "/.shellrc", parser = parse_ini },
{ path = home .. "/.neoshell", parser = nil }, -- Lua format, backward compatible
}
local loaded_config = nil
local loaded_path = nil
for _, cfg in ipairs(config_files) do
local file = io.open(cfg.path, "r")
if file then
local content = file:read("*all")
file:close()
if cfg.parser then
local success, result = pcall(cfg.parser, content)
if success then
loaded_config = result
loaded_path = cfg.path
break
else
print("Error parsing " .. cfg.path .. ": " .. tostring(result))
end
else
-- Lua format
local env = {}
setmetatable(env, { __index = _G })
local chunk, err = load(content, cfg.path, "t", env)
if chunk then
local ok, result = pcall(chunk)
if ok and type(result) == "table" then
loaded_config = result
loaded_path = cfg.path
break
end
end
end
end
end
if not loaded_config then
return
end
-- Apply loaded config
if loaded_config.prompt then
config.prompt = loaded_config.prompt
end
if loaded_config.aliases then
config.aliases = loaded_config.aliases
end
if loaded_config.global_aliases then
config.global_aliases = loaded_config.global_aliases
end
if loaded_config.colors ~= nil then
config.colors = loaded_config.colors
end
if loaded_config.theme then
config.theme = loaded_config.theme
end
if loaded_config.cdpath then
config.cdpath = loaded_config.cdpath
end
if loaded_config.history_file then
config.history_file = loaded_config.history_file
end
if loaded_config.history_size then
config.history_size = loaded_config.history_size
end
if loaded_config.rprompt then
config.rprompt = loaded_config.rprompt
end
if loaded_config.syntax_highlighting ~= nil then
config.syntax_highlighting = loaded_config.syntax_highlighting
end
if loaded_config.auto_suggestions ~= nil then
config.auto_suggestions = loaded_config.auto_suggestions
end
if loaded_config.fuzzy_completion ~= nil then
config.fuzzy_completion = loaded_config.fuzzy_completion
end
if loaded_config.auto_cd ~= nil then
config.auto_cd = loaded_config.auto_cd
end
if loaded_config.syntax_colors then
for k, v in pairs(loaded_config.syntax_colors) do
config.syntax_colors[k] = v
end
end
-- Source additional config files
if loaded_config.source and loaded_config.source.files then
for _, file in ipairs(loaded_config.source.files) do
local expanded_path = file:gsub("^~", home)
local f = io.open(expanded_path, "r")
if f then
local content = f:read("*all")
f:close()
local env = {}
setmetatable(env, { __index = _G })
local chunk, err = load(content, expanded_path, "t", env)
if chunk then
pcall(chunk)
end
end
end
end
aliases = config.aliases
global_aliases = config.global_aliases
end
local function format_prompt()
local prompt = config.prompt
local username = os.getenv("USER") or os.getenv("USERNAME") or "user"
local hostname = os.getenv("HOSTNAME") or "localhost"
local git_str = ""
-- Update git info
get_git_info()
if git_info.branch ~= "" then
git_str = c("mauve") .. "(" .. git_info.branch .. ")" .. c("reset")
if git_info.dirty then
git_str = git_str .. c("yellow") .. "*" .. c("reset")
end
if git_info.ahead > 0 then
git_str = git_str .. c("green") .. "↑" .. git_info.ahead .. c("reset")
end
if git_info.behind > 0 then
git_str = git_str .. c("red") .. "↓" .. git_info.behind .. c("reset")
end
git_str = git_str .. " "
end
-- Get short directory name
local short_dir = current_dir
if short_dir == get_home() then
short_dir = "~"
else
-- Replace home with ~ in path
short_dir = short_dir:gsub("^" .. get_home(), "~")
end
prompt = prompt:gsub("%%u", username)
prompt = prompt:gsub("%%h", hostname)
prompt = prompt:gsub("%%w", short_dir)
prompt = prompt:gsub("%%%%", "%%") -- Replace %% with % (escaped properly)
-- Add git branch placeholder
prompt = prompt:gsub("%%g", git_info.branch ~= "" and git_info.branch or "")
if config.colors then
-- Build colored prompt
local prompt_parts = {}
local i = 1
while i <= #prompt do
if prompt:sub(i, i) == "%" then
local code = prompt:sub(i+1, i+1)
if code == "n" then
table.insert(prompt_parts, c("blue") .. username .. c("reset"))
i = i + 2
elseif code == "m" then
table.insert(prompt_parts, c("mauve") .. hostname .. c("reset"))
i = i + 2
elseif code == "~" then
table.insert(prompt_parts, c("green") .. short_dir .. c("reset"))
i = i + 2
elseif code == "g" then
if git_info.branch ~= "" then
table.insert(prompt_parts, c("mauve") .. "(" .. git_info.branch .. ")" .. c("reset"))
if git_info.dirty then
table.insert(prompt_parts, c("yellow") .. "*" .. c("reset"))
end
end
i = i + 2
elseif code == "#" then
table.insert(prompt_parts, c("red") .. "#" .. c("reset"))
i = i + 2
elseif code == "$" then
table.insert(prompt_parts, c("yellow") .. "$" .. c("reset"))
i = i + 2
elseif code == "%" then
table.insert(prompt_parts, "%")
i = i + 2
else
table.insert(prompt_parts, prompt:sub(i, i))
i = i + 1
end
else
table.insert(prompt_parts, prompt:sub(i, i))
i = i + 1
end
end
prompt = table.concat(prompt_parts)
end
return prompt
end
local function format_rprompt()
local rprompt = config.rprompt
if rprompt == "" then
return ""
end
local username = os.getenv("USER") or os.getenv("USERNAME") or "user"
local hostname = os.getenv("HOSTNAME") or "localhost"
local time_str = os.date("%H:%M")
rprompt = rprompt:gsub("%%u", username)
rprompt = rprompt:gsub("%%h", hostname)
rprompt = rprompt:gsub("%%w", current_dir)
rprompt = rprompt:gsub("%%t", time_str)
rprompt = rprompt:gsub("%%%", "%%")
if config.colors then
rprompt = c("overlay0") .. rprompt .. c("reset")
end
return rprompt
end
local builtin_cmds = {
cd = true,
pwd = true,
exit = true,
help = true,
echo = true,
printf = true,
test = true,
export = true,
alias = true,
unalias = true,
source = true,
set = true,
unset = true,
pushd = true,
popd = true,
dirs = true,
jobs = true,
fg = true,
bg = true,
type = true,
["true"] = true,
["false"] = true,
return_builtin = true,
}
local function fuzzy_match(str, pattern)
if not config.fuzzy_completion then
return str:sub(1, #pattern) == pattern
end
local pattern_idx = 1
local str_idx = 1
while pattern_idx <= #pattern and str_idx <= #str do
if pattern:sub(pattern_idx, pattern_idx):lower() == str:sub(str_idx, str_idx):lower() then
pattern_idx = pattern_idx + 1
end
str_idx = str_idx + 1
end
return pattern_idx > #pattern
end
local function get_command_completions(prefix)
local matches = {}
for cmd, _ in pairs(builtin_cmds) do
if cmd ~= "return_builtin" and fuzzy_match(cmd, prefix) then
table.insert(matches, cmd)
end
end
for cmd, _ in pairs(aliases) do
if fuzzy_match(cmd, prefix) then
table.insert(matches, cmd)
end
end
local handle = io.popen("compgen -c 2>/dev/null || echo ''")
if handle then
for line in handle:lines() do
if line and fuzzy_match(line, prefix) then
local found = false
for _, m in ipairs(matches) do
if m == line then
found = true
break
end
end
if not found then
table.insert(matches, line)
end
end
end
handle:close()
end
return matches
end
local function get_path_completions(prefix)
local matches = {}
local dir = current_dir
local search_prefix = prefix
if prefix:match("^~/") then
dir = get_home()
search_prefix = prefix:sub(3)
elseif prefix:sub(1, 1) == "~" then
dir = get_home()
search_prefix = prefix:sub(2)
elseif prefix:match("^%./") then
dir = current_dir
search_prefix = prefix:sub(3)
elseif prefix:match("^%/") then
dir = "/"
search_prefix = prefix:sub(2)
else
local last_slash = prefix:match(".*/")
if last_slash then
dir = current_dir .. "/" .. last_slash
search_prefix = prefix:match("([^/]+)$") or ""
end
end