-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshow
More file actions
executable file
·541 lines (472 loc) · 15 KB
/
Copy pathshow
File metadata and controls
executable file
·541 lines (472 loc) · 15 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
#!/usr/bin/env nu
#
# SPDX-FileCopyrightText: 2025-present jochumdev <rene@jochum.dev>
#
# SPDX-License-Identifier: MIT OR Apache-2.0
use std/log
let renderers = {
"kitten_icat": {
"required_cmds": ["kitten" "sed"]
"check_terminals": true
"renderer": {|config, term, jump_to|
let term_size = (term size)
let c = ($env.FZF_PREVIEW_COLUMNS? | default $term_size.columns | into int)
let l = ($env.FZF_PREVIEW_LINES? | default $term_size.rows | into int)
# This comment is from `fzf-preview.sh`
# 1. 'memory' is the fastest option but if you want the image to be scrollable,
# you have to use 'stream'.
#
# 2. The last line of the output is the ANSI reset code without newline.
# This confuses fzf and makes it render scroll offset indicator.
# So we remove the last line and append the reset code to its previous line.
let dim = $"($c)x($l)"
kitten icat --clear --transfer-mode=memory --unicode-placeholder --stdin=no --place=$"($dim)@0x0" $in | sed '$d'
}
}
"imgcat": {
"required_cmds": ["imgcat"]
"renderer": {|config, term, jump_to|
let term_size = (term size)
let c = ($env.FZF_PREVIEW_COLUMNS? | default $term_size.columns | into int)
let l = ($env.FZF_PREVIEW_LINES? | default $term_size.rows | into int)
# TODO(jochumdev): this is completly untested.
#
# This comment is from `fzf-preview.sh`
# NOTE: We should use https://iterm2.com/utilities/it2check to check if the
# user is running iTerm2. But for the sake of simplicity, we just assume
# that's the case here.
imgcat -W $c -H $l $in
}
}
"chafa": {
"required_cmds": ["chafa"]
"renderer": {|config, term, jump_to|
let term_size = (term size)
let c = ($env.FZF_PREVIEW_COLUMNS? | default $term_size.columns | into int)
let l = ($env.FZF_PREVIEW_LINES? | default $term_size.rows | into int)
let dim = (
if (($env.FZF_PREVIEW_TOP? | default 0 | into int) + $l == $term_size.columns) {
# Avoid scrolling issue when the Sixel image touches the bottom of the screen
# * https://github.com/junegunn/fzf/issues/2544
$"($c)x(($l - 1))"
} else {
$"($c)x($l)"
}
)
chafa -s $dim $in
}
}
"sed": {
"required_cmds": ["sed"]
"renderer": {|config, term, jump_to|
if ($jump_to != 0) {
let pstart = [($jump_to - 10) 1] | math max
let pend = $pstart + $env.FZF_PREVIEW_LINES
sed --quiet $"($pstart),($pend)p" $in
} else {
sed --quiet "1,200p" $in
}
}
}
"bat": {
"required_cmds": ["bat", "less"]
"renderer": {|config, term, jump_to|
let $file = $in
let term_size = (term size)
let l = ($env.FZF_PREVIEW_LINES? | default $term_size.rows | into int)
let pstart = [($jump_to - 10) 1] | math max
if ($env.FZF_LINES? | default "") != "" {
let pend = $pstart + $l
log debug $"Running bat in fzf mode, line-range: '($pstart):($pend)'"
bat --style $"($config.renderers.bat.fzf_style)" --color $"($config.renderers.bat.fzf_color)" --pager "never" --line-range $"($pstart):($pend)" --highlight-line $jump_to -- $file
} else {
let pager = $'less +G($pstart) -RF'
log debug $"Running bat in Less mode, pager: '($pager)'"
bat --pager $pager --highlight-line $jump_to -- $file
}
}
}
"cat": {
"required_cmds": ["cat"]
"renderer": {|config, term, jump_to|
cat $in
}
}
"nu-highlight": {
"required_cmds": ["nu-highlight"]
"renderer": {|config, term, jump_to|
open --raw $in | nu-highlight | print
}
}
}
# The show config.
#
# with this first /usr/bin/file tells me this text/plain
# when here its text/x-script.python ...
def get-config [
]: nothing -> record {
let defaults = {
# Per command config/defaults
"commands": {
"main": {
# glob patterns (help glob) to search for, first match wins.
"patterns": [
"(?i)readme*"
"(?i)*.md"
"(?i)*.rst"
"(?i)*.toml"
]
# Excludes for all the patterns above.
"excludes": [
"**/target/**"
"**/.git/**"
]
}
"search": {
"opener": "nvim"
"line_openers": [
"helix"
"hx"
]
}
}
# Mime to renderer map. The order matters!
"mimegroups": [
{
"mimes": ["application/x-nuscript", "application/x-nuon", "text/x-nushell", "application/json"]
"renderers": ["nu-highlight", "bat", "sed", "cat"]
}
{
"mimes": ["application", "text"]
"renderers": ["bat", "sed", "cat"]
}
{
"mimes": ["image"]
"renderers": ["kitten_icat", "imgcat", "chafa"]
}
]
"renderers": {
"kitten_icat": {
# Runs only in these terminals
"terms": [
"kitty"
"ghostty"
]
}
"bat": {
# Only in fzf mode applied.
"fzf_style": "full" # man bat -> "--style"
"fzf_color": "always" # man bat -> "--color"
}
}
}
if not ($env.XDG_CONFIG_HOME? | is-empty) {
if ($"($env.XDG_CONFIG_HOME?)/show/config.toml" | path exists) {
let cp = $"($env.XDG_CONFIG_HOME?)/show/config.toml"
log debug $"Found config '($cp)', loading it"
let usercfg = (open --raw $cp | from toml)
return ($defaults | merge deep $usercfg --strategy=prepend)
}
}
return $defaults
}
# Check if all cmds (external or internal) are available.
# returns true if so else false
def check-cmds [
]: list<string> -> bool {
$in | all {|cmd| which $cmd | is-not-empty }
}
def fallback-ls [
reason: string = "unknown"
]: path -> any {
print --stderr $"WARNING: In fallback-ls, reason: ($reason)"
ls ($in | path expand)
}
def run-renderers [
wanted: list<string>
config: record
term: string
jump_to_line: int
]: path -> binary {
let file = $in
# Get renderers we known about, silently ignore others.
let matched = $wanted | where {|x| $x in $renderers}
for x in $matched {
let $fmt = $renderers | get $x
let $fmt_cfg = $config.renderers | get -o $x | default {}
# Check terminals if needed.
if ($fmt.check_terminals? | default false) {
let terms = $fmt_cfg | get -o "terms"
if ($terms | is-empty) {
log warning $"Skipping '($x)', found an invalid config, the renderers is configured to check terminals and the config doesnt have any"
continue
}
if not ($term in $terms) {
log debug $"Skipping '($x)', isnt compatible with term '($term)', it is compatible with '($terms | str join ' ')'"
continue
}
}
# Check required cmds
if not ($fmt.required_cmds | check-cmds) {
log debug $"Skipping '($x)', not all required cmds are available, cmds '($fmt.required_cmds | str join ' ')'"
continue
}
log debug $"Running renderer '($x)'"
$file | do -c $fmt.renderer $config $term $jump_to_line
return
}
error make {msg: $"No renderer matched for '($file)'"}
return null
}
def show-file [
config: record
jump_to_line: int
]: path -> binary {
let file = ($in | path expand)
mut term = ($env.TERM? | default "unknown")
if ($env.KITTY_WINDOW_ID? | is-not-empty) {
$term = "kitty"
}
# Using `file` to get the mime if available its resolution is better.
let mime = (if (["file"] | check-cmds) {
(file --brief --dereference --mime -- $file | split row ';' | first)
} else {
ls -m $file | get type
})
log debug $"Detected mime '($mime)' and term '($term)'"
let type = $mime | split row '/' | first
let flattened_mimes = ($config.mimegroups
| reduce -f {} {|it acc|
$it.mimes
| reduce -f $acc {|m acc2|
$acc2 | upsert $m $it.renderers
}
}
)
# Try direct match, then type match, else fail
let renderers = $flattened_mimes | get -o $mime | default ($flattened_mimes | get -o $type | default null)
if ($renderers == null) {
error make {msg: "Unknown mime", labels: {text: $"Mime '($mime)' is unknown for file '($file)'", span: (metadata $mime).span}}
}
$file | run-renderers $renderers $config $term $jump_to_line
}
def find-file [
patterns: list<oneof<string, glob>>
excludes: list<string>
]: path -> path {
let dir = ($in | path expand)
let found = (
$patterns
| each {|pattern|
glob (
[$dir $"($pattern)"]
| path join
) --no-dir --follow-symlinks --exclude $excludes
}
| where {|x|
$x
| is-not-empty
}
)
if ($found | is-empty) {
error make {msg: "None of the glob patterns matched"}
}
$found | first | first
}
# Renders a file from a directory or directly a file.
# It is able to render images and highlights text with bat in your terminal.
#
# Also it works as preview command for fzf with `--preview "show {}"`
#
# If the argument is a directory it searches for known files (you can
# customize that with env vars or parameters).
#
# If path is a file (or a file has been found):
#
# - `Image`: try to render or Sixl it.
#
# Rendering is only supported for kitty and ghosty,
# other terminals will Sixl the image.
#
# - `Binary`: just show the path
#
# - `everything else`: use bat or cat to render it.
#
# For list of environment vars please take a look at the first lines of
# the script.
def main [
path: path # Input either a single directory or file.
--glob (-g) # Enable globing for directories, usefull inside fzf with directories as input.
--patterns: list<oneof<string, glob>> # Find patterns for globing, (ENV: SHOW_FIND_PATTERNS)
--excludes: list<string> # Find excludes for globing (ENV: SHOW_FIND_EXCLUDES)
--jump-to-line (-j): string = "0" # Jump to line x
--debug (-d) # Enable debug logging
]: nothing -> binary {
if $debug {
log set-level (log log-level).DEBUG
}
let config = get-config
let find_patterns = $patterns | default $env.SHOW_FIND_PATTERNS? | default $config.commands.main.patterns
let find_excludes = $excludes | default $env.SHOW_FIND_EXCLUDES? | default $config.commands.main.excludes
if not ($path | path exists) {
error make {msg: $"Path '($path)' not found"}
}
# Parse "''" which is passed when we have '-j "{2}"' as FZF_DEFAULT_OPTS but no line.
let m_jump = (if ($jump_to_line | parse -r "([0-9]+)" | is-not-empty) {
$jump_to_line | parse -r "([0-9]+)" | first | $in.capture0 | into int
} else {
0
})
log debug $"Checking '($path)', type '($path | path type)'"
let c = {||
let file = (match ($path | path expand | path type) {
"file" => {
$path
}
"dir" => {
if not ($glob) {
ls $path | print
exit 0
}
$path | find-file $find_patterns $find_excludes
}
})
$file | show-file $config $m_jump
}
# no fallback in debug (wanna see the error)
if $debug {
do -c $c
} else {
try {
do -c $c
} catch {|err|
$path | fallback-ls $err.msg
}
}
}
# Search with `rg` <> `fzf` | open.
#
# Examples:
#
# Just walk files with rg, let fzf do the fuzzy search work:
#
# `show search -g '**/*.nu'`
#
# The above with a different working directory:
#
# `show search -d ~/vendor/nushell/nu_scripts -g '**/*.nu'`
#
# Search for "run-external" in all .nu files:
#
# `show search -g '**/*.nu' 'run-external'`
#
# Search for .nu files multi-line:
#
# `show search -g '**/*.nu' -m '# Update.*\n.*def --env'`
#
# Used fixed strings (search for regex patterns for example):
#
# `show search -F 'hello.*'`
#
# Enable auto-reload (fzf will execute rg on each change in the prompt):
#
# `show search -F -a initial`
#
# Tip: When it is not working right enable "--debug". After you close the fzf tui
# with --debug enabled you will see the output.
def --env "main search" [
query: string = ""
--working-directory (-d): path = "" # Directory to search and open in
--opener (-o): string # Editor/opener to use (default: $env.SHOW_SEARCH_OPENER then "nvim")
--debug (-d) # Enable debug logging
--auto-reload (-a) # Run ripgrep on each query change
--fixed-strings (-F) # Use fixed strings with ripgrep
--glob (-g): string = "" # Glob file names with ripgrep
--multi-line (-m) # Enable ripgreps multi-line search
]: nothing -> nothing {
if $debug {
log set-level (log log-level).DEBUG
}
# load env / config
let $config = get-config
let m_opener = $opener | default $env.SHOW_SEARCH_OPENER? | default $config.commands.search.opener
# Openers that support the "file:line" syntax
let line_openers = $env.SHOW_SEARCH_LINE_OPENERS? | default $config.commands.search.line_openers
log debug $"Opener is: ($m_opener)"
# Needed for fzf
$env.SHELL = $nu.current-exe
mut rg_args = [
"--pretty"
"--color" "always"
"--line-number"
"--no-heading"
"--smart-case"
]
if $glob != "" {
$rg_args = [...$rg_args "--glob" $"($glob)"]
}
if $fixed_strings {
$rg_args = [...$rg_args "--fixed-strings"]
}
if $multi_line {
$rg_args = [...$rg_args "--multiline"]
}
let reload = $"rg ($rg_args | each {|arg| $"'($arg)'"} | str join ' ') {q}"
# Use this script as previewer with globs enabled (for directories), jumps enabled
# Fzf replaces {2} with the line number
# and {1} with the file.
let preview = $"($env.CURRENT_FILE) -g -j ' {2} ' {1}"
mut fzf_args = [
"--bind" 'ctrl-a:select-all,ctrl-d:deselect-all,ctrl-/:toggle-preview'
"--with-shell" $"($nu.current-exe) -c"
"--prompt" "Filter > "
"--ansi"
"--multi"
"--color" "hl:-1:underline,hl+:-1:underline:reverse"
"--delimiter" ":"
"--preview" $preview
]
if $auto_reload {
$fzf_args = [
"--header" 'CTRL-A to select all, CTRL-D to deselect all and CTRL-/ to toggle the preview'
"--bind" $"change:reload:($reload)"
"--query" $"($query)"
...$fzf_args
]
} else {
$fzf_args = [
"--header" 'Press CTRL-R to run the query again, CTRL-A to select all, CTRL-D to deselect all and CTRL-/ to toggle the preview'
"--bind" $"ctrl-r:reload:($reload)"
...$fzf_args
]
}
log debug $"rg cmdline: rg ($rg_args | each {|arg| $"'($arg)'"} | str join ' ') '($query)'"
log debug $"fzf cmdline: fzf ($fzf_args | each {|arg| $"'($arg)'"} | str join ' ')"
if ($working_directory | is-not-empty) {
cd --physical $working_directory
}
# The actual call
let results = rg ...($rg_args) $query
| fzf ...($fzf_args)
| lines | each {|line| $line | split row ':' }
# Convert into file list either "<file>:<line>" or "<file>"
let files = (
if ($m_opener in $line_openers) {
$results | each { $"($in.0):($in.1)" }
} else {
$results | each { first }
}
)
if ($files | is-empty) {
print --stderr "No results"
exit 1
}
# Open external/internal.
# The is-empty gives a nice error with run-external,
# do gives a cryptic error for end users in this case.
if (which $m_opener | is-empty) or (which $m_opener | $in.type | first) == "external" {
run-external $m_opener ...$files
} else {
do $m_opener ...$files
}
}