par-term 0.45.2

Cross-platform GPU-accelerated terminal emulator with inline graphics support (Sixel, iTerm2, Kitty)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
#!/bin/sh
# pt-imgcat — Display inline images in par-term
#
# Uses iTerm2 OSC 1337 File protocol (default) or Kitty graphics protocol
# to display images directly in the terminal.
#
# Usage:
#   pt-imgcat [options] <file>
#   pt-imgcat [options] -          # read from stdin
#   cat image.png | pt-imgcat
#
# Options:
#   --format <iterm2|kitty>        Graphics protocol (default: iterm2)
#   --width <N>                    Width in cells or pixels (e.g., 80, 400px)
#   --height <N>                   Height in cells or pixels
#   --preserve-aspect-ratio        Maintain aspect ratio (default: yes)
#   --no-preserve-aspect-ratio     Allow stretching
#
# Kitty format prefers PNG; non-PNG (JPEG/GIF/WebP) is auto-converted
# via sips (macOS) or ImageMagick convert when available.
# Kitty format rejects pixel-unit width/height (cells only).
#
# Requirements: iterm2 mode needs base64, wc, printf, cat, basename.
# kitty mode additionally uses fold, awk, tr, mktemp, and sips or convert.

set -e

# Detect tmux/screen for passthrough wrapping
_pt_is_tmux() {
    case "$TERM" in
        screen*|tmux*) return 0 ;;
        *) return 1 ;;
    esac
}

# Print escape sequence with optional tmux passthrough
_pt_print_osc() {
    if _pt_is_tmux; then
        printf '\033Ptmux;\033'
    fi
    printf '\033]'
}

_pt_print_st() {
    printf '\007'
    if _pt_is_tmux; then
        printf '\033\\'
    fi
}

# Get image pixel dimensions as "width height".
# Returns empty string on failure.
_pt_image_dims() {
    _f="$1"
    if [ ! -f "$_f" ]; then
        return
    fi
    # macOS: sips is always available
    if command -v sips >/dev/null 2>&1; then
        _w=$(sips --getProperty pixelWidth "$_f" 2>/dev/null | awk '/pixelWidth/{print $2}')
        _h=$(sips --getProperty pixelHeight "$_f" 2>/dev/null | awk '/pixelHeight/{print $2}')
        if [ -n "$_w" ] && [ -n "$_h" ]; then
            printf '%s %s' "$_w" "$_h"
            return
        fi
    fi
    # ImageMagick
    if command -v identify >/dev/null 2>&1; then
        _dims=$(identify -format '%w %h' "$_f" 2>/dev/null)
        if [ -n "$_dims" ]; then
            printf '%s' "$_dims"
            return
        fi
    fi
    # file(1) — parse "NNN x NNN" from output (works for PNG, JPEG, GIF)
    if command -v file >/dev/null 2>&1; then
        _pair=$(file "$_f" 2>/dev/null | grep -oE '[0-9]+ x [0-9]+' | head -1)
        if [ -n "$_pair" ]; then
            printf '%s' "$_pair" | sed 's/ x / /'
            return
        fi
    fi
}

# After displaying an image inside tmux, advance tmux's cursor so the
# shell prompt appears below the image (tmux's virtual terminal doesn't
# see passthrough content, so its cursor stays put).
_pt_tmux_advance_cursor() {
    _rows_to_advance="$1"
    if [ "$_rows_to_advance" -le 0 ] 2>/dev/null; then
        return
    fi
    _i=0
    while [ "$_i" -lt "$_rows_to_advance" ]; do
        printf '\n'
        _i=$((_i + 1))
    done
}


# Check if base64 data starts with a PNG header.
# PNG magic \x89PNG\r\n\x1a\n base64-encodes to iVBORw0KGgo...
_pt_is_png_b64() {
    _b="$1"
    case "$_b" in
        iVBORw0KGgo*) return 0 ;;
        *) return 1 ;;
    esac
}

# Print APC start with optional tmux DCS passthrough.
# tmux doubles every ESC inside the passthrough wrapper.
_pt_print_apc() {
    if _pt_is_tmux; then
        printf '\033Ptmux;\033\033_G'
    else
        printf '\033_G'
    fi
}

# Print APC ST with optional tmux DCS terminator.
# Inside tmux: inner ST has its ESC doubled (ESC ESC \), then the
# outer DCS wrapper closes with its own ESC \.
_pt_print_apc_st() {
    if _pt_is_tmux; then
        printf '\033\033\\\033\\'
    else
        printf '\033\\'
    fi
}

