File copy/move: make ETA accurate.
[midnight-commander.git] / src / viewer / ascii.c
blobffe7d6db1f06a05b768910aaceb1418c02379a6e
1 /*
2 Internal file viewer for the Midnight Commander
3 Function for plain view
5 Copyright (C) 1994-2024
6 Free Software Foundation, Inc.
8 Written by:
9 Miguel de Icaza, 1994, 1995, 1998
10 Janne Kukonlehto, 1994, 1995
11 Jakub Jelinek, 1995
12 Joseph M. Hinkle, 1996
13 Norbert Warmuth, 1997
14 Pavel Machek, 1998
15 Roland Illig <roland.illig@gmx.de>, 2004, 2005
16 Slava Zanko <slavazanko@google.com>, 2009
17 Andrew Borodin <aborodin@vmail.ru>, 2009-2022
18 Ilia Maslakov <il.smind@gmail.com>, 2009
19 Rewritten almost from scratch by:
20 Egmont Koblinger <egmont@gmail.com>, 2014
22 This file is part of the Midnight Commander.
24 The Midnight Commander is free software: you can redistribute it
25 and/or modify it under the terms of the GNU General Public License as
26 published by the Free Software Foundation, either version 3 of the License,
27 or (at your option) any later version.
29 The Midnight Commander is distributed in the hope that it will be useful,
30 but WITHOUT ANY WARRANTY; without even the implied warranty of
31 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
32 GNU General Public License for more details.
34 You should have received a copy of the GNU General Public License
35 along with this program. If not, see <http://www.gnu.org/licenses/>.
37 ------------------------------------------------------------------------------------------------
39 The viewer is implemented along the following design principles:
41 Goals: Always display simple scripts, double wide (CJK), combining accents and spacing marks
42 (often used e.g. in Devanagari) perfectly. Make the arrow keys always work correctly.
44 Absolutely non-goal: RTL.
46 Terminology:
48 - A "paragraph" is the text between two adjacent newline characters. A "line" or "row" is a
49 visual row on the screen. In wrap mode, the viewer formats a paragraph into one or more lines.
51 - The Unicode glossary <http://www.unicode.org/glossary/> doesn't seem to have a notion of "base
52 character followed by zero or more combining characters". The closest matches are "Combining
53 Character Sequence" meaning a base character followed by one or more combining characters, or
54 "Grapheme" which seems to exclude non-printable characters such as newline. In this file,
55 "combining character sequence" (or any obvious abbreviation thereof) means a base character
56 followed by zero or more (up to a current limit of 4) combining characters.
58 ------------------------------------------------------------------------------------------------
60 The parser-formatter is designed to be stateless across paragraphs. This is so that we can walk
61 backwards without having to reparse the whole file (although we still need to reparse and
62 reformat the whole paragraph, but it's a lot better). This principle needs to be changed if we
63 ever get to address tickets 1849/2977, but then we can still store (for efficiency) the parser
64 state at the beginning of the paragraph, and safely walk backwards if we don't cross an escape
65 character.
67 The parser-formatter, however, definitely needs to carry a state across lines. Currently this
68 state contains:
70 - The logical column (as if we didn't wrap). This is used for handling TAB characters after a
71 wordwrap consistently with less.
73 - Whether the last nroff character was bold or underlined. This is used for displaying the
74 ambiguous _\b_ sequence consistently with less.
76 - Whether the desired way of displaying a lonely combining accent or spacing mark is to place it
77 over a dotted circle (we do this at the beginning of the paragraph of after a TAB), or to ignore
78 the combining char and show replacement char for the spacing mark (we do this if e.g. too many
79 of these were encountered and hence we don't glue them with their base character).
81 - (This state needs to be expanded if e.g. we decide to print verbose replacement characters
82 (e.g. "<U+0080>") and allow these to wrap around lines.)
84 The state also contains the file offset, as it doesn't make sense to ever know the state without
85 knowing the corresponding offset.
87 The state depends on various settings (viewer width, encoding, nroff mode, charwrap or wordwrap
88 mode (if we'll have that one day) etc.), needs to be recomputed if any of these changes.
90 Walking forwards is usually relatively easy both in the file and on the screen. Walking
91 backwards within a paragraph would only be possible in some special cases and even then it would
92 be painful, so we always walk back to the beginning of the paragraph and reparse-reformat from
93 there.
95 (Walking back within a line in the file would have at least the following difficulties: handling
96 the parser state; processing invalid UTF-8; processing invalid nroff (e.g. what is "_\bA\bA"?).
97 Walking back on the display: we wouldn't know where to display the last line of a paragraph, or
98 where to display a line if its following line starts with a wide (CJK or Tab) character. Long
99 story short: just forget this approach.)
101 Most important variables:
103 - dpy_start: Both in unwrap and wrap modes this points to the beginning of the topmost displayed
104 paragraph.
106 - dpy_text_column: Only in unwrap mode, an additional horizontal scroll.
108 - dpy_paragraph_skip_lines: Only in wrap mode, an additional vertical scroll (the number of
109 lines that are scrolled off at the top from the topmost paragraph).
111 - dpy_state_top: Only in wrap mode, the offset and parser-formatter state at the line where
112 displaying the file begins is cached here.
114 - dpy_wrap_dirty: If some parameter has changed that makes it necessary to reparse-redisplay the
115 topmost paragraph.
117 In wrap mode, the three variables "dpy_start", "dpy_paragraph_skip_lines" and "dpy_state_top"
118 are kept consistent. Think of the first two as the ones describing the position, and the third
119 as a cached value for better performance so that we don't need to wrap the invisible beginning
120 of the topmost paragraph over and over again. The third value needs to be recomputed each time a
121 parameter that influences parsing or displaying the file (e.g. width of screen, encoding, nroff
122 mode) changes, this is signaled by "dpy_wrap_dirty" to force recomputing "dpy_state_top" (and
123 clamp "dpy_paragraph_skip_lines" if necessary).
125 ------------------------------------------------------------------------------------------------
127 Help integration
129 I'm planning to port the help viewer to this codebase.
131 Splitting at sections would still happen in the help viewer. It would either copy a section, or
132 set force_max and a similar force_min to limit displaying to one section only.
134 Parsing the help format would go next to the nroff parser. The colors, alternate character set,
135 and emitting the version number would go to the "state". (The version number would be
136 implemented by emitting remaining characters of a buffer in the "state" one by one, without
137 advancing in the file position.)
139 The active link would be drawn similarly to the search highlight. Other than that, the viewer
140 wouldn't care about links (except for their color). help.c would keep track of which one is
141 highlighted, how to advance to the next/prev on an arrow, how the scroll offset needs to be
142 adjusted when moving, etc.
144 Add wrapping at word boundaries to where wrapping at char boundaries happens now.
147 #include <config.h>
149 #include "lib/global.h"
150 #include "lib/tty/tty.h"
151 #include "lib/skin.h"
152 #include "lib/util.h" /* is_printable() */
153 #ifdef HAVE_CHARSET
154 #include "lib/charsets.h"
155 #endif
157 #include "src/setup.h" /* option_tab_spacing */
159 #include "internal.h"
161 /*** global variables ****************************************************************************/
163 /*** file scope macro definitions ****************************************************************/
165 /* The Unicode standard recommends that lonely combining characters are printed over a dotted
166 * circle. If the terminal is not UTF-8, this will be replaced by a dot anyway. */
167 #define BASE_CHARACTER_FOR_LONELY_COMBINING 0x25CC /* dotted circle */
168 #define MAX_COMBINING_CHARS 4 /* both slang and ncurses support exactly 4 */
170 /* I think anything other than space (e.g. arrows) just introduce visual clutter without actually
171 * adding value. */
172 #define PARTIAL_CJK_AT_LEFT_MARGIN ' '
173 #define PARTIAL_CJK_AT_RIGHT_MARGIN ' '
176 * Wrap mode: This is for safety so that jumping to the end of file (which already includes
177 * scrolling back by a page) and then walking backwards is reasonably fast, even if the file is
178 * extremely large and consists of maybe full zeros or something like that. If there's no newline
179 * found within this limit, just start displaying from there and see what happens. We might get
180 * some displaying parameters (most importantly the columns) incorrect, but at least will show the
181 * file without spinning the CPU for ages. When scrolling back to that point, the user might see a
182 * garbled first line (even starting with an invalid partial UTF-8), but then walking back by yet
183 * another line should fix it.
185 * Unwrap mode: This is not used, we wouldn't be able to do anything reasonable without walking
186 * back a whole paragraph (well, view->data_area.height paragraphs actually).
188 #define MAX_BACKWARDS_WALK_IN_PARAGRAPH (100 * 1000)
190 /*** file scope type declarations ****************************************************************/
192 /*** forward declarations (file scope functions) *************************************************/
194 /*** file scope variables ************************************************************************/
196 /* --------------------------------------------------------------------------------------------- */
197 /*** file scope functions ************************************************************************/
198 /* --------------------------------------------------------------------------------------------- */
200 /* TODO: These methods shouldn't be necessary, see ticket 3257 */
202 static int
203 mcview_wcwidth (const WView *view, int c)
205 #ifdef HAVE_CHARSET
206 if (view->utf8)
208 if (g_unichar_iswide (c))
209 return 2;
210 if (g_unichar_iszerowidth (c))
211 return 0;
213 #else
214 (void) view;
215 (void) c;
216 #endif /* HAVE_CHARSET */
217 return 1;
220 /* --------------------------------------------------------------------------------------------- */
222 static gboolean
223 mcview_ismark (const WView *view, int c)
225 #ifdef HAVE_CHARSET
226 if (view->utf8)
227 return g_unichar_ismark (c);
228 #else
229 (void) view;
230 (void) c;
231 #endif /* HAVE_CHARSET */
232 return FALSE;
235 /* --------------------------------------------------------------------------------------------- */
237 /* actually is_non_spacing_mark_or_enclosing_mark */
238 static gboolean
239 mcview_is_non_spacing_mark (const WView *view, int c)
241 #ifdef HAVE_CHARSET
242 if (view->utf8)
244 GUnicodeType type;
246 type = g_unichar_type (c);
248 return type == G_UNICODE_NON_SPACING_MARK || type == G_UNICODE_ENCLOSING_MARK;
250 #else
251 (void) view;
252 (void) c;
253 #endif /* HAVE_CHARSET */
254 return FALSE;
257 /* --------------------------------------------------------------------------------------------- */
259 #if 0
260 static gboolean
261 mcview_is_spacing_mark (const WView *view, int c)
263 #ifdef HAVE_CHARSET
264 if (view->utf8)
265 return g_unichar_type (c) == G_UNICODE_SPACING_MARK;
266 #else
267 (void) view;
268 (void) c;
269 #endif /* HAVE_CHARSET */
270 return FALSE;
272 #endif /* 0 */
274 /* --------------------------------------------------------------------------------------------- */
276 static gboolean
277 mcview_isprint (const WView *view, int c)
279 #ifdef HAVE_CHARSET
280 if (!view->utf8)
281 c = convert_from_8bit_to_utf_c ((unsigned char) c, view->converter);
282 return g_unichar_isprint (c);
283 #else
284 (void) view;
285 /* TODO this is very-very buggy by design: ticket 3257 comments 0-1 */
286 return is_printable (c);
287 #endif /* HAVE_CHARSET */
290 /* --------------------------------------------------------------------------------------------- */
292 static int
293 mcview_char_display (const WView *view, int c, char *s)
295 #ifdef HAVE_CHARSET
296 if (mc_global.utf8_display)
298 if (!view->utf8)
299 c = convert_from_8bit_to_utf_c ((unsigned char) c, view->converter);
300 if (!g_unichar_isprint (c))
301 c = '.';
302 return g_unichar_to_utf8 (c, s);
304 if (view->utf8)
306 if (g_unichar_iswide (c))
308 s[0] = s[1] = '.';
309 return 2;
311 if (g_unichar_iszerowidth (c))
312 return 0;
313 /* TODO the is_printable check below will be broken for this */
314 c = convert_from_utf_to_current_c (c, view->converter);
316 else
318 /* TODO the is_printable check below will be broken for this */
319 c = convert_to_display_c (c);
321 #else
322 (void) view;
323 #endif /* HAVE_CHARSET */
324 /* TODO this is very-very buggy by design: ticket 3257 comments 0-1 */
325 if (!is_printable (c))
326 c = '.';
327 *s = c;
328 return 1;
331 /* --------------------------------------------------------------------------------------------- */
334 * Just for convenience, a common interface in front of mcview_get_utf and mcview_get_byte, so that
335 * the caller doesn't have to care about utf8 vs 8-bit modes.
337 * Normally: stores c, updates state, returns TRUE.
338 * At EOF: state is unchanged, c is undefined, returns FALSE.
340 * Just as with mcview_get_utf(), invalid UTF-8 is reported using negative integers.
342 * Also, temporary hack: handle force_max here.
343 * TODO: move it to lower layers (datasource.c)?
345 static gboolean
346 mcview_get_next_char (WView *view, mcview_state_machine_t *state, int *c)
348 /* Pretend EOF if we reached force_max */
349 if (view->force_max >= 0 && state->offset >= view->force_max)
350 return FALSE;
352 #ifdef HAVE_CHARSET
353 if (view->utf8)
355 int char_length = 0;
357 if (!mcview_get_utf (view, state->offset, c, &char_length))
358 return FALSE;
359 /* Pretend EOF if we crossed force_max */
360 if (view->force_max >= 0 && state->offset + char_length > view->force_max)
361 return FALSE;
363 state->offset += char_length;
364 return TRUE;
366 #endif /* HAVE_CHARSET */
367 if (!mcview_get_byte (view, state->offset, c))
368 return FALSE;
369 state->offset++;
370 return TRUE;
373 /* --------------------------------------------------------------------------------------------- */
375 * This function parses the next nroff character and gives it to you along with its desired color,
376 * so you never have to care about nroff again.
378 * The nroff mode does the backspace trick for every single character (Unicode codepoint). At least
379 * that's what the GNU groff 1.22 package produces, and that's what less 458 expects. For
380 * double-wide characters (CJK), still only a single backspace is emitted. For combining accents
381 * and such, the print-backspace-print step is repeated for the base character and then for each
382 * accent separately.
384 * So, the right place for this layer is after the bytes are interpreted in UTF-8, but before
385 * joining a base character with its combining accents.
387 * Normally: stores c and color, updates state, returns TRUE.
388 * At EOF: state is unchanged, c and color are undefined, returns FALSE.
390 * color can be null if the caller doesn't care.
392 static gboolean
393 mcview_get_next_maybe_nroff_char (WView *view, mcview_state_machine_t *state, int *c, int *color)
395 mcview_state_machine_t state_after_nroff;
396 int c2, c3;
398 if (color != NULL)
399 *color = VIEW_NORMAL_COLOR;
401 if (!view->mode_flags.nroff)
402 return mcview_get_next_char (view, state, c);
404 if (!mcview_get_next_char (view, state, c))
405 return FALSE;
406 /* Don't allow nroff formatting around CR, LF, TAB or other special chars */
407 if (!mcview_isprint (view, *c))
408 return TRUE;
410 state_after_nroff = *state;
412 if (!mcview_get_next_char (view, &state_after_nroff, &c2))
413 return TRUE;
414 if (c2 != '\b')
415 return TRUE;
417 if (!mcview_get_next_char (view, &state_after_nroff, &c3))
418 return TRUE;
419 if (!mcview_isprint (view, c3))
420 return TRUE;
422 if (*c == '_' && c3 == '_')
424 *state = state_after_nroff;
425 if (color != NULL)
426 *color =
427 state->nroff_underscore_is_underlined ? VIEW_UNDERLINED_COLOR : VIEW_BOLD_COLOR;
429 else if (*c == c3)
431 *state = state_after_nroff;
432 state->nroff_underscore_is_underlined = FALSE;
433 if (color != NULL)
434 *color = VIEW_BOLD_COLOR;
436 else if (*c == '_')
438 *c = c3;
439 *state = state_after_nroff;
440 state->nroff_underscore_is_underlined = TRUE;
441 if (color != NULL)
442 *color = VIEW_UNDERLINED_COLOR;
445 return TRUE;
448 /* --------------------------------------------------------------------------------------------- */
450 * Get one base character, along with its combining or spacing mark characters.
452 * (A spacing mark is a character that extends the base character's width 1 into a combined
453 * character of width 2, yet these two character cells should not be separated. E.g. Devanagari
454 * <U+0939><U+094B>.)
456 * This method exists mainly for two reasons. One is to be able to tell if we fit on the current
457 * line or need to wrap to the next one. The other is that both slang and ncurses seem to require
458 * that the character and its combining marks are printed in a single call (or is it just a
459 * limitation of mc's wrapper to them?).
461 * For convenience, this method takes care of converting CR or CR+LF into LF.
462 * TODO this should probably happen later, when displaying the file?
464 * Normally: stores cs and color, updates state, returns >= 1 (entries in cs).
465 * At EOF: state is unchanged, cs and color are undefined, returns 0.
467 * @param view ...
468 * @param state the parser-formatter state machine's state, updated
469 * @param cs store the characters here
470 * @param clen the room available in cs (that is, at most clen-1 combining marks are allowed), must
471 * be at least 2
472 * @param color if non-NULL, store the color here, taken from the first codepoint's color
473 * @return the number of entries placed in cs, or 0 on EOF
475 static int
476 mcview_next_combining_char_sequence (WView *view, mcview_state_machine_t *state, int *cs,
477 int clen, int *color)
479 int i = 1;
481 if (!mcview_get_next_maybe_nroff_char (view, state, cs, color))
482 return 0;
484 /* Process \r and \r\n newlines. */
485 if (cs[0] == '\r')
487 int cnext;
489 mcview_state_machine_t state_after_crlf = *state;
490 if (mcview_get_next_maybe_nroff_char (view, &state_after_crlf, &cnext, NULL)
491 && cnext == '\n')
492 *state = state_after_crlf;
493 cs[0] = '\n';
494 return 1;
497 /* We don't want combining over non-printable characters. This includes '\n' and '\t' too. */
498 if (!mcview_isprint (view, cs[0]))
499 return 1;
501 if (mcview_ismark (view, cs[0]))
503 if (!state->print_lonely_combining)
505 /* First character is combining. Either just return it, ... */
506 return 1;
508 else
510 /* or place this (and subsequent combining ones) over a dotted circle. */
511 cs[1] = cs[0];
512 cs[0] = BASE_CHARACTER_FOR_LONELY_COMBINING;
513 i = 2;
517 if (mcview_wcwidth (view, cs[0]) == 2)
519 /* Don't allow combining or spacing mark for wide characters, is this okay? */
520 return 1;
523 /* Look for more combining chars. Either at most clen-1 zero-width combining chars,
524 * or at most 1 spacing mark. Is this logic correct? */
525 for (; i < clen; i++)
527 mcview_state_machine_t state_after_combining;
529 state_after_combining = *state;
530 if (!mcview_get_next_maybe_nroff_char (view, &state_after_combining, &cs[i], NULL))
531 return i;
532 if (!mcview_ismark (view, cs[i]) || !mcview_isprint (view, cs[i]))
533 return i;
534 if (g_unichar_type (cs[i]) == G_UNICODE_SPACING_MARK)
536 /* Only allow as the first combining char. Stop processing in either case. */
537 if (i == 1)
539 *state = state_after_combining;
540 i++;
542 return i;
544 *state = state_after_combining;
546 return i;
549 /* --------------------------------------------------------------------------------------------- */
551 * Parse, format and possibly display one visual line of text.
553 * Formatting starts at the given "state" (which encodes the file offset and parser and formatter's
554 * internal state). In unwrap mode, this should point to the beginning of the paragraph with the
555 * default state, the additional horizontal scrolling is added here. In wrap mode, this should
556 * point to the beginning of the line, with the proper state at that point.
558 * In wrap mode, if a line ends in a newline, it is consumed, even if it's exactly at the right
559 * edge. In unwrap mode, the whole remaining line, including the newline is consumed. Displaying
560 * the next line should start at "state"'s new value, or if we displayed the bottom line then
561 * state->offset tells the file offset to be shown in the top bar.
563 * If "row" is offscreen, don't actually display the line but still update "state" and return the
564 * proper value. This is used by mcview_wrap_move_down to advance in the file.
566 * @param view ...
567 * @param state the parser-formatter state machine's state, updated
568 * @param row print to this row
569 * @param paragraph_ended store TRUE if paragraph ended by newline or EOF, FALSE if wraps to next
570 * line
571 * @param linewidth store the width of the line here
572 * @return the number of rows, that is, 0 if we were already at EOF, otherwise 1
574 static int
575 mcview_display_line (WView *view, mcview_state_machine_t *state, int row,
576 gboolean *paragraph_ended, off_t *linewidth)
578 const WRect *r = &view->data_area;
579 off_t dpy_text_column = view->mode_flags.wrap ? 0 : view->dpy_text_column;
580 int col = 0;
581 int cs[1 + MAX_COMBINING_CHARS];
582 char str[(1 + MAX_COMBINING_CHARS) * UTF8_CHAR_LEN + 1];
583 int i, j;
585 if (paragraph_ended != NULL)
586 *paragraph_ended = TRUE;
588 if (!view->mode_flags.wrap && (row < 0 || row >= r->lines) && linewidth == NULL)
590 /* Optimization: Fast forward to the end of the line, rather than carefully
591 * parsing and then not actually displaying it. */
592 off_t eol;
593 int retval;
595 eol = mcview_eol (view, state->offset);
596 retval = (eol > state->offset) ? 1 : 0;
598 mcview_state_machine_init (state, eol);
599 return retval;
602 while (TRUE)
604 int charwidth = 0;
605 mcview_state_machine_t state_saved;
606 int n;
607 int color;
609 state_saved = *state;
610 n = mcview_next_combining_char_sequence (view, state, cs, 1 + MAX_COMBINING_CHARS, &color);
611 if (n == 0)
613 if (linewidth != NULL)
614 *linewidth = col;
615 return (col > 0) ? 1 : 0;
618 if (view->search_start <= state->offset && state->offset < view->search_end)
619 color = VIEW_SELECTED_COLOR;
621 if (cs[0] == '\n')
623 /* New line: reset all formatting state for the next paragraph. */
624 mcview_state_machine_init (state, state->offset);
625 if (linewidth != NULL)
626 *linewidth = col;
627 return 1;
630 if (mcview_is_non_spacing_mark (view, cs[0]))
632 /* Lonely combining character. Probably leftover after too many combining chars. Just ignore. */
633 continue;
636 /* Nonprintable, or lonely spacing mark */
637 if ((!mcview_isprint (view, cs[0]) || mcview_ismark (view, cs[0])) && cs[0] != '\t')
638 cs[0] = '.';
640 for (i = 0; i < n; i++)
641 charwidth += mcview_wcwidth (view, cs[i]);
643 /* Adjust the width for TAB. It's handled below along with the normal characters,
644 * so that it's wrapped consistently with them, and is painted with the proper
645 * attributes (although currently it can't have a special color). */
646 if (cs[0] == '\t')
648 charwidth = option_tab_spacing - state->unwrapped_column % option_tab_spacing;
649 state->print_lonely_combining = TRUE;
651 else
652 state->print_lonely_combining = FALSE;
654 /* In wrap mode only: We're done with this row if the character sequence wouldn't fit.
655 * Except if at the first column, because then it wouldn't fit in the next row either.
656 * In this extreme case let the unwrapped code below do its best to display it. */
657 if (view->mode_flags.wrap && (off_t) col + charwidth > dpy_text_column + (off_t) r->cols
658 && col > 0)
660 *state = state_saved;
661 if (paragraph_ended != NULL)
662 *paragraph_ended = FALSE;
663 if (linewidth != NULL)
664 *linewidth = col;
665 return 1;
668 /* Display, unless outside of the viewport. */
669 if (row >= 0 && row < r->lines)
671 if ((off_t) col >= dpy_text_column &&
672 (off_t) col + charwidth <= dpy_text_column + (off_t) r->cols)
674 /* The combining character sequence fits entirely in the viewport. Print it. */
675 tty_setcolor (color);
676 widget_gotoyx (view, r->y + row, r->x + ((off_t) col - dpy_text_column));
677 if (cs[0] == '\t')
679 for (i = 0; i < charwidth; i++)
680 tty_print_char (' ');
682 else
684 j = 0;
685 for (i = 0; i < n; i++)
686 j += mcview_char_display (view, cs[i], str + j);
687 str[j] = '\0';
688 /* This is probably a bug in our tty layer, but tty_print_string
689 * normalizes the string, whereas tty_printf doesn't. Don't normalize,
690 * since we handle combining characters ourselves correctly, it's
691 * better if they are copy-pasted correctly. Ticket 3255. */
692 tty_printf ("%s", str);
695 else if ((off_t) col < dpy_text_column && (off_t) col + charwidth > dpy_text_column)
697 /* The combining character sequence would cross the left edge of the viewport.
698 * This cannot happen with wrap mode. Print replacement character(s),
699 * or spaces with the correct attributes for partial Tabs. */
700 tty_setcolor (color);
701 for (i = dpy_text_column;
702 i < (off_t) col + charwidth && i < dpy_text_column + (off_t) r->cols; i++)
704 widget_gotoyx (view, r->y + row, r->x + (i - dpy_text_column));
705 tty_print_anychar ((cs[0] == '\t') ? ' ' : PARTIAL_CJK_AT_LEFT_MARGIN);
708 else if ((off_t) col < dpy_text_column + (off_t) r->cols &&
709 (off_t) col + charwidth > dpy_text_column + (off_t) r->cols)
711 /* The combining character sequence would cross the right edge of the viewport
712 * and we're not wrapping. Print replacement character(s),
713 * or spaces with the correct attributes for partial Tabs. */
714 tty_setcolor (color);
715 for (i = col; i < dpy_text_column + (off_t) r->cols; i++)
717 widget_gotoyx (view, r->y + row, r->x + (i - dpy_text_column));
718 tty_print_anychar ((cs[0] == '\t') ? ' ' : PARTIAL_CJK_AT_RIGHT_MARGIN);
723 col += charwidth;
724 state->unwrapped_column += charwidth;
726 if (!view->mode_flags.wrap && (off_t) col >= dpy_text_column + (off_t) r->cols
727 && linewidth == NULL)
729 /* Optimization: Fast forward to the end of the line, rather than carefully
730 * parsing and then not actually displaying it. */
731 off_t eol;
733 eol = mcview_eol (view, state->offset);
734 mcview_state_machine_init (state, eol);
735 return 1;
740 /* --------------------------------------------------------------------------------------------- */
742 * Parse, format and possibly display one paragraph (perhaps not from the beginning).
744 * Formatting starts at the given "state" (which encodes the file offset and parser and formatter's
745 * internal state). In unwrap mode, this should point to the beginning of the paragraph with the
746 * default state, the additional horizontal scrolling is added here. In wrap mode, this may point
747 * to the beginning of the line within a paragraph (to display the partial paragraph at the top),
748 * with the proper state at that point.
750 * Displaying the next paragraph should start at "state"'s new value, or if we displayed the bottom
751 * line then state->offset tells the file offset to be shown in the top bar.
753 * If "row" is negative, don't display the first abs(row) lines and display the rest from the top.
754 * This was a nice idea but it's now unused :)
756 * If "row" is too large, don't display the paragraph at all but still return the number of lines.
757 * This is used when moving upwards.
759 * @param view ...
760 * @param state the parser-formatter state machine's state, updated
761 * @param row print starting at this row
762 * @return the number of rows the paragraphs is wrapped to, that is, 0 if we were already at EOF,
763 * otherwise 1 in unwrap mode, >= 1 in wrap mode. We stop when reaching the bottom of the
764 * viewport, it's not counted how many more lines the paragraph would occupy
766 static int
767 mcview_display_paragraph (WView *view, mcview_state_machine_t *state, int row)
769 int lines = 0;
771 while (TRUE)
773 gboolean paragraph_ended;
775 lines += mcview_display_line (view, state, row, &paragraph_ended, NULL);
776 if (paragraph_ended)
777 return lines;
779 if (row < view->data_area.lines)
781 row++;
782 /* stop if bottom of screen reached */
783 if (row >= view->data_area.lines)
784 return lines;
789 /* --------------------------------------------------------------------------------------------- */
791 * Recompute dpy_state_top from dpy_start and dpy_paragraph_skip_lines. Clamp
792 * dpy_paragraph_skip_lines if necessary.
794 * This method should be called in wrap mode after changing one of the parsing or formatting
795 * properties (e.g. window width, encoding, nroff), or when switching to wrap mode from unwrap or
796 * hex.
798 * If we stayed within the same paragraph then try to keep the vertical offset within that
799 * paragraph as well. It might happen though that the paragraph became shorter than our desired
800 * vertical position, in that case move to its last row.
802 static void
803 mcview_wrap_fixup (WView *view)
805 int lines = view->dpy_paragraph_skip_lines;
807 if (!view->dpy_wrap_dirty)
808 return;
809 view->dpy_wrap_dirty = FALSE;
811 view->dpy_paragraph_skip_lines = 0;
812 mcview_state_machine_init (&view->dpy_state_top, view->dpy_start);
814 while (lines-- != 0)
816 mcview_state_machine_t state_prev;
817 gboolean paragraph_ended;
819 state_prev = view->dpy_state_top;
820 if (mcview_display_line (view, &view->dpy_state_top, -1, &paragraph_ended, NULL) == 0)
821 break;
822 if (paragraph_ended)
824 view->dpy_state_top = state_prev;
825 break;
827 view->dpy_paragraph_skip_lines++;
831 /* --------------------------------------------------------------------------------------------- */
832 /*** public functions ****************************************************************************/
833 /* --------------------------------------------------------------------------------------------- */
836 * In both wrap and unwrap modes, dpy_start points to the beginning of the paragraph.
838 * In unwrap mode, start displaying from this position, probably applying an additional horizontal
839 * scroll.
841 * In wrap mode, an additional dpy_paragraph_skip_lines lines are skipped from the top of this
842 * paragraph. dpy_state_top contains the position and parser-formatter state corresponding to the
843 * top left corner so we can just start rendering from here. Unless dpy_wrap_dirty is set in which
844 * case dpy_state_top is invalid and we need to recompute first.
846 void
847 mcview_display_text (WView *view)
849 const WRect *r = &view->data_area;
850 int row;
851 mcview_state_machine_t state;
852 gboolean again;
856 int n;
858 again = FALSE;
860 mcview_display_clean (view);
861 mcview_display_ruler (view);
863 if (!view->mode_flags.wrap)
864 mcview_state_machine_init (&state, view->dpy_start);
865 else
867 mcview_wrap_fixup (view);
868 state = view->dpy_state_top;
871 for (row = 0; row < r->lines; row += n)
873 n = mcview_display_paragraph (view, &state, row);
874 if (n == 0)
876 /* In the rare case that displaying didn't start at the beginning
877 * of the file, yet there are some empty lines at the bottom,
878 * scroll the file and display again. This happens when e.g. the
879 * window is made bigger, or the file becomes shorter due to
880 * charset change or enabling nroff. */
881 if ((view->mode_flags.wrap ? view->dpy_state_top.offset : view->dpy_start) > 0)
883 mcview_ascii_move_up (view, r->lines - row);
884 again = TRUE;
886 break;
890 while (again);
892 view->dpy_end = state.offset;
893 view->dpy_state_bottom = state;
895 tty_setcolor (VIEW_NORMAL_COLOR);
896 if (mcview_show_eof != NULL && mcview_show_eof[0] != '\0')
897 while (row < r->lines)
899 widget_gotoyx (view, r->y + row, r->x);
900 /* TODO: should make it no wider than the viewport */
901 tty_print_string (mcview_show_eof);
902 row++;
906 /* --------------------------------------------------------------------------------------------- */
908 * Move down.
910 * It's very simple. Just invisibly format the next "lines" lines, carefully carrying the formatter
911 * state in wrap mode. But before each step we need to check if we've already hit the end of the
912 * file, in that case we can no longer move. This is done by walking from dpy_state_bottom.
914 * Note that this relies on mcview_display_text() setting dpy_state_bottom to its correct value
915 * upon rendering the screen contents. So don't call this function from other functions (e.g. at
916 * the bottom of mcview_ascii_move_up()) which invalidate this value.
918 void
919 mcview_ascii_move_down (WView *view, off_t lines)
921 while (lines-- != 0)
923 gboolean paragraph_ended;
925 /* See if there's still data below the bottom line, by imaginarily displaying one
926 * more line. This takes care of reading more data into growbuf, if required.
927 * If the end position didn't advance, we're at EOF and hence bail out. */
928 if (mcview_display_line (view, &view->dpy_state_bottom, -1, &paragraph_ended, NULL) == 0)
929 break;
931 /* Okay, there's enough data. Move by 1 row at the top, too. No need to check for
932 * EOF, that can't happen. */
933 if (!view->mode_flags.wrap)
935 view->dpy_start = mcview_eol (view, view->dpy_start);
936 view->dpy_paragraph_skip_lines = 0;
937 view->dpy_wrap_dirty = TRUE;
939 else
941 mcview_display_line (view, &view->dpy_state_top, -1, &paragraph_ended, NULL);
942 if (!paragraph_ended)
943 view->dpy_paragraph_skip_lines++;
944 else
946 view->dpy_start = view->dpy_state_top.offset;
947 view->dpy_paragraph_skip_lines = 0;
953 /* --------------------------------------------------------------------------------------------- */
955 * Move up.
957 * Unwrap mode: Piece of cake. Wrap mode: If we'd walk back more than the current line offset
958 * within the paragraph, we need to jump back to the previous paragraph and compute its height to
959 * see if we start from that paragraph, and repeat this if necessary. Once we're within the desired
960 * paragraph, we still need to format it from its beginning to know the state.
962 * See the top of this file for comments about MAX_BACKWARDS_WALK_IN_PARAGRAPH.
964 * force_max is a nice protection against the rare extreme case that the file underneath us
965 * changes, we don't want to endlessly consume a file of maybe full of zeros upon moving upwards.
967 void
968 mcview_ascii_move_up (WView *view, off_t lines)
970 if (!view->mode_flags.wrap)
972 while (lines-- != 0)
973 view->dpy_start = mcview_bol (view, view->dpy_start - 1, 0);
974 view->dpy_paragraph_skip_lines = 0;
975 view->dpy_wrap_dirty = TRUE;
977 else
979 int i;
981 while (lines > view->dpy_paragraph_skip_lines)
983 /* We need to go back to the previous paragraph. */
984 if (view->dpy_start == 0)
986 /* Oops, we're already in the first paragraph. */
987 view->dpy_paragraph_skip_lines = 0;
988 mcview_state_machine_init (&view->dpy_state_top, 0);
989 return;
991 lines -= view->dpy_paragraph_skip_lines;
992 view->force_max = view->dpy_start;
993 view->dpy_start =
994 mcview_bol (view, view->dpy_start - 1,
995 view->dpy_start - MAX_BACKWARDS_WALK_IN_PARAGRAPH);
996 mcview_state_machine_init (&view->dpy_state_top, view->dpy_start);
997 /* This is a tricky way of denoting that we're at the end of the paragraph.
998 * Normally we'd jump to the next paragraph and reset paragraph_skip_lines. But for
999 * walking backwards this is exactly what we need. */
1000 view->dpy_paragraph_skip_lines =
1001 mcview_display_paragraph (view, &view->dpy_state_top, view->data_area.lines);
1002 view->force_max = -1;
1005 /* Okay, we have have dpy_start pointing to the desired paragraph, and we still need to
1006 * walk back "lines" lines from the current "dpy_paragraph_skip_lines" offset. We can't do
1007 * that, so walk from the beginning of the paragraph. */
1008 mcview_state_machine_init (&view->dpy_state_top, view->dpy_start);
1009 view->dpy_paragraph_skip_lines -= lines;
1010 for (i = 0; i < view->dpy_paragraph_skip_lines; i++)
1011 mcview_display_line (view, &view->dpy_state_top, -1, NULL, NULL);
1015 /* --------------------------------------------------------------------------------------------- */
1017 void
1018 mcview_ascii_moveto_bol (WView *view)
1020 if (!view->mode_flags.wrap)
1021 view->dpy_text_column = 0;
1024 /* --------------------------------------------------------------------------------------------- */
1026 void
1027 mcview_ascii_moveto_eol (WView *view)
1029 if (!view->mode_flags.wrap)
1031 mcview_state_machine_t state;
1032 off_t linewidth;
1034 /* Get the width of the topmost paragraph. */
1035 mcview_state_machine_init (&state, view->dpy_start);
1036 mcview_display_line (view, &state, -1, NULL, &linewidth);
1037 view->dpy_text_column = DOZ (linewidth, (off_t) view->data_area.cols);
1041 /* --------------------------------------------------------------------------------------------- */
1043 void
1044 mcview_state_machine_init (mcview_state_machine_t *state, off_t offset)
1046 memset (state, 0, sizeof (*state));
1047 state->offset = offset;
1048 state->print_lonely_combining = TRUE;
1051 /* --------------------------------------------------------------------------------------------- */