limner 0.5.0

A ratatui markdown renderer with image placeholders, code blocks, and styled headings
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
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
//! Terminal image rendering via [`ratatui-image`].
//!
//! Provides helpers for creating terminal image protocols from decoded images,
//! and for placing inline images within rendered markdown content.
//!
//! Uses `ratatui-image` which auto-detects Kitty protocol, Sixel, or half-block
//! fallback.  Images are rendered as native ratatui widgets inside the frame
//! buffer — they scroll, clear, and clip automatically.

use std::collections::HashMap;

use ratatui::layout::{Alignment, Rect};
use ratatui::text::Line;
use ratatui::widgets::{Paragraph, Wrap};

use crate::ImageInfo;

/// Re-export the `image` crate for callers that need to decode images.
pub use image as img_crate;

/// Re-export key `ratatui-image` types for convenience.
pub use ratatui_image::{protocol::Protocol, FontSize, Image, Resize};

/// Re-export the picker and protocol type.
pub use ratatui_image::picker::{Picker, ProtocolType};

/// Re-export sliced image types for scrollable/clipped image rendering.
pub use ratatui_image::sliced::{SignedPosition, SlicedImage, SlicedProtocol};

/// Result of preparing images for inline rendering within markdown content.
///
/// Returned by [`prepare_inline_images`]; the caller uses the fields to position
/// [`Image`] widgets in the frame.
pub struct ImagePlacement {
    /// The image URL (used as key into the protocol cache).
    pub url: String,
    /// 0-based row index within the rendered line buffer where the image starts.
    pub line_start: usize,
    /// Number of terminal columns (character cells) the image occupies.
    pub cell_cols: u16,
    /// Number of terminal rows the image occupies.
    pub cell_rows: u16,
    /// Horizontal alignment within the content area (None = left-aligned).
    pub alignment: Option<Alignment>,
}

/// Compute the optimal cell dimensions for an image, fitting within
/// `max_cols × max_rows` while preserving aspect ratio.
///
/// Never upscales — the image is only ever shrunk to fit.
/// Returns `(cols, rows)` both at least 1.
pub fn fit_cell_size(
    img: &img_crate::DynamicImage,
    font_size: &FontSize,
    max_cols: u16,
    max_rows: u16,
) -> (u16, u16) {
    if max_cols == 0 || max_rows == 0 || img.width() == 0 || img.height() == 0 {
        return (max_cols.max(1), max_rows.max(1));
    }

    let cell_w = font_size.width as f64;
    let cell_h = font_size.height as f64;

    let img_cols = (img.width() as f64 / cell_w).ceil();
    let img_rows = (img.height() as f64 / cell_h).ceil();

    let scale_x = max_cols as f64 / img_cols;
    let scale_y = max_rows as f64 / img_rows;
    let scale = scale_x.min(scale_y).min(1.0);

    let cols = (img_cols * scale).ceil().max(1.0) as u16;
    let rows = (img_rows * scale).ceil().max(1.0) as u16;

    (cols.min(max_cols), rows.min(max_rows))
}

/// Create a fixed-size [`Protocol`] from a decoded image.
///
/// The image is scaled to fit within `cell_cols × cell_rows` terminal cells
/// while preserving aspect ratio (via `Resize::Fit`).
///
/// Note: the `Size` passed to `picker.new_protocol` is in **cell units** (not
/// pixels).  For halfblocks this is the number of `▀` characters to use.
pub fn make_protocol(
    picker: &Picker,
    img: &img_crate::DynamicImage,
    cell_cols: u16,
    cell_rows: u16,
) -> Option<Protocol> {
    let size = ratatui::layout::Size::new(cell_cols, cell_rows);
    picker
        .new_protocol(img.clone(), size, Resize::Fit(None))
        .ok()
}

/// Create a [`SlicedProtocol`] from a decoded image.
///
/// The image is scaled to fit within `cell_cols × cell_rows` terminal cells
/// while preserving aspect ratio, then encoded into a protocol that supports
/// efficient row-level clipping for scrolling via [`SlicedImage`].
///
/// Unlike [`make_protocol`], this consumes the `DynamicImage` and sets up
/// internal row slicing so that scrolling/clipping costs zero per-frame work.
pub fn make_sliced_protocol(
    picker: &Picker,
    img: img_crate::DynamicImage,
    cell_cols: u16,
    cell_rows: u16,
) -> Option<SlicedProtocol> {
    let size = ratatui::layout::Size::new(cell_cols, cell_rows);
    SlicedProtocol::new(picker, img, Some(size)).ok()
}