# Send image data using Kitty graphics protocol (a=T, f=100 PNG).
# Splits base64 into chunks of at most 4096 characters with m=1/m=0.
# Uses fold for linear chunk extraction. All control keys (including q=2)
# are comma-separated in _kitty_control; only the first chunk carries them.
_pt_send_kitty() {
    _chunk_size=4096
    _first=1

    printf '%s\n' "$_b64data" | fold -w "$_chunk_size" | \
        awk -v sz="$_chunk_size" '
            { buf[NR] = $0 }
            END {
                for (i = 1; i <= NR; i++) {
                    if (i < NR) printf "%s\tm=1\t%s\n", (i==1 ? "first" : ""), buf[i]
                    else printf "%s\tm=0\t%s\n", (i==1 ? "first" : ""), buf[i]
                }
            }
        ' | while IFS='	' read -r _tag _m _chunk; do
        if [ "$_tag" = "first" ]; then
            _pt_print_apc
            printf '%s,%s;%s' "$_kitty_control" "$_m" "$_chunk"
            _pt_print_apc_st
        else
            _pt_print_apc
            printf '%s;%s' "$_m" "$_chunk"
            _pt_print_apc_st
        fi
    done
    printf '\n'
}


# Estimate the number of terminal rows the image will occupy.
# Uses explicit --height if in cell units, otherwise computes from
# image pixel dimensions and estimated cell metrics.
_pt_estimate_rows() {
    _img_file="$1"      # file path (empty for stdin)
    _opt_width="$2"     # --width value or empty
    _opt_height="$3"    # --height value or empty
    _preserve="$4"      # 1 or 0

    # If --height is in cell units (no "px" suffix), use it directly.
    if [ -n "$_opt_height" ]; then
        case "$_opt_height" in
            *px) ;;  # pixel units — fall through to calculation
            *)
                printf '%s' "$_opt_height"
                return
                ;;
        esac
    fi

    # Need image pixel dimensions for calculation.
    if [ -z "$_img_file" ] || [ ! -f "$_img_file" ]; then
        return
    fi
    _dims=$(_pt_image_dims "$_img_file")
    if [ -z "$_dims" ]; then
        return
    fi
    _img_w=$(printf '%s' "$_dims" | cut -d' ' -f1)
    _img_h=$(printf '%s' "$_dims" | cut -d' ' -f2)
    if [ -z "$_img_w" ] || [ -z "$_img_h" ] || [ "$_img_h" -le 0 ] 2>/dev/null; then
        return
    fi

    # Terminal metrics (best-effort estimates).
    _term_cols=$(tput cols 2>/dev/null || echo 80)
    _cell_w=8
    _cell_h=16
    _term_px_w=$((_term_cols * _cell_w))

    # If explicit pixel height, use that.
    if [ -n "$_opt_height" ]; then
        _display_h=$(printf '%s' "$_opt_height" | sed 's/px$//')
    else
        # Scale to fit terminal width if image is wider.
        if [ "$_img_w" -gt "$_term_px_w" ]; then
            # display_h = img_h * term_px_w / img_w  (integer math)
            _display_h=$(( _img_h * _term_px_w / _img_w ))
        else
            _display_h="$_img_h"
        fi
    fi

    # Ceiling division: rows = (display_h + cell_h - 1) / cell_h
    _rows=$(( (_display_h + _cell_h - 1) / _cell_h ))
    printf '%s' "$_rows"
}

# Defaults
_width=""
_height=""
_preserve_aspect="1"
_file=""
_format="iterm2"

# Parse options
while [ $# -gt 0 ]; do
    case "$1" in
        --format)
            _format="$2"
            shift 2
            ;;
        --width)
            _width="$2"
            shift 2
            ;;
        --height)
            _height="$2"
            shift 2
            ;;
        --preserve-aspect-ratio)
            _preserve_aspect="1"
            shift
            ;;
        --no-preserve-aspect-ratio)
            _preserve_aspect="0"
            shift
            ;;
        --)
            shift
            _file="${1:--}"
            break
            ;;
        -)
            _file="-"
            shift
            break
            ;;
        -*)
            echo "Unknown option: $1" >&2
            echo "Usage: pt-imgcat [--format iterm2|kitty] [--width N] [--height N] <file|->" >&2
            exit 1
            ;;
        *)
            _file="$1"
            shift
            break
            ;;
    esac
done

# Validate format
case "$_format" in
    iterm2|kitty) ;;
    *)
        echo "Error: unknown format '$_format' (use iterm2 or kitty)" >&2
        exit 1
        ;;
esac

# Determine input source
_from_stdin=0
if [ -z "$_file" ]; then
    if [ -t 0 ]; then
        echo "Usage: pt-imgcat [options] <file|->" >&2
        echo "       cat image.png | pt-imgcat" >&2
        exit 1
    fi
    _from_stdin=1
    _file="-"
elif [ "$_file" = "-" ]; then
    _from_stdin=1
fi

