Merge from trunk
[emacs.git] / src / bidi.c
blob1f3b196d5a41d35d49d583dd6bfae07f698e284c
1 /* Low-level bidirectional buffer-scanning functions for GNU Emacs.
2 Copyright (C) 2000-2001, 2004-2005, 2009-2011
3 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20 /* Written by Eli Zaretskii <eliz@gnu.org>.
22 A sequential implementation of the Unicode Bidirectional algorithm,
23 as per UAX#9, a part of the Unicode Standard.
25 Unlike the reference and most other implementations, this one is
26 designed to be called once for every character in the buffer or
27 string.
29 The main entry point is bidi_move_to_visually_next. Each time it
30 is called, it finds the next character in the visual order, and
31 returns its information in a special structure. The caller is then
32 expected to process this character for display or any other
33 purposes, and call bidi_move_to_visually_next for the next
34 character. See the comments in bidi_move_to_visually_next for more
35 details about its algorithm that finds the next visual-order
36 character by resolving their levels on the fly.
38 The two other entry points are bidi_paragraph_init and
39 bidi_mirror_char. The first determines the base direction of a
40 paragraph, while the second returns the mirrored version of its
41 argument character.
43 If you want to understand the code, you will have to read it
44 together with the relevant portions of UAX#9. The comments include
45 references to UAX#9 rules, for that very reason.
47 A note about references to UAX#9 rules: if the reference says
48 something like "X9/Retaining", it means that you need to refer to
49 rule X9 and to its modifications decribed in the "Implementation
50 Notes" section of UAX#9, under "Retaining Format Codes". */
52 #include <config.h>
53 #include <stdio.h>
54 #include <setjmp.h>
56 #include "lisp.h"
57 #include "buffer.h"
58 #include "character.h"
59 #include "dispextern.h"
61 static int bidi_initialized = 0;
63 static Lisp_Object bidi_type_table, bidi_mirror_table;
65 #define LRM_CHAR 0x200E
66 #define RLM_CHAR 0x200F
67 #define BIDI_EOB -1
69 /* Local data structures. (Look in dispextern.h for the rest.) */
71 /* What we need to know about the current paragraph. */
72 struct bidi_paragraph_info {
73 EMACS_INT start_bytepos; /* byte position where it begins */
74 EMACS_INT end_bytepos; /* byte position where it ends */
75 int embedding_level; /* its basic embedding level */
76 bidi_dir_t base_dir; /* its base direction */
79 /* Data type for describing the bidirectional character categories. */
80 typedef enum {
81 UNKNOWN_BC,
82 NEUTRAL,
83 WEAK,
84 STRONG
85 } bidi_category_t;
87 extern int bidi_ignore_explicit_marks_for_paragraph_level EXTERNALLY_VISIBLE;
88 int bidi_ignore_explicit_marks_for_paragraph_level = 1;
90 static Lisp_Object paragraph_start_re, paragraph_separate_re;
91 static Lisp_Object Qparagraph_start, Qparagraph_separate;
93 static void
94 bidi_initialize (void)
97 #include "biditype.h"
98 #include "bidimirror.h"
100 int i;
102 bidi_type_table = Fmake_char_table (Qnil, make_number (STRONG_L));
103 staticpro (&bidi_type_table);
105 for (i = 0; i < sizeof bidi_type / sizeof bidi_type[0]; i++)
106 char_table_set_range (bidi_type_table, bidi_type[i].from, bidi_type[i].to,
107 make_number (bidi_type[i].type));
109 bidi_mirror_table = Fmake_char_table (Qnil, Qnil);
110 staticpro (&bidi_mirror_table);
112 for (i = 0; i < sizeof bidi_mirror / sizeof bidi_mirror[0]; i++)
113 char_table_set (bidi_mirror_table, bidi_mirror[i].from,
114 make_number (bidi_mirror[i].to));
116 Qparagraph_start = intern ("paragraph-start");
117 staticpro (&Qparagraph_start);
118 paragraph_start_re = Fsymbol_value (Qparagraph_start);
119 if (!STRINGP (paragraph_start_re))
120 paragraph_start_re = build_string ("\f\\|[ \t]*$");
121 staticpro (&paragraph_start_re);
122 Qparagraph_separate = intern ("paragraph-separate");
123 staticpro (&Qparagraph_separate);
124 paragraph_separate_re = Fsymbol_value (Qparagraph_separate);
125 if (!STRINGP (paragraph_separate_re))
126 paragraph_separate_re = build_string ("[ \t\f]*$");
127 staticpro (&paragraph_separate_re);
128 bidi_initialized = 1;
131 /* Return the bidi type of a character CH, subject to the current
132 directional OVERRIDE. */
133 static inline bidi_type_t
134 bidi_get_type (int ch, bidi_dir_t override)
136 bidi_type_t default_type;
138 if (ch == BIDI_EOB)
139 return NEUTRAL_B;
140 if (ch < 0 || ch > MAX_CHAR)
141 abort ();
143 default_type = (bidi_type_t) XINT (CHAR_TABLE_REF (bidi_type_table, ch));
145 if (override == NEUTRAL_DIR)
146 return default_type;
148 switch (default_type)
150 /* Although UAX#9 does not tell, it doesn't make sense to
151 override NEUTRAL_B and LRM/RLM characters. */
152 case NEUTRAL_B:
153 case LRE:
154 case LRO:
155 case RLE:
156 case RLO:
157 case PDF:
158 return default_type;
159 default:
160 switch (ch)
162 case LRM_CHAR:
163 case RLM_CHAR:
164 return default_type;
165 default:
166 if (override == L2R) /* X6 */
167 return STRONG_L;
168 else if (override == R2L)
169 return STRONG_R;
170 else
171 abort (); /* can't happen: handled above */
176 static void
177 bidi_check_type (bidi_type_t type)
179 if (type < UNKNOWN_BT || type > NEUTRAL_ON)
180 abort ();
183 /* Given a bidi TYPE of a character, return its category. */
184 static inline bidi_category_t
185 bidi_get_category (bidi_type_t type)
187 switch (type)
189 case UNKNOWN_BT:
190 return UNKNOWN_BC;
191 case STRONG_L:
192 case STRONG_R:
193 case STRONG_AL:
194 case LRE:
195 case LRO:
196 case RLE:
197 case RLO:
198 return STRONG;
199 case PDF: /* ??? really?? */
200 case WEAK_EN:
201 case WEAK_ES:
202 case WEAK_ET:
203 case WEAK_AN:
204 case WEAK_CS:
205 case WEAK_NSM:
206 case WEAK_BN:
207 return WEAK;
208 case NEUTRAL_B:
209 case NEUTRAL_S:
210 case NEUTRAL_WS:
211 case NEUTRAL_ON:
212 return NEUTRAL;
213 default:
214 abort ();
218 /* Return the mirrored character of C, if it has one. If C has no
219 mirrored counterpart, return C.
220 Note: The conditions in UAX#9 clause L4 regarding the surrounding
221 context must be tested by the caller. */
223 bidi_mirror_char (int c)
225 Lisp_Object val;
227 if (c == BIDI_EOB)
228 return c;
229 if (c < 0 || c > MAX_CHAR)
230 abort ();
232 val = CHAR_TABLE_REF (bidi_mirror_table, c);
233 if (INTEGERP (val))
235 int v = XINT (val);
237 if (v < 0 || v > MAX_CHAR)
238 abort ();
240 return v;
243 return c;
246 /* Copy the bidi iterator from FROM to TO. To save cycles, this only
247 copies the part of the level stack that is actually in use. */
248 static inline void
249 bidi_copy_it (struct bidi_it *to, struct bidi_it *from)
251 int i;
253 /* Copy everything except the level stack and beyond. */
254 memcpy (to, from, offsetof (struct bidi_it, level_stack[0]));
256 /* Copy the active part of the level stack. */
257 to->level_stack[0] = from->level_stack[0]; /* level zero is always in use */
258 for (i = 1; i <= from->stack_idx; i++)
259 to->level_stack[i] = from->level_stack[i];
262 /* Caching the bidi iterator states. */
264 #define BIDI_CACHE_CHUNK 200
265 static struct bidi_it *bidi_cache;
266 static size_t bidi_cache_size = 0;
267 static size_t elsz = sizeof (struct bidi_it);
268 static int bidi_cache_idx; /* next unused cache slot */
269 static int bidi_cache_last_idx; /* slot of last cache hit */
271 static inline void
272 bidi_cache_reset (void)
274 bidi_cache_idx = 0;
275 bidi_cache_last_idx = -1;
278 static inline void
279 bidi_cache_shrink (void)
281 if (bidi_cache_size > BIDI_CACHE_CHUNK)
283 bidi_cache_size = BIDI_CACHE_CHUNK;
284 bidi_cache =
285 (struct bidi_it *) xrealloc (bidi_cache, bidi_cache_size * elsz);
287 bidi_cache_reset ();
290 static inline void
291 bidi_cache_fetch_state (int idx, struct bidi_it *bidi_it)
293 int current_scan_dir = bidi_it->scan_dir;
295 if (idx < 0 || idx >= bidi_cache_idx)
296 abort ();
298 bidi_copy_it (bidi_it, &bidi_cache[idx]);
299 bidi_it->scan_dir = current_scan_dir;
300 bidi_cache_last_idx = idx;
303 /* Find a cached state with a given CHARPOS and resolved embedding
304 level less or equal to LEVEL. if LEVEL is -1, disregard the
305 resolved levels in cached states. DIR, if non-zero, means search
306 in that direction from the last cache hit. */
307 static inline int
308 bidi_cache_search (EMACS_INT charpos, int level, int dir)
310 int i, i_start;
312 if (bidi_cache_idx)
314 if (charpos < bidi_cache[bidi_cache_last_idx].charpos)
316 dir = -1;
317 i_start = bidi_cache_last_idx - 1;
319 else if (charpos > (bidi_cache[bidi_cache_last_idx].charpos
320 + bidi_cache[bidi_cache_last_idx].nchars - 1))
322 dir = 1;
323 i_start = bidi_cache_last_idx + 1;
325 else if (dir)
326 i_start = bidi_cache_last_idx;
327 else
329 dir = -1;
330 i_start = bidi_cache_idx - 1;
333 if (dir < 0)
335 /* Linear search for now; FIXME! */
336 for (i = i_start; i >= 0; i--)
337 if (bidi_cache[i].charpos <= charpos
338 && charpos < bidi_cache[i].charpos + bidi_cache[i].nchars
339 && (level == -1 || bidi_cache[i].resolved_level <= level))
340 return i;
342 else
344 for (i = i_start; i < bidi_cache_idx; i++)
345 if (bidi_cache[i].charpos <= charpos
346 && charpos < bidi_cache[i].charpos + bidi_cache[i].nchars
347 && (level == -1 || bidi_cache[i].resolved_level <= level))
348 return i;
352 return -1;
355 /* Find a cached state where the resolved level changes to a value
356 that is lower than LEVEL, and return its cache slot index. DIR is
357 the direction to search, starting with the last used cache slot.
358 BEFORE, if non-zero, means return the index of the slot that is
359 ``before'' the level change in the search direction. That is,
360 given the cached levels like this:
362 1122333442211
363 AB C
365 and assuming we are at the position cached at the slot marked with
366 C, searching backwards (DIR = -1) for LEVEL = 2 will return the
367 index of slot B or A, depending whether BEFORE is, respectively,
368 non-zero or zero. */
369 static int
370 bidi_cache_find_level_change (int level, int dir, int before)
372 if (bidi_cache_idx)
374 int i = dir ? bidi_cache_last_idx : bidi_cache_idx - 1;
375 int incr = before ? 1 : 0;
377 if (!dir)
378 dir = -1;
379 else if (!incr)
380 i += dir;
382 if (dir < 0)
384 while (i >= incr)
386 if (bidi_cache[i - incr].resolved_level >= 0
387 && bidi_cache[i - incr].resolved_level < level)
388 return i;
389 i--;
392 else
394 while (i < bidi_cache_idx - incr)
396 if (bidi_cache[i + incr].resolved_level >= 0
397 && bidi_cache[i + incr].resolved_level < level)
398 return i;
399 i++;
404 return -1;
407 static inline void
408 bidi_cache_iterator_state (struct bidi_it *bidi_it, int resolved)
410 int idx;
412 /* We should never cache on backward scans. */
413 if (bidi_it->scan_dir == -1)
414 abort ();
415 idx = bidi_cache_search (bidi_it->charpos, -1, 1);
417 if (idx < 0)
419 idx = bidi_cache_idx;
420 /* Enlarge the cache as needed. */
421 if (idx >= bidi_cache_size)
423 bidi_cache_size += BIDI_CACHE_CHUNK;
424 bidi_cache =
425 (struct bidi_it *) xrealloc (bidi_cache, bidi_cache_size * elsz);
427 /* Character positions should correspond to cache positions 1:1.
428 If we are outside the range of cached positions, the cache is
429 useless and must be reset. */
430 if (idx > 0 &&
431 (bidi_it->charpos > (bidi_cache[idx - 1].charpos
432 + bidi_cache[idx - 1].nchars)
433 || bidi_it->charpos < bidi_cache[0].charpos))
435 bidi_cache_reset ();
436 idx = 0;
438 if (bidi_it->nchars <= 0)
439 abort ();
440 bidi_copy_it (&bidi_cache[idx], bidi_it);
441 if (!resolved)
442 bidi_cache[idx].resolved_level = -1;
444 else
446 /* Copy only the members which could have changed, to avoid
447 costly copying of the entire struct. */
448 bidi_cache[idx].type = bidi_it->type;
449 bidi_check_type (bidi_it->type);
450 bidi_cache[idx].type_after_w1 = bidi_it->type_after_w1;
451 bidi_check_type (bidi_it->type_after_w1);
452 if (resolved)
453 bidi_cache[idx].resolved_level = bidi_it->resolved_level;
454 else
455 bidi_cache[idx].resolved_level = -1;
456 bidi_cache[idx].invalid_levels = bidi_it->invalid_levels;
457 bidi_cache[idx].invalid_rl_levels = bidi_it->invalid_rl_levels;
458 bidi_cache[idx].next_for_neutral = bidi_it->next_for_neutral;
459 bidi_cache[idx].next_for_ws = bidi_it->next_for_ws;
460 bidi_cache[idx].ignore_bn_limit = bidi_it->ignore_bn_limit;
463 bidi_cache_last_idx = idx;
464 if (idx >= bidi_cache_idx)
465 bidi_cache_idx = idx + 1;
468 static inline bidi_type_t
469 bidi_cache_find (EMACS_INT charpos, int level, struct bidi_it *bidi_it)
471 int i = bidi_cache_search (charpos, level, bidi_it->scan_dir);
473 if (i >= 0)
475 bidi_dir_t current_scan_dir = bidi_it->scan_dir;
477 bidi_copy_it (bidi_it, &bidi_cache[i]);
478 bidi_cache_last_idx = i;
479 /* Don't let scan direction from from the cached state override
480 the current scan direction. */
481 bidi_it->scan_dir = current_scan_dir;
482 return bidi_it->type;
485 return UNKNOWN_BT;
488 static inline int
489 bidi_peek_at_next_level (struct bidi_it *bidi_it)
491 if (bidi_cache_idx == 0 || bidi_cache_last_idx == -1)
492 abort ();
493 return bidi_cache[bidi_cache_last_idx + bidi_it->scan_dir].resolved_level;
496 /* Check if buffer position CHARPOS/BYTEPOS is the end of a paragraph.
497 Value is the non-negative length of the paragraph separator
498 following the buffer position, -1 if position is at the beginning
499 of a new paragraph, or -2 if position is neither at beginning nor
500 at end of a paragraph. */
501 static EMACS_INT
502 bidi_at_paragraph_end (EMACS_INT charpos, EMACS_INT bytepos)
504 Lisp_Object sep_re;
505 Lisp_Object start_re;
506 EMACS_INT val;
508 sep_re = paragraph_separate_re;
509 start_re = paragraph_start_re;
511 val = fast_looking_at (sep_re, charpos, bytepos, ZV, ZV_BYTE, Qnil);
512 if (val < 0)
514 if (fast_looking_at (start_re, charpos, bytepos, ZV, ZV_BYTE, Qnil) >= 0)
515 val = -1;
516 else
517 val = -2;
520 return val;
523 /* Determine the start-of-run (sor) directional type given the two
524 embedding levels on either side of the run boundary. Also, update
525 the saved info about previously seen characters, since that info is
526 generally valid for a single level run. */
527 static inline void
528 bidi_set_sor_type (struct bidi_it *bidi_it, int level_before, int level_after)
530 int higher_level = level_before > level_after ? level_before : level_after;
532 /* The prev_was_pdf gork is required for when we have several PDFs
533 in a row. In that case, we want to compute the sor type for the
534 next level run only once: when we see the first PDF. That's
535 because the sor type depends only on the higher of the two levels
536 that we find on the two sides of the level boundary (see UAX#9,
537 clause X10), and so we don't need to know the final embedding
538 level to which we descend after processing all the PDFs. */
539 if (!bidi_it->prev_was_pdf || level_before < level_after)
540 /* FIXME: should the default sor direction be user selectable? */
541 bidi_it->sor = (higher_level & 1) != 0 ? R2L : L2R;
542 if (level_before > level_after)
543 bidi_it->prev_was_pdf = 1;
545 bidi_it->prev.type = UNKNOWN_BT;
546 bidi_it->last_strong.type = bidi_it->last_strong.type_after_w1 =
547 bidi_it->last_strong.orig_type = UNKNOWN_BT;
548 bidi_it->prev_for_neutral.type = bidi_it->sor == R2L ? STRONG_R : STRONG_L;
549 bidi_it->prev_for_neutral.charpos = bidi_it->charpos;
550 bidi_it->prev_for_neutral.bytepos = bidi_it->bytepos;
551 bidi_it->next_for_neutral.type = bidi_it->next_for_neutral.type_after_w1 =
552 bidi_it->next_for_neutral.orig_type = UNKNOWN_BT;
553 bidi_it->ignore_bn_limit = 0; /* meaning it's unknown */
556 /* Perform initializations for reordering a new line of bidi text. */
557 static void
558 bidi_line_init (struct bidi_it *bidi_it)
560 bidi_it->scan_dir = 1; /* FIXME: do we need to have control on this? */
561 bidi_it->resolved_level = bidi_it->level_stack[0].level;
562 bidi_it->level_stack[0].override = NEUTRAL_DIR; /* X1 */
563 bidi_it->invalid_levels = 0;
564 bidi_it->invalid_rl_levels = -1;
565 bidi_it->next_en_pos = -1;
566 bidi_it->next_for_ws.type = UNKNOWN_BT;
567 bidi_set_sor_type (bidi_it,
568 bidi_it->paragraph_dir == R2L ? 1 : 0,
569 bidi_it->level_stack[0].level); /* X10 */
571 bidi_cache_reset ();
574 /* Fetch and return the character at BYTEPOS/CHARPOS. If that
575 character is covered by a display string, treat the entire run of
576 covered characters as a single character u+FFFC, and return their
577 combined length in CH_LEN and NCHARS. DISP_POS specifies the
578 character position of the next display string, or -1 if not yet
579 computed. When the next character is at or beyond that position,
580 the function updates DISP_POS with the position of the next display
581 string. */
582 static inline int
583 bidi_fetch_char (EMACS_INT bytepos, EMACS_INT charpos, EMACS_INT *disp_pos,
584 int frame_window_p, EMACS_INT *ch_len, EMACS_INT *nchars)
586 int ch;
588 /* FIXME: Support strings in addition to buffers. */
589 /* If we got past the last known position of display string, compute
590 the position of the next one. That position could be at BYTEPOS. */
591 if (charpos < ZV && charpos > *disp_pos)
592 *disp_pos = compute_display_string_pos (charpos, frame_window_p);
594 /* Fetch the character at BYTEPOS. */
595 if (bytepos >= ZV_BYTE)
597 ch = BIDI_EOB;
598 *ch_len = 1;
599 *nchars = 1;
600 *disp_pos = ZV;
602 else if (charpos >= *disp_pos)
604 EMACS_INT disp_end_pos;
606 /* We don't expect to find ourselves in the middle of a display
607 property. Hopefully, it will never be needed. */
608 if (charpos > *disp_pos)
609 abort ();
610 /* Return the Unicode Object Replacement Character to represent
611 the entire run of characters covered by the display
612 string. */
613 ch = 0xFFFC;
614 disp_end_pos = compute_display_string_end (*disp_pos);
615 *nchars = disp_end_pos - *disp_pos;
616 *ch_len = CHAR_TO_BYTE (disp_end_pos) - bytepos;
618 else
620 ch = FETCH_MULTIBYTE_CHAR (bytepos);
621 *nchars = 1;
622 *ch_len = CHAR_BYTES (ch);
625 /* If we just entered a run of characters covered by a display
626 string, compute the position of the next display string. */
627 if (charpos + *nchars <= ZV && charpos + *nchars > *disp_pos)
628 *disp_pos = compute_display_string_pos (charpos + *nchars, frame_window_p);
630 return ch;
633 /* Find the beginning of this paragraph by looking back in the buffer.
634 Value is the byte position of the paragraph's beginning. */
635 static EMACS_INT
636 bidi_find_paragraph_start (EMACS_INT pos, EMACS_INT pos_byte)
638 Lisp_Object re = paragraph_start_re;
639 EMACS_INT limit = ZV, limit_byte = ZV_BYTE;
641 while (pos_byte > BEGV_BYTE
642 && fast_looking_at (re, pos, pos_byte, limit, limit_byte, Qnil) < 0)
644 /* FIXME: What if the paragraph beginning is covered by a
645 display string? And what if a display string covering some
646 of the text over which we scan back includes
647 paragraph_start_re? */
648 pos = find_next_newline_no_quit (pos - 1, -1);
649 pos_byte = CHAR_TO_BYTE (pos);
651 return pos_byte;
654 /* Determine the base direction, a.k.a. base embedding level, of the
655 paragraph we are about to iterate through. If DIR is either L2R or
656 R2L, just use that. Otherwise, determine the paragraph direction
657 from the first strong directional character of the paragraph.
659 NO_DEFAULT_P non-zero means don't default to L2R if the paragraph
660 has no strong directional characters and both DIR and
661 bidi_it->paragraph_dir are NEUTRAL_DIR. In that case, search back
662 in the buffer until a paragraph is found with a strong character,
663 or until hitting BEGV. In the latter case, fall back to L2R. This
664 flag is used in current-bidi-paragraph-direction.
666 Note that this function gives the paragraph separator the same
667 direction as the preceding paragraph, even though Emacs generally
668 views the separartor as not belonging to any paragraph. */
669 void
670 bidi_paragraph_init (bidi_dir_t dir, struct bidi_it *bidi_it, int no_default_p)
672 EMACS_INT bytepos = bidi_it->bytepos;
673 EMACS_INT pstartbyte;
675 /* Special case for an empty buffer. */
676 if (bytepos == BEGV_BYTE && bytepos == ZV_BYTE)
677 dir = L2R;
678 /* We should never be called at EOB or before BEGV. */
679 else if (bytepos >= ZV_BYTE || bytepos < BEGV_BYTE)
680 abort ();
682 if (dir == L2R)
684 bidi_it->paragraph_dir = L2R;
685 bidi_it->new_paragraph = 0;
687 else if (dir == R2L)
689 bidi_it->paragraph_dir = R2L;
690 bidi_it->new_paragraph = 0;
692 else if (dir == NEUTRAL_DIR) /* P2 */
694 int ch;
695 EMACS_INT ch_len, nchars;
696 EMACS_INT pos, disp_pos = -1;
697 bidi_type_t type;
699 if (!bidi_initialized)
700 bidi_initialize ();
702 /* If we are inside a paragraph separator, we are just waiting
703 for the separator to be exhausted; use the previous paragraph
704 direction. But don't do that if we have been just reseated,
705 because we need to reinitialize below in that case. */
706 if (!bidi_it->first_elt
707 && bidi_it->charpos < bidi_it->separator_limit)
708 return;
710 /* If we are on a newline, get past it to where the next
711 paragraph might start. But don't do that at BEGV since then
712 we are potentially in a new paragraph that doesn't yet
713 exist. */
714 pos = bidi_it->charpos;
715 if (bytepos > BEGV_BYTE && FETCH_CHAR (bytepos) == '\n')
717 bytepos++;
718 pos++;
721 /* We are either at the beginning of a paragraph or in the
722 middle of it. Find where this paragraph starts. */
723 pstartbyte = bidi_find_paragraph_start (pos, bytepos);
724 bidi_it->separator_limit = -1;
725 bidi_it->new_paragraph = 0;
727 /* The following loop is run more than once only if NO_DEFAULT_P
728 is non-zero. */
729 do {
730 bytepos = pstartbyte;
731 pos = BYTE_TO_CHAR (bytepos);
732 ch = bidi_fetch_char (bytepos, pos, &disp_pos, bidi_it->frame_window_p,
733 &ch_len, &nchars);
734 type = bidi_get_type (ch, NEUTRAL_DIR);
736 for (pos += nchars, bytepos += ch_len;
737 /* NOTE: UAX#9 says to search only for L, AL, or R types
738 of characters, and ignore RLE, RLO, LRE, and LRO.
739 However, I'm not sure it makes sense to omit those 4;
740 should try with and without that to see the effect. */
741 (bidi_get_category (type) != STRONG)
742 || (bidi_ignore_explicit_marks_for_paragraph_level
743 && (type == RLE || type == RLO
744 || type == LRE || type == LRO));
745 type = bidi_get_type (ch, NEUTRAL_DIR))
747 if (type == NEUTRAL_B && bidi_at_paragraph_end (pos, bytepos) >= -1)
748 break;
749 if (bytepos >= ZV_BYTE)
751 /* Pretend there's a paragraph separator at end of
752 buffer. */
753 type = NEUTRAL_B;
754 break;
756 /* Fetch next character and advance to get past it. */
757 ch = bidi_fetch_char (bytepos, pos, &disp_pos,
758 bidi_it->frame_window_p, &ch_len, &nchars);
759 pos += nchars;
760 bytepos += ch_len;
762 if (type == STRONG_R || type == STRONG_AL) /* P3 */
763 bidi_it->paragraph_dir = R2L;
764 else if (type == STRONG_L)
765 bidi_it->paragraph_dir = L2R;
766 if (no_default_p && bidi_it->paragraph_dir == NEUTRAL_DIR)
768 /* If this paragraph is at BEGV, default to L2R. */
769 if (pstartbyte == BEGV_BYTE)
770 bidi_it->paragraph_dir = L2R; /* P3 and HL1 */
771 else
773 EMACS_INT prevpbyte = pstartbyte;
774 EMACS_INT p = BYTE_TO_CHAR (pstartbyte), pbyte = pstartbyte;
776 /* Find the beginning of the previous paragraph, if any. */
777 while (pbyte > BEGV_BYTE && prevpbyte >= pstartbyte)
779 /* FXIME: What if p is covered by a display
780 string? See also a FIXME inside
781 bidi_find_paragraph_start. */
782 p--;
783 pbyte = CHAR_TO_BYTE (p);
784 prevpbyte = bidi_find_paragraph_start (p, pbyte);
786 pstartbyte = prevpbyte;
789 } while (no_default_p && bidi_it->paragraph_dir == NEUTRAL_DIR);
791 else
792 abort ();
794 /* Contrary to UAX#9 clause P3, we only default the paragraph
795 direction to L2R if we have no previous usable paragraph
796 direction. This is allowed by the HL1 clause. */
797 if (bidi_it->paragraph_dir != L2R && bidi_it->paragraph_dir != R2L)
798 bidi_it->paragraph_dir = L2R; /* P3 and HL1 ``higher-level protocols'' */
799 if (bidi_it->paragraph_dir == R2L)
800 bidi_it->level_stack[0].level = 1;
801 else
802 bidi_it->level_stack[0].level = 0;
804 bidi_line_init (bidi_it);
807 /* Do whatever UAX#9 clause X8 says should be done at paragraph's
808 end. */
809 static inline void
810 bidi_set_paragraph_end (struct bidi_it *bidi_it)
812 bidi_it->invalid_levels = 0;
813 bidi_it->invalid_rl_levels = -1;
814 bidi_it->stack_idx = 0;
815 bidi_it->resolved_level = bidi_it->level_stack[0].level;
818 /* Initialize the bidi iterator from buffer/string position CHARPOS. */
819 void
820 bidi_init_it (EMACS_INT charpos, EMACS_INT bytepos, int frame_window_p,
821 struct bidi_it *bidi_it)
823 if (! bidi_initialized)
824 bidi_initialize ();
825 bidi_it->charpos = charpos;
826 bidi_it->bytepos = bytepos;
827 bidi_it->frame_window_p = frame_window_p;
828 bidi_it->nchars = -1; /* to be computed in bidi_resolve_explicit_1 */
829 bidi_it->first_elt = 1;
830 bidi_set_paragraph_end (bidi_it);
831 bidi_it->new_paragraph = 1;
832 bidi_it->separator_limit = -1;
833 bidi_it->type = NEUTRAL_B;
834 bidi_it->type_after_w1 = NEUTRAL_B;
835 bidi_it->orig_type = NEUTRAL_B;
836 bidi_it->prev_was_pdf = 0;
837 bidi_it->prev.type = bidi_it->prev.type_after_w1 =
838 bidi_it->prev.orig_type = UNKNOWN_BT;
839 bidi_it->last_strong.type = bidi_it->last_strong.type_after_w1 =
840 bidi_it->last_strong.orig_type = UNKNOWN_BT;
841 bidi_it->next_for_neutral.charpos = -1;
842 bidi_it->next_for_neutral.type =
843 bidi_it->next_for_neutral.type_after_w1 =
844 bidi_it->next_for_neutral.orig_type = UNKNOWN_BT;
845 bidi_it->prev_for_neutral.charpos = -1;
846 bidi_it->prev_for_neutral.type =
847 bidi_it->prev_for_neutral.type_after_w1 =
848 bidi_it->prev_for_neutral.orig_type = UNKNOWN_BT;
849 bidi_it->sor = L2R; /* FIXME: should it be user-selectable? */
850 bidi_it->disp_pos = -1; /* invalid/unknown */
851 bidi_cache_shrink ();
854 /* Push the current embedding level and override status; reset the
855 current level to LEVEL and the current override status to OVERRIDE. */
856 static inline void
857 bidi_push_embedding_level (struct bidi_it *bidi_it,
858 int level, bidi_dir_t override)
860 bidi_it->stack_idx++;
861 if (bidi_it->stack_idx >= BIDI_MAXLEVEL)
862 abort ();
863 bidi_it->level_stack[bidi_it->stack_idx].level = level;
864 bidi_it->level_stack[bidi_it->stack_idx].override = override;
867 /* Pop the embedding level and directional override status from the
868 stack, and return the new level. */
869 static inline int
870 bidi_pop_embedding_level (struct bidi_it *bidi_it)
872 /* UAX#9 says to ignore invalid PDFs. */
873 if (bidi_it->stack_idx > 0)
874 bidi_it->stack_idx--;
875 return bidi_it->level_stack[bidi_it->stack_idx].level;
878 /* Record in SAVED_INFO the information about the current character. */
879 static inline void
880 bidi_remember_char (struct bidi_saved_info *saved_info,
881 struct bidi_it *bidi_it)
883 saved_info->charpos = bidi_it->charpos;
884 saved_info->bytepos = bidi_it->bytepos;
885 saved_info->type = bidi_it->type;
886 bidi_check_type (bidi_it->type);
887 saved_info->type_after_w1 = bidi_it->type_after_w1;
888 bidi_check_type (bidi_it->type_after_w1);
889 saved_info->orig_type = bidi_it->orig_type;
890 bidi_check_type (bidi_it->orig_type);
893 /* Resolve the type of a neutral character according to the type of
894 surrounding strong text and the current embedding level. */
895 static inline bidi_type_t
896 bidi_resolve_neutral_1 (bidi_type_t prev_type, bidi_type_t next_type, int lev)
898 /* N1: European and Arabic numbers are treated as though they were R. */
899 if (next_type == WEAK_EN || next_type == WEAK_AN)
900 next_type = STRONG_R;
901 if (prev_type == WEAK_EN || prev_type == WEAK_AN)
902 prev_type = STRONG_R;
904 if (next_type == prev_type) /* N1 */
905 return next_type;
906 else if ((lev & 1) == 0) /* N2 */
907 return STRONG_L;
908 else
909 return STRONG_R;
912 static inline int
913 bidi_explicit_dir_char (int ch)
915 bidi_type_t ch_type;
917 if (!bidi_initialized)
918 abort ();
919 ch_type = (bidi_type_t) XINT (CHAR_TABLE_REF (bidi_type_table, ch));
920 return (ch_type == LRE || ch_type == LRO
921 || ch_type == RLE || ch_type == RLO
922 || ch_type == PDF);
925 /* A helper function for bidi_resolve_explicit. It advances to the
926 next character in logical order and determines the new embedding
927 level and directional override, but does not take into account
928 empty embeddings. */
929 static int
930 bidi_resolve_explicit_1 (struct bidi_it *bidi_it)
932 int curchar;
933 bidi_type_t type;
934 int current_level;
935 int new_level;
936 bidi_dir_t override;
938 /* If reseat()'ed, don't advance, so as to start iteration from the
939 position where we were reseated. bidi_it->bytepos can be less
940 than BEGV_BYTE after reseat to BEGV. */
941 if (bidi_it->bytepos < BEGV_BYTE
942 || bidi_it->first_elt)
944 bidi_it->first_elt = 0;
945 if (bidi_it->charpos < BEGV)
946 bidi_it->charpos = BEGV;
947 bidi_it->bytepos = CHAR_TO_BYTE (bidi_it->charpos);
949 else if (bidi_it->bytepos < ZV_BYTE) /* don't move at ZV */
951 /* Advance to the next character, skipping characters covered by
952 display strings (nchars > 1). */
953 if (bidi_it->nchars <= 0)
954 abort ();
955 bidi_it->charpos += bidi_it->nchars;
956 if (bidi_it->ch_len == 0)
957 abort ();
958 bidi_it->bytepos += bidi_it->ch_len;
961 current_level = bidi_it->level_stack[bidi_it->stack_idx].level; /* X1 */
962 override = bidi_it->level_stack[bidi_it->stack_idx].override;
963 new_level = current_level;
965 if (bidi_it->bytepos >= ZV_BYTE)
967 curchar = BIDI_EOB;
968 bidi_it->ch_len = 1;
969 bidi_it->nchars = 1;
970 bidi_it->disp_pos = ZV;
972 else
974 /* Fetch the character at BYTEPOS. If it is covered by a
975 display string, treat the entire run of covered characters as
976 a single character u+FFFC. */
977 curchar = bidi_fetch_char (bidi_it->bytepos, bidi_it->charpos,
978 &bidi_it->disp_pos, bidi_it->frame_window_p,
979 &bidi_it->ch_len, &bidi_it->nchars);
981 bidi_it->ch = curchar;
983 /* Don't apply directional override here, as all the types we handle
984 below will not be affected by the override anyway, and we need
985 the original type unaltered. The override will be applied in
986 bidi_resolve_weak. */
987 type = bidi_get_type (curchar, NEUTRAL_DIR);
988 bidi_it->orig_type = type;
989 bidi_check_type (bidi_it->orig_type);
991 if (type != PDF)
992 bidi_it->prev_was_pdf = 0;
994 bidi_it->type_after_w1 = UNKNOWN_BT;
996 switch (type)
998 case RLE: /* X2 */
999 case RLO: /* X4 */
1000 bidi_it->type_after_w1 = type;
1001 bidi_check_type (bidi_it->type_after_w1);
1002 type = WEAK_BN; /* X9/Retaining */
1003 if (bidi_it->ignore_bn_limit <= 0)
1005 if (current_level <= BIDI_MAXLEVEL - 4)
1007 /* Compute the least odd embedding level greater than
1008 the current level. */
1009 new_level = ((current_level + 1) & ~1) + 1;
1010 if (bidi_it->type_after_w1 == RLE)
1011 override = NEUTRAL_DIR;
1012 else
1013 override = R2L;
1014 if (current_level == BIDI_MAXLEVEL - 4)
1015 bidi_it->invalid_rl_levels = 0;
1016 bidi_push_embedding_level (bidi_it, new_level, override);
1018 else
1020 bidi_it->invalid_levels++;
1021 /* See the commentary about invalid_rl_levels below. */
1022 if (bidi_it->invalid_rl_levels < 0)
1023 bidi_it->invalid_rl_levels = 0;
1024 bidi_it->invalid_rl_levels++;
1027 else if (bidi_it->prev.type_after_w1 == WEAK_EN /* W5/Retaining */
1028 || bidi_it->next_en_pos > bidi_it->charpos)
1029 type = WEAK_EN;
1030 break;
1031 case LRE: /* X3 */
1032 case LRO: /* X5 */
1033 bidi_it->type_after_w1 = type;
1034 bidi_check_type (bidi_it->type_after_w1);
1035 type = WEAK_BN; /* X9/Retaining */
1036 if (bidi_it->ignore_bn_limit <= 0)
1038 if (current_level <= BIDI_MAXLEVEL - 5)
1040 /* Compute the least even embedding level greater than
1041 the current level. */
1042 new_level = ((current_level + 2) & ~1);
1043 if (bidi_it->type_after_w1 == LRE)
1044 override = NEUTRAL_DIR;
1045 else
1046 override = L2R;
1047 bidi_push_embedding_level (bidi_it, new_level, override);
1049 else
1051 bidi_it->invalid_levels++;
1052 /* invalid_rl_levels counts invalid levels encountered
1053 while the embedding level was already too high for
1054 LRE/LRO, but not for RLE/RLO. That is because
1055 there may be exactly one PDF which we should not
1056 ignore even though invalid_levels is non-zero.
1057 invalid_rl_levels helps to know what PDF is
1058 that. */
1059 if (bidi_it->invalid_rl_levels >= 0)
1060 bidi_it->invalid_rl_levels++;
1063 else if (bidi_it->prev.type_after_w1 == WEAK_EN /* W5/Retaining */
1064 || bidi_it->next_en_pos > bidi_it->charpos)
1065 type = WEAK_EN;
1066 break;
1067 case PDF: /* X7 */
1068 bidi_it->type_after_w1 = type;
1069 bidi_check_type (bidi_it->type_after_w1);
1070 type = WEAK_BN; /* X9/Retaining */
1071 if (bidi_it->ignore_bn_limit <= 0)
1073 if (!bidi_it->invalid_rl_levels)
1075 new_level = bidi_pop_embedding_level (bidi_it);
1076 bidi_it->invalid_rl_levels = -1;
1077 if (bidi_it->invalid_levels)
1078 bidi_it->invalid_levels--;
1079 /* else nothing: UAX#9 says to ignore invalid PDFs */
1081 if (!bidi_it->invalid_levels)
1082 new_level = bidi_pop_embedding_level (bidi_it);
1083 else
1085 bidi_it->invalid_levels--;
1086 bidi_it->invalid_rl_levels--;
1089 else if (bidi_it->prev.type_after_w1 == WEAK_EN /* W5/Retaining */
1090 || bidi_it->next_en_pos > bidi_it->charpos)
1091 type = WEAK_EN;
1092 break;
1093 default:
1094 /* Nothing. */
1095 break;
1098 bidi_it->type = type;
1099 bidi_check_type (bidi_it->type);
1101 return new_level;
1104 /* Given an iterator state in BIDI_IT, advance one character position
1105 in the buffer/string to the next character (in the logical order),
1106 resolve any explicit embeddings and directional overrides, and
1107 return the embedding level of the character after resolving
1108 explicit directives and ignoring empty embeddings. */
1109 static int
1110 bidi_resolve_explicit (struct bidi_it *bidi_it)
1112 int prev_level = bidi_it->level_stack[bidi_it->stack_idx].level;
1113 int new_level = bidi_resolve_explicit_1 (bidi_it);
1115 if (prev_level < new_level
1116 && bidi_it->type == WEAK_BN
1117 && bidi_it->ignore_bn_limit == 0 /* only if not already known */
1118 && bidi_it->bytepos < ZV_BYTE /* not already at EOB */
1119 && bidi_explicit_dir_char (FETCH_MULTIBYTE_CHAR (bidi_it->bytepos
1120 + bidi_it->ch_len)))
1122 /* Avoid pushing and popping embedding levels if the level run
1123 is empty, as this breaks level runs where it shouldn't.
1124 UAX#9 removes all the explicit embedding and override codes,
1125 so empty embeddings disappear without a trace. We need to
1126 behave as if we did the same. */
1127 struct bidi_it saved_it;
1128 int level = prev_level;
1130 bidi_copy_it (&saved_it, bidi_it);
1132 while (bidi_explicit_dir_char (FETCH_MULTIBYTE_CHAR (bidi_it->bytepos
1133 + bidi_it->ch_len)))
1135 /* This advances to the next character, skipping any
1136 characters covered by display strings. */
1137 level = bidi_resolve_explicit_1 (bidi_it);
1140 if (bidi_it->nchars <= 0)
1141 abort ();
1142 if (level == prev_level) /* empty embedding */
1143 saved_it.ignore_bn_limit = bidi_it->charpos + bidi_it->nchars;
1144 else /* this embedding is non-empty */
1145 saved_it.ignore_bn_limit = -1;
1147 bidi_copy_it (bidi_it, &saved_it);
1148 if (bidi_it->ignore_bn_limit > 0)
1150 /* We pushed a level, but we shouldn't have. Undo that. */
1151 if (!bidi_it->invalid_rl_levels)
1153 new_level = bidi_pop_embedding_level (bidi_it);
1154 bidi_it->invalid_rl_levels = -1;
1155 if (bidi_it->invalid_levels)
1156 bidi_it->invalid_levels--;
1158 if (!bidi_it->invalid_levels)
1159 new_level = bidi_pop_embedding_level (bidi_it);
1160 else
1162 bidi_it->invalid_levels--;
1163 bidi_it->invalid_rl_levels--;
1168 if (bidi_it->type == NEUTRAL_B) /* X8 */
1170 bidi_set_paragraph_end (bidi_it);
1171 /* This is needed by bidi_resolve_weak below, and in L1. */
1172 bidi_it->type_after_w1 = bidi_it->type;
1173 bidi_check_type (bidi_it->type_after_w1);
1176 return new_level;
1179 /* Advance in the buffer/string, resolve weak types and return the
1180 type of the next character after weak type resolution. */
1181 static bidi_type_t
1182 bidi_resolve_weak (struct bidi_it *bidi_it)
1184 bidi_type_t type;
1185 bidi_dir_t override;
1186 int prev_level = bidi_it->level_stack[bidi_it->stack_idx].level;
1187 int new_level = bidi_resolve_explicit (bidi_it);
1188 int next_char;
1189 bidi_type_t type_of_next;
1190 struct bidi_it saved_it;
1192 type = bidi_it->type;
1193 override = bidi_it->level_stack[bidi_it->stack_idx].override;
1195 if (type == UNKNOWN_BT
1196 || type == LRE
1197 || type == LRO
1198 || type == RLE
1199 || type == RLO
1200 || type == PDF)
1201 abort ();
1203 if (new_level != prev_level
1204 || bidi_it->type == NEUTRAL_B)
1206 /* We've got a new embedding level run, compute the directional
1207 type of sor and initialize per-run variables (UAX#9, clause
1208 X10). */
1209 bidi_set_sor_type (bidi_it, prev_level, new_level);
1211 else if (type == NEUTRAL_S || type == NEUTRAL_WS
1212 || type == WEAK_BN || type == STRONG_AL)
1213 bidi_it->type_after_w1 = type; /* needed in L1 */
1214 bidi_check_type (bidi_it->type_after_w1);
1216 /* Level and directional override status are already recorded in
1217 bidi_it, and do not need any change; see X6. */
1218 if (override == R2L) /* X6 */
1219 type = STRONG_R;
1220 else if (override == L2R)
1221 type = STRONG_L;
1222 else
1224 if (type == WEAK_NSM) /* W1 */
1226 /* Note that we don't need to consider the case where the
1227 prev character has its type overridden by an RLO or LRO,
1228 because then either the type of this NSM would have been
1229 also overridden, or the previous character is outside the
1230 current level run, and thus not relevant to this NSM.
1231 This is why NSM gets the type_after_w1 of the previous
1232 character. */
1233 if (bidi_it->prev.type_after_w1 != UNKNOWN_BT
1234 /* if type_after_w1 is NEUTRAL_B, this NSM is at sor */
1235 && bidi_it->prev.type_after_w1 != NEUTRAL_B)
1236 type = bidi_it->prev.type_after_w1;
1237 else if (bidi_it->sor == R2L)
1238 type = STRONG_R;
1239 else if (bidi_it->sor == L2R)
1240 type = STRONG_L;
1241 else /* shouldn't happen! */
1242 abort ();
1244 if (type == WEAK_EN /* W2 */
1245 && bidi_it->last_strong.type_after_w1 == STRONG_AL)
1246 type = WEAK_AN;
1247 else if (type == STRONG_AL) /* W3 */
1248 type = STRONG_R;
1249 else if ((type == WEAK_ES /* W4 */
1250 && bidi_it->prev.type_after_w1 == WEAK_EN
1251 && bidi_it->prev.orig_type == WEAK_EN)
1252 || (type == WEAK_CS
1253 && ((bidi_it->prev.type_after_w1 == WEAK_EN
1254 && bidi_it->prev.orig_type == WEAK_EN)
1255 || bidi_it->prev.type_after_w1 == WEAK_AN)))
1257 next_char =
1258 bidi_it->bytepos + bidi_it->ch_len >= ZV_BYTE
1259 ? BIDI_EOB : FETCH_MULTIBYTE_CHAR (bidi_it->bytepos
1260 + bidi_it->ch_len);
1261 type_of_next = bidi_get_type (next_char, override);
1263 if (type_of_next == WEAK_BN
1264 || bidi_explicit_dir_char (next_char))
1266 bidi_copy_it (&saved_it, bidi_it);
1267 while (bidi_resolve_explicit (bidi_it) == new_level
1268 && bidi_it->type == WEAK_BN)
1270 type_of_next = bidi_it->type;
1271 bidi_copy_it (bidi_it, &saved_it);
1274 /* If the next character is EN, but the last strong-type
1275 character is AL, that next EN will be changed to AN when
1276 we process it in W2 above. So in that case, this ES
1277 should not be changed into EN. */
1278 if (type == WEAK_ES
1279 && type_of_next == WEAK_EN
1280 && bidi_it->last_strong.type_after_w1 != STRONG_AL)
1281 type = WEAK_EN;
1282 else if (type == WEAK_CS)
1284 if (bidi_it->prev.type_after_w1 == WEAK_AN
1285 && (type_of_next == WEAK_AN
1286 /* If the next character is EN, but the last
1287 strong-type character is AL, EN will be later
1288 changed to AN when we process it in W2 above.
1289 So in that case, this ES should not be
1290 changed into EN. */
1291 || (type_of_next == WEAK_EN
1292 && bidi_it->last_strong.type_after_w1 == STRONG_AL)))
1293 type = WEAK_AN;
1294 else if (bidi_it->prev.type_after_w1 == WEAK_EN
1295 && type_of_next == WEAK_EN
1296 && bidi_it->last_strong.type_after_w1 != STRONG_AL)
1297 type = WEAK_EN;
1300 else if (type == WEAK_ET /* W5: ET with EN before or after it */
1301 || type == WEAK_BN) /* W5/Retaining */
1303 if (bidi_it->prev.type_after_w1 == WEAK_EN /* ET/BN w/EN before it */
1304 || bidi_it->next_en_pos > bidi_it->charpos)
1305 type = WEAK_EN;
1306 else /* W5: ET/BN with EN after it. */
1308 EMACS_INT en_pos = bidi_it->charpos + bidi_it->nchars;
1310 if (bidi_it->nchars <= 0)
1311 abort ();
1312 next_char =
1313 bidi_it->bytepos + bidi_it->ch_len >= ZV_BYTE
1314 ? BIDI_EOB : FETCH_MULTIBYTE_CHAR (bidi_it->bytepos
1315 + bidi_it->ch_len);
1316 type_of_next = bidi_get_type (next_char, override);
1318 if (type_of_next == WEAK_ET
1319 || type_of_next == WEAK_BN
1320 || bidi_explicit_dir_char (next_char))
1322 bidi_copy_it (&saved_it, bidi_it);
1323 while (bidi_resolve_explicit (bidi_it) == new_level
1324 && (bidi_it->type == WEAK_BN
1325 || bidi_it->type == WEAK_ET))
1327 type_of_next = bidi_it->type;
1328 en_pos = bidi_it->charpos;
1329 bidi_copy_it (bidi_it, &saved_it);
1331 if (type_of_next == WEAK_EN)
1333 /* If the last strong character is AL, the EN we've
1334 found will become AN when we get to it (W2). */
1335 if (bidi_it->last_strong.type_after_w1 != STRONG_AL)
1337 type = WEAK_EN;
1338 /* Remember this EN position, to speed up processing
1339 of the next ETs. */
1340 bidi_it->next_en_pos = en_pos;
1342 else if (type == WEAK_BN)
1343 type = NEUTRAL_ON; /* W6/Retaining */
1349 if (type == WEAK_ES || type == WEAK_ET || type == WEAK_CS /* W6 */
1350 || (type == WEAK_BN
1351 && (bidi_it->prev.type_after_w1 == WEAK_CS /* W6/Retaining */
1352 || bidi_it->prev.type_after_w1 == WEAK_ES
1353 || bidi_it->prev.type_after_w1 == WEAK_ET)))
1354 type = NEUTRAL_ON;
1356 /* Store the type we've got so far, before we clobber it with strong
1357 types in W7 and while resolving neutral types. But leave alone
1358 the original types that were recorded above, because we will need
1359 them for the L1 clause. */
1360 if (bidi_it->type_after_w1 == UNKNOWN_BT)
1361 bidi_it->type_after_w1 = type;
1362 bidi_check_type (bidi_it->type_after_w1);
1364 if (type == WEAK_EN) /* W7 */
1366 if ((bidi_it->last_strong.type_after_w1 == STRONG_L)
1367 || (bidi_it->last_strong.type == UNKNOWN_BT && bidi_it->sor == L2R))
1368 type = STRONG_L;
1371 bidi_it->type = type;
1372 bidi_check_type (bidi_it->type);
1373 return type;
1376 static bidi_type_t
1377 bidi_resolve_neutral (struct bidi_it *bidi_it)
1379 int prev_level = bidi_it->level_stack[bidi_it->stack_idx].level;
1380 bidi_type_t type = bidi_resolve_weak (bidi_it);
1381 int current_level = bidi_it->level_stack[bidi_it->stack_idx].level;
1383 if (!(type == STRONG_R
1384 || type == STRONG_L
1385 || type == WEAK_BN
1386 || type == WEAK_EN
1387 || type == WEAK_AN
1388 || type == NEUTRAL_B
1389 || type == NEUTRAL_S
1390 || type == NEUTRAL_WS
1391 || type == NEUTRAL_ON))
1392 abort ();
1394 if (bidi_get_category (type) == NEUTRAL
1395 || (type == WEAK_BN && prev_level == current_level))
1397 if (bidi_it->next_for_neutral.type != UNKNOWN_BT)
1398 type = bidi_resolve_neutral_1 (bidi_it->prev_for_neutral.type,
1399 bidi_it->next_for_neutral.type,
1400 current_level);
1401 else
1403 /* Arrrgh!! The UAX#9 algorithm is too deeply entrenched in
1404 the assumption of batch-style processing; see clauses W4,
1405 W5, and especially N1, which require to look far forward
1406 (as well as back) in the buffer/string. May the fleas of
1407 a thousand camels infest the armpits of those who design
1408 supposedly general-purpose algorithms by looking at their
1409 own implementations, and fail to consider other possible
1410 implementations! */
1411 struct bidi_it saved_it;
1412 bidi_type_t next_type;
1414 if (bidi_it->scan_dir == -1)
1415 abort ();
1417 bidi_copy_it (&saved_it, bidi_it);
1418 /* Scan the text forward until we find the first non-neutral
1419 character, and then use that to resolve the neutral we
1420 are dealing with now. We also cache the scanned iterator
1421 states, to salvage some of the effort later. */
1422 bidi_cache_iterator_state (bidi_it, 0);
1423 do {
1424 /* Record the info about the previous character, so that
1425 it will be cached below with this state. */
1426 if (bidi_it->type_after_w1 != WEAK_BN /* W1/Retaining */
1427 && bidi_it->type != WEAK_BN)
1428 bidi_remember_char (&bidi_it->prev, bidi_it);
1429 type = bidi_resolve_weak (bidi_it);
1430 /* Paragraph separators have their levels fully resolved
1431 at this point, so cache them as resolved. */
1432 bidi_cache_iterator_state (bidi_it, type == NEUTRAL_B);
1433 /* FIXME: implement L1 here, by testing for a newline and
1434 resetting the level for any sequence of whitespace
1435 characters adjacent to it. */
1436 } while (!(type == NEUTRAL_B
1437 || (type != WEAK_BN
1438 && bidi_get_category (type) != NEUTRAL)
1439 /* This is all per level run, so stop when we
1440 reach the end of this level run. */
1441 || bidi_it->level_stack[bidi_it->stack_idx].level !=
1442 current_level));
1444 bidi_remember_char (&saved_it.next_for_neutral, bidi_it);
1446 switch (type)
1448 case STRONG_L:
1449 case STRONG_R:
1450 case STRONG_AL:
1451 next_type = type;
1452 break;
1453 case WEAK_EN:
1454 case WEAK_AN:
1455 /* N1: ``European and Arabic numbers are treated as
1456 though they were R.'' */
1457 next_type = STRONG_R;
1458 saved_it.next_for_neutral.type = STRONG_R;
1459 break;
1460 case WEAK_BN:
1461 if (!bidi_explicit_dir_char (bidi_it->ch))
1462 abort (); /* can't happen: BNs are skipped */
1463 /* FALLTHROUGH */
1464 case NEUTRAL_B:
1465 /* Marched all the way to the end of this level run.
1466 We need to use the eor type, whose information is
1467 stored by bidi_set_sor_type in the prev_for_neutral
1468 member. */
1469 if (saved_it.type != WEAK_BN
1470 || bidi_get_category (bidi_it->prev.type_after_w1) == NEUTRAL)
1472 next_type = bidi_it->prev_for_neutral.type;
1473 saved_it.next_for_neutral.type = next_type;
1474 bidi_check_type (next_type);
1476 else
1478 /* This is a BN which does not adjoin neutrals.
1479 Leave its type alone. */
1480 bidi_copy_it (bidi_it, &saved_it);
1481 return bidi_it->type;
1483 break;
1484 default:
1485 abort ();
1487 type = bidi_resolve_neutral_1 (saved_it.prev_for_neutral.type,
1488 next_type, current_level);
1489 saved_it.type = type;
1490 bidi_check_type (type);
1491 bidi_copy_it (bidi_it, &saved_it);
1494 return type;
1497 /* Given an iterator state in BIDI_IT, advance one character position
1498 in the buffer/string to the next character (in the logical order),
1499 resolve the bidi type of that next character, and return that
1500 type. */
1501 static bidi_type_t
1502 bidi_type_of_next_char (struct bidi_it *bidi_it)
1504 bidi_type_t type;
1506 /* This should always be called during a forward scan. */
1507 if (bidi_it->scan_dir != 1)
1508 abort ();
1510 /* Reset the limit until which to ignore BNs if we step out of the
1511 area where we found only empty levels. */
1512 if ((bidi_it->ignore_bn_limit > 0
1513 && bidi_it->ignore_bn_limit <= bidi_it->charpos)
1514 || (bidi_it->ignore_bn_limit == -1
1515 && !bidi_explicit_dir_char (bidi_it->ch)))
1516 bidi_it->ignore_bn_limit = 0;
1518 type = bidi_resolve_neutral (bidi_it);
1520 return type;
1523 /* Given an iterator state BIDI_IT, advance one character position in
1524 the buffer/string to the next character (in the current scan
1525 direction), resolve the embedding and implicit levels of that next
1526 character, and return the resulting level. */
1527 static int
1528 bidi_level_of_next_char (struct bidi_it *bidi_it)
1530 bidi_type_t type;
1531 int level, prev_level = -1;
1532 struct bidi_saved_info next_for_neutral;
1533 EMACS_INT next_char_pos;
1535 if (bidi_it->scan_dir == 1)
1537 /* There's no sense in trying to advance if we hit end of text. */
1538 if (bidi_it->bytepos >= ZV_BYTE)
1539 return bidi_it->resolved_level;
1541 /* Record the info about the previous character. */
1542 if (bidi_it->type_after_w1 != WEAK_BN /* W1/Retaining */
1543 && bidi_it->type != WEAK_BN)
1544 bidi_remember_char (&bidi_it->prev, bidi_it);
1545 if (bidi_it->type_after_w1 == STRONG_R
1546 || bidi_it->type_after_w1 == STRONG_L
1547 || bidi_it->type_after_w1 == STRONG_AL)
1548 bidi_remember_char (&bidi_it->last_strong, bidi_it);
1549 /* FIXME: it sounds like we don't need both prev and
1550 prev_for_neutral members, but I'm leaving them both for now. */
1551 if (bidi_it->type == STRONG_R || bidi_it->type == STRONG_L
1552 || bidi_it->type == WEAK_EN || bidi_it->type == WEAK_AN)
1553 bidi_remember_char (&bidi_it->prev_for_neutral, bidi_it);
1555 /* If we overstepped the characters used for resolving neutrals
1556 and whitespace, invalidate their info in the iterator. */
1557 if (bidi_it->charpos >= bidi_it->next_for_neutral.charpos)
1558 bidi_it->next_for_neutral.type = UNKNOWN_BT;
1559 if (bidi_it->next_en_pos >= 0
1560 && bidi_it->charpos >= bidi_it->next_en_pos)
1561 bidi_it->next_en_pos = -1;
1562 if (bidi_it->next_for_ws.type != UNKNOWN_BT
1563 && bidi_it->charpos >= bidi_it->next_for_ws.charpos)
1564 bidi_it->next_for_ws.type = UNKNOWN_BT;
1566 /* This must be taken before we fill the iterator with the info
1567 about the next char. If we scan backwards, the iterator
1568 state must be already cached, so there's no need to know the
1569 embedding level of the previous character, since we will be
1570 returning to our caller shortly. */
1571 prev_level = bidi_it->level_stack[bidi_it->stack_idx].level;
1573 next_for_neutral = bidi_it->next_for_neutral;
1575 /* Perhaps the character we want is already cached. If it is, the
1576 call to bidi_cache_find below will return a type other than
1577 UNKNOWN_BT. */
1578 if (bidi_cache_idx && !bidi_it->first_elt)
1580 if (bidi_it->scan_dir > 0)
1582 if (bidi_it->nchars <= 0)
1583 abort ();
1584 next_char_pos = bidi_it->charpos + bidi_it->nchars;
1586 else
1587 next_char_pos = bidi_it->charpos - 1;
1588 type = bidi_cache_find (next_char_pos, -1, bidi_it);
1590 else
1591 type = UNKNOWN_BT;
1592 if (type != UNKNOWN_BT)
1594 /* Don't lose the information for resolving neutrals! The
1595 cached states could have been cached before their
1596 next_for_neutral member was computed. If we are on our way
1597 forward, we can simply take the info from the previous
1598 state. */
1599 if (bidi_it->scan_dir == 1
1600 && bidi_it->next_for_neutral.type == UNKNOWN_BT)
1601 bidi_it->next_for_neutral = next_for_neutral;
1603 /* If resolved_level is -1, it means this state was cached
1604 before it was completely resolved, so we cannot return
1605 it. */
1606 if (bidi_it->resolved_level != -1)
1607 return bidi_it->resolved_level;
1609 if (bidi_it->scan_dir == -1)
1610 /* If we are going backwards, the iterator state is already cached
1611 from previous scans, and should be fully resolved. */
1612 abort ();
1614 if (type == UNKNOWN_BT)
1615 type = bidi_type_of_next_char (bidi_it);
1617 if (type == NEUTRAL_B)
1618 return bidi_it->resolved_level;
1620 level = bidi_it->level_stack[bidi_it->stack_idx].level;
1621 if ((bidi_get_category (type) == NEUTRAL /* && type != NEUTRAL_B */)
1622 || (type == WEAK_BN && prev_level == level))
1624 if (bidi_it->next_for_neutral.type == UNKNOWN_BT)
1625 abort ();
1627 /* If the cached state shows a neutral character, it was not
1628 resolved by bidi_resolve_neutral, so do it now. */
1629 type = bidi_resolve_neutral_1 (bidi_it->prev_for_neutral.type,
1630 bidi_it->next_for_neutral.type,
1631 level);
1634 if (!(type == STRONG_R
1635 || type == STRONG_L
1636 || type == WEAK_BN
1637 || type == WEAK_EN
1638 || type == WEAK_AN))
1639 abort ();
1640 bidi_it->type = type;
1641 bidi_check_type (bidi_it->type);
1643 /* For L1 below, we need to know, for each WS character, whether
1644 it belongs to a sequence of WS characters preceding a newline
1645 or a TAB or a paragraph separator. */
1646 if (bidi_it->orig_type == NEUTRAL_WS
1647 && bidi_it->next_for_ws.type == UNKNOWN_BT)
1649 int ch;
1650 EMACS_INT clen = bidi_it->ch_len;
1651 EMACS_INT bpos = bidi_it->bytepos;
1652 EMACS_INT cpos = bidi_it->charpos;
1653 EMACS_INT disp_pos = bidi_it->disp_pos;
1654 EMACS_INT nc = bidi_it->nchars;
1655 bidi_type_t chtype;
1656 int fwp = bidi_it->frame_window_p;
1658 if (bidi_it->nchars <= 0)
1659 abort ();
1660 do {
1661 ch = bidi_fetch_char (bpos += clen, cpos += nc, &disp_pos, fwp,
1662 &clen, &nc);
1663 if (ch == '\n' || ch == BIDI_EOB /* || ch == LINESEP_CHAR */)
1664 chtype = NEUTRAL_B;
1665 else
1666 chtype = bidi_get_type (ch, NEUTRAL_DIR);
1667 } while (chtype == NEUTRAL_WS || chtype == WEAK_BN
1668 || bidi_explicit_dir_char (ch)); /* L1/Retaining */
1669 bidi_it->next_for_ws.type = chtype;
1670 bidi_check_type (bidi_it->next_for_ws.type);
1671 bidi_it->next_for_ws.charpos = cpos;
1672 bidi_it->next_for_ws.bytepos = bpos;
1675 /* Resolve implicit levels, with a twist: PDFs get the embedding
1676 level of the enbedding they terminate. See below for the
1677 reason. */
1678 if (bidi_it->orig_type == PDF
1679 /* Don't do this if this formatting code didn't change the
1680 embedding level due to invalid or empty embeddings. */
1681 && prev_level != level)
1683 /* Don't look in UAX#9 for the reason for this: it's our own
1684 private quirk. The reason is that we want the formatting
1685 codes to be delivered so that they bracket the text of their
1686 embedding. For example, given the text
1688 {RLO}teST{PDF}
1690 we want it to be displayed as
1692 {PDF}STet{RLO}
1694 not as
1696 STet{RLO}{PDF}
1698 which will result because we bump up the embedding level as
1699 soon as we see the RLO and pop it as soon as we see the PDF,
1700 so RLO itself has the same embedding level as "teST", and
1701 thus would be normally delivered last, just before the PDF.
1702 The switch below fiddles with the level of PDF so that this
1703 ugly side effect does not happen.
1705 (This is, of course, only important if the formatting codes
1706 are actually displayed, but Emacs does need to display them
1707 if the user wants to.) */
1708 level = prev_level;
1710 else if (bidi_it->orig_type == NEUTRAL_B /* L1 */
1711 || bidi_it->orig_type == NEUTRAL_S
1712 || bidi_it->ch == '\n' || bidi_it->ch == BIDI_EOB
1713 /* || bidi_it->ch == LINESEP_CHAR */
1714 || (bidi_it->orig_type == NEUTRAL_WS
1715 && (bidi_it->next_for_ws.type == NEUTRAL_B
1716 || bidi_it->next_for_ws.type == NEUTRAL_S)))
1717 level = bidi_it->level_stack[0].level;
1718 else if ((level & 1) == 0) /* I1 */
1720 if (type == STRONG_R)
1721 level++;
1722 else if (type == WEAK_EN || type == WEAK_AN)
1723 level += 2;
1725 else /* I2 */
1727 if (type == STRONG_L || type == WEAK_EN || type == WEAK_AN)
1728 level++;
1731 bidi_it->resolved_level = level;
1732 return level;
1735 /* Move to the other edge of a level given by LEVEL. If END_FLAG is
1736 non-zero, we are at the end of a level, and we need to prepare to
1737 resume the scan of the lower level.
1739 If this level's other edge is cached, we simply jump to it, filling
1740 the iterator structure with the iterator state on the other edge.
1741 Otherwise, we walk the buffer or string until we come back to the
1742 same level as LEVEL.
1744 Note: we are not talking here about a ``level run'' in the UAX#9
1745 sense of the term, but rather about a ``level'' which includes
1746 all the levels higher than it. In other words, given the levels
1747 like this:
1749 11111112222222333333334443343222222111111112223322111
1750 A B C
1752 and assuming we are at point A scanning left to right, this
1753 function moves to point C, whereas the UAX#9 ``level 2 run'' ends
1754 at point B. */
1755 static void
1756 bidi_find_other_level_edge (struct bidi_it *bidi_it, int level, int end_flag)
1758 int dir = end_flag ? -bidi_it->scan_dir : bidi_it->scan_dir;
1759 int idx;
1761 /* Try the cache first. */
1762 if ((idx = bidi_cache_find_level_change (level, dir, end_flag)) >= 0)
1763 bidi_cache_fetch_state (idx, bidi_it);
1764 else
1766 int new_level;
1768 if (end_flag)
1769 abort (); /* if we are at end of level, its edges must be cached */
1771 bidi_cache_iterator_state (bidi_it, 1);
1772 do {
1773 new_level = bidi_level_of_next_char (bidi_it);
1774 bidi_cache_iterator_state (bidi_it, 1);
1775 } while (new_level >= level);
1779 void
1780 bidi_move_to_visually_next (struct bidi_it *bidi_it)
1782 int old_level, new_level, next_level;
1783 struct bidi_it sentinel;
1785 if (bidi_it->scan_dir == 0)
1787 bidi_it->scan_dir = 1; /* default to logical order */
1790 /* If we just passed a newline, initialize for the next line. */
1791 if (!bidi_it->first_elt && bidi_it->orig_type == NEUTRAL_B)
1792 bidi_line_init (bidi_it);
1794 /* Prepare the sentinel iterator state, and cache it. When we bump
1795 into it, scanning backwards, we'll know that the last non-base
1796 level is exhausted. */
1797 if (bidi_cache_idx == 0)
1799 bidi_copy_it (&sentinel, bidi_it);
1800 if (bidi_it->first_elt)
1802 sentinel.charpos--; /* cached charpos needs to be monotonic */
1803 sentinel.bytepos--;
1804 sentinel.ch = '\n'; /* doesn't matter, but why not? */
1805 sentinel.ch_len = 1;
1806 sentinel.nchars = 1;
1808 bidi_cache_iterator_state (&sentinel, 1);
1811 old_level = bidi_it->resolved_level;
1812 new_level = bidi_level_of_next_char (bidi_it);
1814 /* Reordering of resolved levels (clause L2) is implemented by
1815 jumping to the other edge of the level and flipping direction of
1816 scanning the text whenever we find a level change. */
1817 if (new_level != old_level)
1819 int ascending = new_level > old_level;
1820 int level_to_search = ascending ? old_level + 1 : old_level;
1821 int incr = ascending ? 1 : -1;
1822 int expected_next_level = old_level + incr;
1824 /* Jump (or walk) to the other edge of this level. */
1825 bidi_find_other_level_edge (bidi_it, level_to_search, !ascending);
1826 /* Switch scan direction and peek at the next character in the
1827 new direction. */
1828 bidi_it->scan_dir = -bidi_it->scan_dir;
1830 /* The following loop handles the case where the resolved level
1831 jumps by more than one. This is typical for numbers inside a
1832 run of text with left-to-right embedding direction, but can
1833 also happen in other situations. In those cases the decision
1834 where to continue after a level change, and in what direction,
1835 is tricky. For example, given a text like below:
1837 abcdefgh
1838 11336622
1840 (where the numbers below the text show the resolved levels),
1841 the result of reordering according to UAX#9 should be this:
1843 efdcghba
1845 This is implemented by the loop below which flips direction
1846 and jumps to the other edge of the level each time it finds
1847 the new level not to be the expected one. The expected level
1848 is always one more or one less than the previous one. */
1849 next_level = bidi_peek_at_next_level (bidi_it);
1850 while (next_level != expected_next_level)
1852 expected_next_level += incr;
1853 level_to_search += incr;
1854 bidi_find_other_level_edge (bidi_it, level_to_search, !ascending);
1855 bidi_it->scan_dir = -bidi_it->scan_dir;
1856 next_level = bidi_peek_at_next_level (bidi_it);
1859 /* Finally, deliver the next character in the new direction. */
1860 next_level = bidi_level_of_next_char (bidi_it);
1863 /* Take note when we have just processed the newline that precedes
1864 the end of the paragraph. The next time we are about to be
1865 called, set_iterator_to_next will automatically reinit the
1866 paragraph direction, if needed. We do this at the newline before
1867 the paragraph separator, because the next character might not be
1868 the first character of the next paragraph, due to the bidi
1869 reordering, whereas we _must_ know the paragraph base direction
1870 _before_ we process the paragraph's text, since the base
1871 direction affects the reordering. */
1872 if (bidi_it->scan_dir == 1
1873 && bidi_it->orig_type == NEUTRAL_B
1874 && bidi_it->bytepos < ZV_BYTE)
1876 EMACS_INT sep_len =
1877 bidi_at_paragraph_end (bidi_it->charpos + bidi_it->nchars,
1878 bidi_it->bytepos + bidi_it->ch_len);
1879 if (bidi_it->nchars <= 0)
1880 abort ();
1881 if (sep_len >= 0)
1883 bidi_it->new_paragraph = 1;
1884 /* Record the buffer position of the last character of the
1885 paragraph separator. */
1886 bidi_it->separator_limit =
1887 bidi_it->charpos + bidi_it->nchars + sep_len;
1891 if (bidi_it->scan_dir == 1 && bidi_cache_idx)
1893 /* If we are at paragraph's base embedding level and beyond the
1894 last cached position, the cache's job is done and we can
1895 discard it. */
1896 if (bidi_it->resolved_level == bidi_it->level_stack[0].level
1897 && bidi_it->charpos > (bidi_cache[bidi_cache_idx - 1].charpos
1898 + bidi_cache[bidi_cache_idx - 1].nchars - 1))
1899 bidi_cache_reset ();
1900 /* But as long as we are caching during forward scan, we must
1901 cache each state, or else the cache integrity will be
1902 compromised: it assumes cached states correspond to buffer
1903 positions 1:1. */
1904 else
1905 bidi_cache_iterator_state (bidi_it, 1);
1909 /* This is meant to be called from within the debugger, whenever you
1910 wish to examine the cache contents. */
1911 void bidi_dump_cached_states (void) EXTERNALLY_VISIBLE;
1912 void
1913 bidi_dump_cached_states (void)
1915 int i;
1916 int ndigits = 1;
1918 if (bidi_cache_idx == 0)
1920 fprintf (stderr, "The cache is empty.\n");
1921 return;
1923 fprintf (stderr, "Total of %d state%s in cache:\n",
1924 bidi_cache_idx, bidi_cache_idx == 1 ? "" : "s");
1926 for (i = bidi_cache[bidi_cache_idx - 1].charpos; i > 0; i /= 10)
1927 ndigits++;
1928 fputs ("ch ", stderr);
1929 for (i = 0; i < bidi_cache_idx; i++)
1930 fprintf (stderr, "%*c", ndigits, bidi_cache[i].ch);
1931 fputs ("\n", stderr);
1932 fputs ("lvl ", stderr);
1933 for (i = 0; i < bidi_cache_idx; i++)
1934 fprintf (stderr, "%*d", ndigits, bidi_cache[i].resolved_level);
1935 fputs ("\n", stderr);
1936 fputs ("pos ", stderr);
1937 for (i = 0; i < bidi_cache_idx; i++)
1938 fprintf (stderr, "%*"pI"d", ndigits, bidi_cache[i].charpos);
1939 fputs ("\n", stderr);