/// Create a [`Protocol`] for a clipped / partially-visible image.
///
/// The original image is first scaled to `full_size` (preserving aspect ratio),
/// then `hidden_top` cell‑rows and `hidden_left` cell‑columns are sliced off,
/// yielding a protocol that matches `visible_size`.
///
/// Use this to render images that are partially off‑screen — the visible
/// portion of the image is sent to the terminal instead of the full image.
#[deprecated(
    since = "0.5.0",
    note = "use `SlicedProtocol` + `SlicedImage` instead; call `make_sliced_protocol` once then render with `SlicedImage::new()`"
)]
pub fn make_clipped_protocol(
    picker: &Picker,
    img: &img_crate::DynamicImage,
    full_size: ratatui::layout::Size,
    visible_size: ratatui::layout::Size,
    hidden_top: u16,
    hidden_left: u16,
) -> Option<Protocol> {
    let (fw, fh) = (
        picker.font_size().width as u32,
        picker.font_size().height as u32,
    );

    // Pixel dimensions the image would occupy at `full_size`.
    let fit_w = full_size.width as u32 * fw;
    let fit_h = full_size.height as u32 * fh;

    // Uniform scale so the image fits into (fit_w × fit_h), never upscale.
    let scale = (fit_w as f64 / img.width() as f64)
        .min(fit_h as f64 / img.height() as f64)
        .min(1.0);
    let sw = (img.width() as f64 * scale).round() as u32;
    let sh = (img.height() as f64 * scale).round() as u32;

    let scaled = img.resize_exact(sw, sh, image::imageops::FilterType::Nearest);

    // Pad to the full cell grid with transparency.
    let mut padded = image::RgbaImage::from_pixel(fit_w, fit_h, image::Rgba([0, 0, 0, 0]));
    image::imageops::overlay(&mut padded, &scaled, 0, 0);

    // Slice off hidden rows and columns in pixel space.
    let vis_pix_w = visible_size.width as u32 * fw;
    let vis_pix_h = visible_size.height as u32 * fh;
    let x_off = (hidden_left as u32 * fw).min(padded.width().saturating_sub(vis_pix_w));
    let y_off = (hidden_top as u32 * fh).min(padded.height().saturating_sub(vis_pix_h));

    let padded_dyn: img_crate::DynamicImage = padded.into();
    let cropped = padded_dyn.crop_imm(x_off, y_off, vis_pix_w, vis_pix_h);

    picker
        .new_protocol(cropped, visible_size, Resize::Fit(None))
        .ok()
}

/// Create a [`Protocol`] for a vertically-scrolled / partially-visible image.
///
/// Convenience wrapper around [`make_clipped_protocol`] with `hidden_left = 0`.
#[deprecated(
    since = "0.5.0",
    note = "use `SlicedProtocol` + `SlicedImage` instead; call `make_sliced_protocol` once then render with `SlicedImage::new()`"
)]
#[allow(deprecated)]
pub fn make_scrolled_protocol(
    picker: &Picker,
    img: &img_crate::DynamicImage,
    full_size: ratatui::layout::Size,
    visible_size: ratatui::layout::Size,
    hidden_top: u16,
) -> Option<Protocol> {
    make_clipped_protocol(picker, img, full_size, visible_size, hidden_top, 0)
}

/// Create a halfblock-only [`Picker`] (works on every terminal).
///
/// Use this instead of [`Picker::from_query_stdio`] when you want reliable
/// cross-terminal image rendering without Kitty/Sixel protocol detection.
pub fn halfblock_picker() -> Picker {
    Picker::halfblocks()
}

/// Describes the visible viewport for computing image render positions.
///
/// Pass this to [`compute_image_render_rects`] along with the placements and
/// line buffer so the library can calculate where each image should appear on
/// screen — including any clipping needed when the image is partially off‑screen.
pub struct ImageViewport {
    /// The area where content is rendered (typically `block.inner(terminal_area)`).
    pub content: Rect,
    /// Current scroll offset in lines.
    pub scroll: u16,
}

/// Describes where to render a [`SlicedImage`] widget.
///
/// Returned by [`compute_image_signed_positions`].  The caller should
/// look up the [`SlicedProtocol`] from `sliced_protocol_cache` and render
/// via `SlicedImage::new(&sliced, position)` at the content area.
///
/// The [`SignedPosition`] is relative to the content area passed to
/// `f.render_widget()` — the [`SlicedImage`] widget handles all row-level
/// skip/drop and column-level clamping automatically.
pub struct ImageSlicedRender {
    /// The image URL (key into `sliced_protocol_cache`).
    pub url: String,
    /// Position relative to the content area (may be negative for off-screen start).
    pub position: SignedPosition,
}