# Send the image
if [ "$_format" = "kitty" ]; then

    # Spool input to a temp file if reading from stdin (so conversion
    # tools can re-read the source without consuming stdin twice).
    _stdin_tmp=""
    if [ "$_from_stdin" -eq 1 ]; then
        _stdin_tmp=$(mktemp /tmp/pt-imgcat-XXXXXX)
        cat > "$_stdin_tmp"
        _src_file="$_stdin_tmp"
    else
        if [ ! -f "$_file" ]; then
            echo "Error: '$_file' is not a regular file" >&2
            exit 1
        fi
        if [ ! -r "$_file" ]; then
            echo "Error: '$_file' is not readable" >&2
            exit 1
        fi
        _src_file="$_file"
    fi

    _b64data=$(base64 < "$_src_file" | tr -d '\n')

    # Validate PNG (Kitty f=100 only supports PNG).
    # If not PNG, try converting with sips (macOS) or ImageMagick.
    if ! _pt_is_png_b64 "$_b64data"; then
        _converted=""
        _conv_tmp=$(mktemp /tmp/pt-imgcat-XXXXXX.png)
        if command -v sips >/dev/null 2>&1; then
            if sips -s format png "$_src_file" --out "$_conv_tmp" >/dev/null 2>&1; then
                _b64data=$(base64 < "$_conv_tmp" | tr -d '\n')
                _converted="1"
            fi
        elif command -v convert >/dev/null 2>&1; then
            if convert "$_src_file" "$_conv_tmp" 2>/dev/null; then
                _b64data=$(base64 < "$_conv_tmp" | tr -d '\n')
                _converted="1"
            fi
        fi
        rm -f "$_conv_tmp"

        if [ -z "$_converted" ] && ! _pt_is_png_b64 "$_b64data"; then
            [ -n "$_stdin_tmp" ] && rm -f "$_stdin_tmp"
            echo "Error: --format kitty requires PNG input (got non-PNG data)" >&2
            echo "       Install sips (macOS) or ImageMagick for auto-conversion," >&2
            echo "       or use --format iterm2 for JPEG/GIF/WebP" >&2
            exit 1
        fi
    fi

    [ -n "$_stdin_tmp" ] && rm -f "$_stdin_tmp"

    # Validate width/height: Kitty uses cell units (c=/r=), not pixels.
    _kitty_control="a=T,f=100,q=2"
    if [ -n "$_width" ]; then
        case "$_width" in
            *px)
                echo "Error: --format kitty does not support pixel-unit width (use cells)" >&2
                exit 1
                ;;
            *) _kitty_control="${_kitty_control},c=${_width}" ;;
        esac
    fi
    if [ -n "$_height" ]; then
        case "$_height" in
            *px)
                echo "Error: --format kitty does not support pixel-unit height (use cells)" >&2
                exit 1
                ;;
            *) _kitty_control="${_kitty_control},r=${_height}" ;;
        esac
    fi

    _pt_send_kitty

    # In tmux, advance the cursor.
    if _pt_is_tmux; then
        _est_rows=$(_pt_estimate_rows "$_file" "$_width" "$_height" "$_preserve_aspect")
        if [ -n "$_est_rows" ] && [ "$_est_rows" -gt 0 ] 2>/dev/null; then
            _pt_tmux_advance_cursor "$_est_rows"
        fi
    fi
else
    # --- iTerm2 OSC 1337 File protocol (existing behavior) ---

    # Build OSC parameters
    _params="inline=1"

    if [ -n "$_width" ]; then
        _params="${_params};width=${_width}"
    fi

    if [ -n "$_height" ]; then
        _params="${_params};height=${_height}"
    fi

    if [ "$_preserve_aspect" = "0" ]; then
        _params="${_params};preserveAspectRatio=0"
    fi

    if [ "$_from_stdin" -eq 1 ]; then
        _b64name=$(printf '%s' "image" | base64 | tr -d '\n')
        _b64data=$(base64 | tr -d '\n')
        _size=$(printf '%s' "$_b64data" | base64 -d 2>/dev/null | wc -c | tr -d ' ')

        _pt_print_osc
        printf '1337;File=name=%s;size=%s;%s:' "$_b64name" "$_size" "$_params"
        printf '%s' "$_b64data"
        _pt_print_st
        printf '\n'
    else
        if [ ! -f "$_file" ]; then
            echo "Error: '$_file' is not a regular file" >&2
            exit 1
        fi
        if [ ! -r "$_file" ]; then
            echo "Error: '$_file' is not readable" >&2
            exit 1
        fi

        _basename=$(basename "$_file")
        _b64name=$(printf '%s' "$_basename" | base64 | tr -d '\n')
        _b64data=$(base64 < "$_file" | tr -d '\n')
        _size=$(printf '%s' "$_b64data" | base64 -d 2>/dev/null | wc -c | tr -d ' ')

        _pt_print_osc
        printf '1337;File=name=%s;size=%s;%s:' "$_b64name" "$_size" "$_params"
        printf '%s' "$_b64data"
        _pt_print_st
        printf '\n'

        # In tmux, advance the cursor so the prompt appears below the image.
        # tmux's virtual terminal doesn't see passthrough content, so its
        # cursor stays put without this.
        if _pt_is_tmux; then
            _est_rows=$(_pt_estimate_rows "$_file" "$_width" "$_height" "$_preserve_aspect")
            if [ -n "$_est_rows" ] && [ "$_est_rows" -gt 0 ] 2>/dev/null; then
                _pt_tmux_advance_cursor "$_est_rows"
            fi
        fi
    fi
fi