/// Compute signed positions for sliced image rendering.
///
/// Takes the output of [`prepare_inline_images`] and the current viewport,
/// returning a signed position for each visible or partially-visible image.
///
/// Images that are fully off‑screen are excluded from the result.  For
/// partially-visible images, the widget's built-in clipping handles the
/// skip/drop automatically — no per-frame protocol creation is needed.
///
/// `lines` is the full line buffer after `prepare_inline_images` has replaced
/// image placeholders — its length is used to safely clamp line indices.
pub fn compute_image_signed_positions(
    placements: &[ImagePlacement],
    lines: &[Line],
    viewport: &ImageViewport,
) -> Vec<ImageSlicedRender> {
    let content_width = viewport.content.width as i16;
    let content_height = viewport.content.height as i16;

    let mut positions = Vec::new();

    for p in placements {
        // Compute visual Y (accounting for Paragraph word-wrap).
        let visual_y: u16 = if p.line_start == 0 {
            0
        } else {
            let end = p.line_start.min(lines.len());
            Paragraph::new(lines[..end].to_vec())
                .wrap(Wrap { trim: false })
                .line_count(viewport.content.width)
                .max(1) as u16
        };

        // Compute x based on alignment (relative to content left edge).
        let x: i16 = match p.alignment {
            Some(Alignment::Center) => (content_width - p.cell_cols as i16) / 2,
            Some(Alignment::Right) => content_width - p.cell_cols as i16,
            _ => 0,
        };

        let y: i16 = visual_y as i16 - viewport.scroll as i16;

        // Skip if fully off-screen.
        let cell_rows = p.cell_rows as i16;
        if y + cell_rows <= 0 || y >= content_height {
            continue;
        }
        let cell_cols = p.cell_cols as i16;
        if x + cell_cols <= 0 || x >= content_width {
            continue;
        }

        positions.push(ImageSlicedRender {
            url: p.url.clone(),
            position: SignedPosition { x, y },
        });
    }

    positions
}

/// Describes how to render a single image, including any clipping parameters.
///
/// Returned by [`compute_image_render_rects`].  The caller should:
///
/// 1. Look up the decoded image from their cache.
/// 2. Build a [`Protocol`] via [`make_clipped_protocol`] if clipping is needed
///    (`hidden_top > 0` or `hidden_left > 0`), or use the standard cached
///    protocol otherwise.
/// 3. Render an [`Image`] widget at `render_rect`.
#[deprecated(
    since = "0.5.0",
    note = "use `ImageSlicedRender` + `compute_image_signed_positions` instead; render via `SlicedImage::new()`"
)]
pub struct ImageRenderRect {
    /// The image URL (key into the caller's image and protocol caches).
    pub url: String,
    /// Where to render the visible portion (position + dimensions in terminal cells).
    pub render_rect: Rect,
    /// The original full cell dimensions (unclipped).
    pub full_cols: u16,
    pub full_rows: u16,
    /// How many cell-rows are hidden from the top of the original image.
    pub hidden_top: u16,
    /// How many cell-columns are hidden from the left of the original image.
    pub hidden_left: u16,
    /// Horizontal alignment (from the markdown source).
    pub alignment: Option<Alignment>,
}

/// Compute where to render each image given a viewport and scroll state.
///
/// Takes the output of [`prepare_inline_images`] and the current render state
/// (`lines` and viewport) and returns a list of [`ImageRenderRect`] values.
///
/// Images that are fully off‑screen (above, below, left, or right) are
/// excluded from the result.  Images that are partially visible get clipping
/// parameters (`hidden_top`, `hidden_left`) that the caller passes to
/// [`make_clipped_protocol`].
///
/// `lines` is the full line buffer after `prepare_inline_images` has replaced
/// image placeholders — its length is used to safely clamp line indices.
#[deprecated(
    since = "0.5.0",
    note = "use `compute_image_signed_positions` instead; SlicedImage handles clipping automatically"
)]
#[allow(deprecated)]
pub fn compute_image_render_rects(
    placements: &[ImagePlacement],
    lines: &[Line],
    viewport: &ImageViewport,
) -> Vec<ImageRenderRect> {
    let content_top = viewport.content.y as i32;
    let content_bottom = (viewport.content.y + viewport.content.height) as i32;
    let content_left = viewport.content.x as i32;
    let content_right = (viewport.content.x + viewport.content.width) as i32;

    let mut render_rects = Vec::new();

    for p in placements {
        // Compute visual Y (accounting for Paragraph word-wrap).
        let visual_y: u16 = if p.line_start == 0 {
            0
        } else {
            let end = p.line_start.min(lines.len());
            Paragraph::new(lines[..end].to_vec())
                .wrap(Wrap { trim: false })
                .line_count(viewport.content.width)
                .max(1) as u16
        };

        // Unclipped terminal-space Y coordinates.
        let unclipped_y0 = content_top + visual_y as i32 - viewport.scroll as i32;
        let unclipped_y1 = unclipped_y0 + p.cell_rows as i32;

        // Clamp Y to content area.
        let y0 = unclipped_y0.max(content_top);
        let y1 = unclipped_y1.min(content_bottom);
        if y0 >= y1 {
            continue;
        }
        let visible_rows = (y1 - y0) as u16;

        // Compute logical horizontal position (may be negative for overflow).
        let logical_x = match p.alignment {
            Some(Alignment::Center) => {
                content_left + (viewport.content.width as i32 / 2) - (p.cell_cols as i32 / 2)
            }
            Some(Alignment::Right) => {
                content_left + viewport.content.width as i32 - p.cell_cols as i32
            }
            _ => content_left,
        };

        // Clamp X to content area.
        let x0 = logical_x.max(content_left);
        let x1 = (logical_x + p.cell_cols as i32).min(content_right);
        if x0 >= x1 {
            continue;
        }
        let visible_cols = (x1 - x0) as u16;

        let hidden_top = if unclipped_y0 < content_top {
            (content_top - unclipped_y0) as u16
        } else {
            0
        };

        let hidden_left = if logical_x < content_left {
            (content_left - logical_x) as u16
        } else {
            0
        };

        render_rects.push(ImageRenderRect {
            url: p.url.clone(),
            render_rect: Rect {
                x: x0 as u16,
                y: y0 as u16,
                width: visible_cols,
                height: visible_rows,
            },
            full_cols: p.cell_cols,
            full_rows: p.cell_rows,
            hidden_top,
            hidden_left,
            alignment: p.alignment,
        });
    }

    render_rects
}

/// Prepare images for inline rendering within markdown content.
///
/// **Pass 1** — For every image whose URL is in `image_cache` but not yet in
/// `sliced_protocol_cache`, a new [`SlicedProtocol`] is created and inserted.
/// The [`DynamicImage`] is consumed (removed from `image_cache`) on success.
///
/// **Pass 2** — Each image placeholder (1 line) in `lines` is replaced with
/// `cell_rows` empty lines to reserve space.  An [`ImagePlacement`] is returned
/// describing where the caller should position the [`SlicedImage`] widget.
///
/// Images whose URL is NOT in `image_cache` are skipped — the placeholder text
/// (e.g. `🖼 alt`) remains visible in the rendered content.
///
/// `max_rows` defaults to 10 (user preference).  `max_cols` should be the
/// content area width in terminal columns.
#[allow(clippy::too_many_arguments)]
pub fn prepare_inline_images(
    lines: &mut Vec<Line<'static>>,
    images: &[ImageInfo],
    image_cache: &mut HashMap<String, img_crate::DynamicImage>,
    sliced_protocol_cache: &mut HashMap<String, SlicedProtocol>,
    picker: &Picker,
    font_size: &FontSize,
    max_cols: u16,
    max_rows: u16,
) -> Vec<ImagePlacement> {
    let mut indexed: Vec<(usize, &ImageInfo)> = images.iter().enumerate().collect();
    indexed.sort_by_key(|a| a.1.line_index);

    // Pass 1 — lazily create SlicedProtocols for newly cached images.
    // Consumes the DynamicImage from image_cache on success.
    for (_, img) in &indexed {
        if !sliced_protocol_cache.contains_key(&img.url) {
            if let Some(dyn_img) = image_cache.remove(&img.url) {
                let (cols, rows) = fit_cell_size(&dyn_img, font_size, max_cols, max_rows);
                if cols > 0 && rows > 0 {
                    if let Some(sliced) = make_sliced_protocol(picker, dyn_img, cols, rows) {
                        sliced_protocol_cache.insert(img.url.clone(), sliced);
                    }
                }
            }
        }
    }

    // Pass 2 — replace placeholder lines with empty space, record placements.
    // `cursor` tracks the next free line so images sharing the same original
    // `line_index` (e.g. multiple extra images at line 0) don't overlap.
    let mut placements = Vec::new();
    let mut offset: isize = 0;
    let mut cursor: isize = 0;

    for (_, img) in &indexed {
        let adjusted_line = (img.line_index as isize + offset) as usize;

        let Some(sliced) = sliced_protocol_cache.get(&img.url) else {
            continue;
        };

        let size = sliced.size();
        if size.width == 0 || size.height == 0 {
            continue;
        }

        let insert_at = (adjusted_line as isize).max(cursor) as usize;
        if insert_at >= lines.len() {
            continue;
        }

        let alignment = lines[insert_at].alignment;
        let empty: Vec<Line<'static>> = (0..size.height)
            .map(|_| {
                let mut l = Line::from("");
                l.alignment = alignment;
                l
            })
            .collect();
        lines.splice(insert_at..=insert_at, empty);

        placements.push(ImagePlacement {
            url: img.url.clone(),
            line_start: insert_at,
            cell_cols: size.width,
            cell_rows: size.height,
            alignment,
        });

        offset += size.height as isize - 1;
        cursor = insert_at as isize + size.height as isize;
    }

    placements
}