Fix assertion violations due to a bug in bidi_set_sos_type; add assertions.
[emacs.git] / src / bidi.c
blob3c204a82b7867036281fa605e97a99d91d5fc9ab
1 /* Low-level bidirectional buffer/string-scanning functions for GNU Emacs.
2 Copyright (C) 2000-2001, 2004-2005, 2009-2014 Free Software
3 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 (UBA) as per UAX#9, a part of the Unicode Standard.
25 Unlike the Reference Implementation and most other implementations,
26 this one is designed to be called once for every character in the
27 buffer or string. That way, we can leave intact the design of the
28 Emacs display engine, whereby an iterator object is used to
29 traverse buffer or string text character by character, and generate
30 the necessary data for displaying each character in 'struct glyph'
31 objects. (See xdisp.c for the details of that iteration.) The
32 functions on this file replace the original linear iteration in the
33 logical order of the text with a non-linear iteration in the visual
34 order, i.e. in the order characters should be shown on display.
36 The main entry point is bidi_move_to_visually_next. Each time it
37 is called, it finds the next character in the visual order, and
38 returns its information in a special structure. The caller is then
39 expected to process this character for display or any other
40 purposes, and call bidi_move_to_visually_next for the next
41 character. See the comments in bidi_move_to_visually_next for more
42 details about its algorithm that finds the next visual-order
43 character by resolving their levels on the fly.
45 Two other entry points are bidi_paragraph_init and
46 bidi_mirror_char. The first determines the base direction of a
47 paragraph, while the second returns the mirrored version of its
48 argument character.
50 A few auxiliary entry points are used to initialize the bidi
51 iterator for iterating an object (buffer or string), push and pop
52 the bidi iterator state, and save and restore the state of the bidi
53 cache.
55 If you want to understand the code, you will have to read it
56 together with the relevant portions of UAX#9. The comments include
57 references to UAX#9 rules, for that very reason.
59 A note about references to UAX#9 rules: if the reference says
60 something like "X9/Retaining", it means that you need to refer to
61 rule X9 and to its modifications described in the "Implementation
62 Notes" section of UAX#9, under "Retaining Format Codes".
64 Here's the overview of the design of the reordering engine
65 implemented by this file.
67 Basic implementation structure
68 ------------------------------
70 The sequential processing steps described by UAX#9 are implemented
71 as recursive levels of processing, all of which examine the next
72 character in the logical order. This hierarchy of processing looks
73 as follows, from the innermost (deepest) to the outermost level,
74 omitting some subroutines used by each level:
76 bidi_fetch_char -- fetch next character
77 bidi_resolve_explicit -- resolve explicit levels and directions
78 bidi_resolve_weak -- resolve weak types
79 bidi_resolve_neutral -- resolve neutral types
80 bidi_level_of_next_char -- resolve implicit levels
82 Each level calls the level below it, and works on the result
83 returned by the lower level, including all of its sub-levels.
85 Unlike all the levels below it, bidi_level_of_next_char can return
86 the information about either the next or previous character in the
87 logical order, depending on the current direction of scanning the
88 buffer or string. For the next character, it calls all the levels
89 below it; for the previous character, it uses the cache, described
90 below.
92 Thus, the result of calling bidi_level_of_next_char is the resolved
93 level of the next or the previous character in the logical order.
94 Based on this information, the function bidi_move_to_visually_next
95 finds the next character in the visual order and updates the
96 direction in which the buffer is scanned, either forward or
97 backward, to find the next character to be displayed. (Text is
98 scanned backwards when it needs to be reversed for display, i.e. if
99 the visual order is the inverse of the logical order.) This
100 implements the last, reordering steps of the UBA, by successively
101 calling bidi_level_of_next_char until the character of the required
102 embedding level is found; the scan direction is dynamically updated
103 as a side effect. See the commentary before the 'while' loop in
104 bidi_move_to_visually_next, for the details.
106 Fetching characters
107 -------------------
109 In a nutshell, fetching the next character boils down to calling
110 STRING_CHAR_AND_LENGTH, passing it the address of a buffer or
111 string position. See bidi_fetch_char. However, if the next
112 character is "covered" by a display property of some kind,
113 bidi_fetch_char returns the u+FFFC "object replacement character"
114 that represents the entire run of text covered by the display
115 property. (The ch_len and nchars members of 'struct bidi_it'
116 reflect the length in bytes and characters of that text.) This is
117 so we reorder text on both sides of the display property as
118 appropriate for an image or embedded string. Similarly, text
119 covered by a display spec of the form '(space ...)', is replaced
120 with the u+2029 paragraph separator character, so such display
121 specs produce the same effect as a TAB under UBA. Both these
122 special characters are not actually displayed -- the display
123 property is displayed instead -- but just used to compute the
124 embedding level of the surrounding text so as to produce the
125 required effect.
127 Bidi iterator states
128 --------------------
130 The UBA is highly context dependent in some of its parts,
131 i.e. results of processing a character can generally depend on
132 characters very far away. The UAX#9 description of the UBA
133 prescribes a stateful processing of each character, whereby the
134 results of this processing depend on various state variables, such
135 as the current embedding level, level stack, and directional
136 override status. In addition, the UAX#9 description includes many
137 passages like this (from rule W2 in this case):
139 Search backward from each instance of a European number until the
140 first strong type (R, L, AL, or sos) is found. If an AL is found,
141 change the type of the European number to Arabic number.
143 To support this, we use a bidi iterator object, 'struct bidi_it',
144 which is a sub-structure of 'struct it' used by xdisp.c (see
145 dispextern.h for the definition of both of these structures). The
146 bidi iterator holds the entire state of the iteration required by
147 the UBA, and is updated as the text is traversed. In particular,
148 the embedding level of the current character being resolved is
149 recorded in the iterator state. To avoid costly searches backward
150 in support of rules like W2 above, the necessary character types
151 are also recorded in the iterator state as they are found during
152 the forward scan, and then used when such rules need to be applied.
153 (Forward scans cannot be avoided in this way; they need to be
154 performed at least once, and the results recorded in the iterator
155 state, to be reused until the forward scan oversteps the recorded
156 position.)
158 In this manner, the iterator state acts as a mini-cache of
159 contextual information required for resolving the level of the
160 current character by various UBA rules.
162 Caching of bidi iterator states
163 -------------------------------
165 As described above, the reordering engine uses the information
166 recorded in the bidi iterator state in order to resolve the
167 embedding level of the current character. When the reordering
168 engine needs to process the next character in the logical order, it
169 fetches it and applies to it all the UBA levels, updating the
170 iterator state as it goes. But when the buffer or string is
171 scanned backwards, i.e. in the reverse order of buffer/string
172 positions, the scanned characters were already processed during the
173 preceding forward scan (see bidi_find_other_level_edge). To avoid
174 costly re-processing of characters that were already processed
175 during the forward scan, the iterator states computed while
176 scanning forward are cached.
178 The cache is just a linear array of 'struct bidi_it' objects, which
179 is dynamically allocated and reallocated as needed, since the size
180 of the cache depends on the text being processed. We only need the
181 cache while processing embedded levels higher than the base
182 paragraph embedding level, because these higher levels require
183 changes in scan direction. Therefore, as soon as we are back to
184 the base embedding level, we can free the cache; see the calls to
185 bidi_cache_reset and bidi_cache_shrink, for the conditions to do
186 this.
188 The cache maintains the index of the next unused cache slot -- this
189 is where the next iterator state will be cached. The function
190 bidi_cache_iterator_state saves an instance of the state in the
191 cache and increments the unused slot index. The companion function
192 bidi_cache_find looks up a cached state that corresponds to a given
193 buffer/string position. All of the cached states must correspond
194 1:1 to the buffer or string region whose processing they reflect;
195 bidi.c will abort if it finds cache slots that violate this 1:1
196 correspondence.
198 When the parent iterator 'struct it' is pushed (see push_it in
199 xdisp.c) to pause the current iteration and start iterating over a
200 different object (e.g., a 'display' string that covers some buffer
201 text), the bidi iterator cache needs to be "pushed" as well, so
202 that a new empty cache could be used while iterating over the new
203 object. Later, when the new object is exhausted, and xdisp.c calls
204 pop_it, we need to "pop" the bidi cache as well and return to the
205 original cache. See bidi_push_it and bidi_pop_it for how this is
206 done.
208 Some functions of the display engine save copies of 'struct it' in
209 local variables, and restore them later. For examples, see
210 pos_visible_p and move_it_in_display_line_to in xdisp.c, and
211 window_scroll_pixel_based in window.c. When this happens, we need
212 to save and restore the bidi cache as well, because conceptually
213 the cache is part of the 'struct it' state, and needs to be in
214 perfect sync with the portion of the buffer/string that is being
215 processed. This saving and restoring of the cache state is handled
216 by bidi_shelve_cache and bidi_unshelve_cache, and the helper macros
217 SAVE_IT and RESTORE_IT defined on xdisp.c.
219 Note that, because reordering is implemented below the level in
220 xdisp.c that breaks glyphs into screen lines, we are violating
221 paragraph 3.4 of UAX#9. which mandates that line breaking shall be
222 done before reordering each screen line separately. However,
223 following UAX#9 to the letter in this matter goes against the basic
224 design of the Emacs display engine, and so we choose here this
225 minor deviation from the UBA letter in preference to redesign of
226 the display engine. The effect of this is only seen in continued
227 lines that are broken into screen lines in the middle of a run
228 whose direction is opposite to the paragraph's base direction.
230 Important design and implementation note: when the code needs to
231 scan far ahead, be sure to avoid such scans as much as possible
232 when the buffer/string doesn't contain any RTL characters. Users
233 of left-to-right scripts will never forgive you if you introduce
234 some slow-down due to bidi in situations that don't involve any
235 bidirectional text. See the large comment near the beginning of
236 bidi_resolve_neutral, for one situation where such shortcut was
237 necessary. */
239 #include <config.h>
240 #include <stdio.h>
242 #include "lisp.h"
243 #include "character.h"
244 #include "buffer.h"
245 #include "dispextern.h"
246 #include "region-cache.h"
248 static bool bidi_initialized = 0;
250 static Lisp_Object bidi_type_table, bidi_mirror_table;
252 #define BIDI_EOB (-1)
254 /* Data type for describing the bidirectional character categories. */
255 typedef enum {
256 UNKNOWN_BC,
257 NEUTRAL,
258 WEAK,
259 STRONG,
260 EXPLICIT_FORMATTING
261 } bidi_category_t;
263 static Lisp_Object paragraph_start_re, paragraph_separate_re;
264 static Lisp_Object Qparagraph_start, Qparagraph_separate;
267 /***********************************************************************
268 Utilities
269 ***********************************************************************/
271 /* Return the bidi type of a character CH, subject to the current
272 directional OVERRIDE. */
273 static bidi_type_t
274 bidi_get_type (int ch, bidi_dir_t override)
276 bidi_type_t default_type;
278 if (ch == BIDI_EOB)
279 return NEUTRAL_B;
280 if (ch < 0 || ch > MAX_CHAR)
281 emacs_abort ();
283 default_type = (bidi_type_t) XINT (CHAR_TABLE_REF (bidi_type_table, ch));
284 /* Every valid character code, even those that are unassigned by the
285 UCD, have some bidi-class property, according to
286 DerivedBidiClass.txt file. Therefore, if we ever get UNKNOWN_BT
287 (= zero) code from CHAR_TABLE_REF, that's a bug. */
288 if (default_type == UNKNOWN_BT)
289 emacs_abort ();
291 switch (default_type)
293 case WEAK_BN:
294 case NEUTRAL_B:
295 case LRE:
296 case LRO:
297 case RLE:
298 case RLO:
299 case PDF:
300 case LRI:
301 case RLI:
302 case FSI:
303 case PDI:
304 return default_type;
305 default:
306 if (override == L2R)
307 return STRONG_L;
308 else if (override == R2L)
309 return STRONG_R;
310 else
311 return default_type;
315 static void
316 bidi_check_type (bidi_type_t type)
318 eassert (UNKNOWN_BT <= type && type <= NEUTRAL_ON);
321 /* Given a bidi TYPE of a character, return its category. */
322 static bidi_category_t
323 bidi_get_category (bidi_type_t type)
325 switch (type)
327 case UNKNOWN_BT:
328 return UNKNOWN_BC;
329 case STRONG_L:
330 case STRONG_R:
331 case STRONG_AL:
332 return STRONG;
333 case WEAK_EN:
334 case WEAK_ES:
335 case WEAK_ET:
336 case WEAK_AN:
337 case WEAK_CS:
338 case WEAK_NSM:
339 case WEAK_BN:
340 return WEAK;
341 case NEUTRAL_B:
342 case NEUTRAL_S:
343 case NEUTRAL_WS:
344 case NEUTRAL_ON:
345 return NEUTRAL;
346 case LRE:
347 case LRO:
348 case RLE:
349 case RLO:
350 case PDF:
351 case LRI:
352 case RLI:
353 case FSI:
354 case PDI:
355 return EXPLICIT_FORMATTING;
356 default:
357 emacs_abort ();
361 /* Return the mirrored character of C, if it has one. If C has no
362 mirrored counterpart, return C.
363 Note: The conditions in UAX#9 clause L4 regarding the surrounding
364 context must be tested by the caller. */
366 bidi_mirror_char (int c)
368 Lisp_Object val;
370 if (c == BIDI_EOB)
371 return c;
372 if (c < 0 || c > MAX_CHAR)
373 emacs_abort ();
375 val = CHAR_TABLE_REF (bidi_mirror_table, c);
376 if (INTEGERP (val))
378 int v;
380 /* When debugging, check before assigning to V, so that the check
381 isn't broken by undefined behavior due to int overflow. */
382 eassert (CHAR_VALID_P (XINT (val)));
384 v = XINT (val);
386 /* Minimal test we must do in optimized builds, to prevent weird
387 crashes further down the road. */
388 if (v < 0 || v > MAX_CHAR)
389 emacs_abort ();
391 return v;
394 return c;
397 /* Determine the start-of-sequence (sos) directional type given the two
398 embedding levels on either side of the run boundary. Also, update
399 the saved info about previously seen characters, since that info is
400 generally valid for a single level run. */
401 static void
402 bidi_set_sos_type (struct bidi_it *bidi_it, int level_before, int level_after)
404 int higher_level = (level_before > level_after ? level_before : level_after);
406 /* FIXME: should the default sos direction be user selectable? */
407 bidi_it->sos = ((higher_level & 1) != 0 ? R2L : L2R); /* X10 */
409 bidi_it->prev.type = UNKNOWN_BT;
410 bidi_it->last_strong.type = bidi_it->last_strong.type_after_w1
411 = bidi_it->last_strong.orig_type = UNKNOWN_BT;
412 bidi_it->prev_for_neutral.type = (bidi_it->sos == R2L ? STRONG_R : STRONG_L);
413 bidi_it->prev_for_neutral.charpos = bidi_it->charpos;
414 bidi_it->prev_for_neutral.bytepos = bidi_it->bytepos;
415 bidi_it->next_for_neutral.type = bidi_it->next_for_neutral.type_after_w1
416 = bidi_it->next_for_neutral.orig_type = UNKNOWN_BT;
417 bidi_it->ignore_bn_limit = -1; /* meaning it's unknown */
420 /* Push the current embedding level and override status; reset the
421 current level to LEVEL and the current override status to OVERRIDE. */
422 static void
423 bidi_push_embedding_level (struct bidi_it *bidi_it,
424 int level, bidi_dir_t override, bool isolate_status)
426 struct bidi_stack *st;
428 bidi_it->stack_idx++;
429 eassert (bidi_it->stack_idx < BIDI_MAXDEPTH+2+1);
430 st = &bidi_it->level_stack[bidi_it->stack_idx];
431 eassert (level <= (1 << 7));
432 st->level = level;
433 st->override = override;
434 st->isolate_status = isolate_status;
435 if (isolate_status)
437 st->last_strong = bidi_it->last_strong;
438 st->prev_for_neutral = bidi_it->prev_for_neutral;
439 st->next_for_neutral = bidi_it->next_for_neutral;
440 st->next_for_ws = bidi_it->next_for_ws;
441 st->sos = bidi_it->sos;
445 /* Pop from the stack the embedding level, the directional override
446 status, and optionally saved information for the isolating run
447 sequence. Return the new level. */
448 static int
449 bidi_pop_embedding_level (struct bidi_it *bidi_it)
451 int level;
453 /* UAX#9 says to ignore invalid PDFs (X7, last bullet)
454 and PDIs (X6a, 2nd bullet). */
455 if (bidi_it->stack_idx > 0)
457 bool isolate_status
458 = bidi_it->level_stack[bidi_it->stack_idx].isolate_status;
459 struct bidi_stack st;
461 st = bidi_it->level_stack[bidi_it->stack_idx];
462 if (isolate_status)
464 /* PREV is used in W1 for resolving WEAK_NSM. By the time
465 we get to an NSM, we must have gotten past at least one
466 character: the PDI that ends the isolate from which we
467 are popping here. So PREV will have been filled up by
468 the time we first use it. We initialize it here to
469 UNKNOWN_BT to be able to catch any blunders in this
470 logic. */
471 bidi_it->prev.orig_type = bidi_it->prev.type_after_w1
472 = bidi_it->prev.type = UNKNOWN_BT;
473 bidi_it->last_strong = st.last_strong;
474 bidi_it->prev_for_neutral = st.prev_for_neutral;
475 bidi_it->next_for_neutral = st.next_for_neutral;
476 bidi_it->next_for_ws = st.next_for_ws;
477 bidi_it->sos = st.sos;
479 bidi_it->stack_idx--;
481 level = bidi_it->level_stack[bidi_it->stack_idx].level;
482 eassert (0 <= level && level <= BIDI_MAXDEPTH + 1);
483 return level;
486 /* Record in SAVED_INFO the information about the current character. */
487 static void
488 bidi_remember_char (struct bidi_saved_info *saved_info,
489 struct bidi_it *bidi_it)
491 saved_info->charpos = bidi_it->charpos;
492 saved_info->bytepos = bidi_it->bytepos;
493 saved_info->type = bidi_it->type;
494 bidi_check_type (bidi_it->type);
495 saved_info->type_after_w1 = bidi_it->type_after_w1;
496 bidi_check_type (bidi_it->type_after_w1);
497 saved_info->orig_type = bidi_it->orig_type;
498 bidi_check_type (bidi_it->orig_type);
501 /* Copy the bidi iterator from FROM to TO. To save cycles, this only
502 copies the part of the level stack that is actually in use. */
503 static void
504 bidi_copy_it (struct bidi_it *to, struct bidi_it *from)
506 /* Copy everything from the start through the active part of
507 the level stack. */
508 memcpy (to, from,
509 (offsetof (struct bidi_it, level_stack[1])
510 + from->stack_idx * sizeof from->level_stack[0]));
514 /***********************************************************************
515 Caching the bidi iterator states
516 ***********************************************************************/
518 /* We allocate and de-allocate the cache in chunks of this size (in
519 characters). 200 was chosen as an upper limit for reasonably-long
520 lines in a text file/buffer. */
521 #define BIDI_CACHE_CHUNK 200
522 static struct bidi_it *bidi_cache;
523 static ptrdiff_t bidi_cache_size = 0;
524 enum { elsz = sizeof (struct bidi_it) };
525 static ptrdiff_t bidi_cache_idx; /* next unused cache slot */
526 static ptrdiff_t bidi_cache_last_idx; /* slot of last cache hit */
527 static ptrdiff_t bidi_cache_start = 0; /* start of cache for this
528 "stack" level */
530 /* 5-slot stack for saving the start of the previous level of the
531 cache. xdisp.c maintains a 5-slot stack for its iterator state,
532 and we need the same size of our stack. */
533 static ptrdiff_t bidi_cache_start_stack[IT_STACK_SIZE];
534 static int bidi_cache_sp;
536 /* Size of header used by bidi_shelve_cache. */
537 enum
539 bidi_shelve_header_size
540 = (sizeof (bidi_cache_idx) + sizeof (bidi_cache_start_stack)
541 + sizeof (bidi_cache_sp) + sizeof (bidi_cache_start)
542 + sizeof (bidi_cache_last_idx))
545 /* Reset the cache state to the empty state. We only reset the part
546 of the cache relevant to iteration of the current object. Previous
547 objects, which are pushed on the display iterator's stack, are left
548 intact. This is called when the cached information is no more
549 useful for the current iteration, e.g. when we were reseated to a
550 new position on the same object. */
551 static void
552 bidi_cache_reset (void)
554 bidi_cache_idx = bidi_cache_start;
555 bidi_cache_last_idx = -1;
558 /* Shrink the cache to its minimal size. Called when we init the bidi
559 iterator for reordering a buffer or a string that does not come
560 from display properties, because that means all the previously
561 cached info is of no further use. */
562 static void
563 bidi_cache_shrink (void)
565 if (bidi_cache_size > BIDI_CACHE_CHUNK)
567 bidi_cache = xrealloc (bidi_cache, BIDI_CACHE_CHUNK * elsz);
568 bidi_cache_size = BIDI_CACHE_CHUNK;
570 bidi_cache_reset ();
573 static void
574 bidi_cache_fetch_state (ptrdiff_t idx, struct bidi_it *bidi_it)
576 int current_scan_dir = bidi_it->scan_dir;
578 if (idx < bidi_cache_start || idx >= bidi_cache_idx)
579 emacs_abort ();
581 bidi_copy_it (bidi_it, &bidi_cache[idx]);
582 bidi_it->scan_dir = current_scan_dir;
583 bidi_cache_last_idx = idx;
586 /* Find a cached state with a given CHARPOS and resolved embedding
587 level less or equal to LEVEL. if LEVEL is -1, disregard the
588 resolved levels in cached states. DIR, if non-zero, means search
589 in that direction from the last cache hit. */
590 static ptrdiff_t
591 bidi_cache_search (ptrdiff_t charpos, int level, int dir)
593 ptrdiff_t i, i_start;
595 if (bidi_cache_idx > bidi_cache_start)
597 if (bidi_cache_last_idx == -1)
598 bidi_cache_last_idx = bidi_cache_idx - 1;
599 if (charpos < bidi_cache[bidi_cache_last_idx].charpos)
601 dir = -1;
602 i_start = bidi_cache_last_idx - 1;
604 else if (charpos > (bidi_cache[bidi_cache_last_idx].charpos
605 + bidi_cache[bidi_cache_last_idx].nchars - 1))
607 dir = 1;
608 i_start = bidi_cache_last_idx + 1;
610 else if (dir)
611 i_start = bidi_cache_last_idx;
612 else
614 dir = -1;
615 i_start = bidi_cache_idx - 1;
618 if (dir < 0)
620 /* Linear search for now; FIXME! */
621 for (i = i_start; i >= bidi_cache_start; i--)
622 if (bidi_cache[i].charpos <= charpos
623 && charpos < bidi_cache[i].charpos + bidi_cache[i].nchars
624 && (level == -1 || bidi_cache[i].resolved_level <= level))
625 return i;
627 else
629 for (i = i_start; i < bidi_cache_idx; i++)
630 if (bidi_cache[i].charpos <= charpos
631 && charpos < bidi_cache[i].charpos + bidi_cache[i].nchars
632 && (level == -1 || bidi_cache[i].resolved_level <= level))
633 return i;
637 return -1;
640 /* Find a cached state where the resolved level changes to a value
641 that is lower than LEVEL, and return its cache slot index. DIR is
642 the direction to search, starting with the last used cache slot.
643 If DIR is zero, we search backwards from the last occupied cache
644 slot. BEFORE means return the index of the slot that
645 is ``before'' the level change in the search direction. That is,
646 given the cached levels like this:
648 1122333442211
649 AB C
651 and assuming we are at the position cached at the slot marked with
652 C, searching backwards (DIR = -1) for LEVEL = 2 will return the
653 index of slot B or A, depending whether BEFORE is, respectively,
654 true or false. */
655 static ptrdiff_t
656 bidi_cache_find_level_change (int level, int dir, bool before)
658 if (bidi_cache_idx)
660 ptrdiff_t i = dir ? bidi_cache_last_idx : bidi_cache_idx - 1;
661 int incr = before ? 1 : 0;
663 eassert (!dir || bidi_cache_last_idx >= 0);
665 if (!dir)
666 dir = -1;
667 else if (!incr)
668 i += dir;
670 if (dir < 0)
672 while (i >= bidi_cache_start + incr)
674 if (bidi_cache[i - incr].resolved_level >= 0
675 && bidi_cache[i - incr].resolved_level < level)
676 return i;
677 i--;
680 else
682 while (i < bidi_cache_idx - incr)
684 if (bidi_cache[i + incr].resolved_level >= 0
685 && bidi_cache[i + incr].resolved_level < level)
686 return i;
687 i++;
692 return -1;
695 static void
696 bidi_cache_ensure_space (ptrdiff_t idx)
698 /* Enlarge the cache as needed. */
699 if (idx >= bidi_cache_size)
701 /* The bidi cache cannot be larger than the largest Lisp string
702 or buffer. */
703 ptrdiff_t string_or_buffer_bound
704 = max (BUF_BYTES_MAX, STRING_BYTES_BOUND);
706 /* Also, it cannot be larger than what C can represent. */
707 ptrdiff_t c_bound
708 = (min (PTRDIFF_MAX, SIZE_MAX) - bidi_shelve_header_size) / elsz;
710 bidi_cache
711 = xpalloc (bidi_cache, &bidi_cache_size,
712 max (BIDI_CACHE_CHUNK, idx - bidi_cache_size + 1),
713 min (string_or_buffer_bound, c_bound), elsz);
717 static void
718 bidi_cache_iterator_state (struct bidi_it *bidi_it, bool resolved)
720 ptrdiff_t idx;
722 /* We should never cache on backward scans. */
723 if (bidi_it->scan_dir == -1)
724 emacs_abort ();
725 idx = bidi_cache_search (bidi_it->charpos, -1, 1);
727 if (idx < 0)
729 idx = bidi_cache_idx;
730 bidi_cache_ensure_space (idx);
731 /* Character positions should correspond to cache positions 1:1.
732 If we are outside the range of cached positions, the cache is
733 useless and must be reset. */
734 if (idx > bidi_cache_start &&
735 (bidi_it->charpos > (bidi_cache[idx - 1].charpos
736 + bidi_cache[idx - 1].nchars)
737 || bidi_it->charpos < bidi_cache[bidi_cache_start].charpos))
739 bidi_cache_reset ();
740 idx = bidi_cache_start;
742 if (bidi_it->nchars <= 0)
743 emacs_abort ();
744 bidi_copy_it (&bidi_cache[idx], bidi_it);
745 if (!resolved)
746 bidi_cache[idx].resolved_level = -1;
748 else
750 /* Copy only the members which could have changed, to avoid
751 costly copying of the entire struct. */
752 bidi_cache[idx].type = bidi_it->type;
753 bidi_check_type (bidi_it->type);
754 bidi_cache[idx].type_after_w1 = bidi_it->type_after_w1;
755 bidi_check_type (bidi_it->type_after_w1);
756 if (resolved)
757 bidi_cache[idx].resolved_level = bidi_it->resolved_level;
758 else
759 bidi_cache[idx].resolved_level = -1;
760 bidi_cache[idx].invalid_levels = bidi_it->invalid_levels;
761 bidi_cache[idx].next_for_neutral = bidi_it->next_for_neutral;
762 bidi_cache[idx].next_for_ws = bidi_it->next_for_ws;
763 bidi_cache[idx].ignore_bn_limit = bidi_it->ignore_bn_limit;
764 bidi_cache[idx].disp_pos = bidi_it->disp_pos;
765 bidi_cache[idx].disp_prop = bidi_it->disp_prop;
768 bidi_cache_last_idx = idx;
769 if (idx >= bidi_cache_idx)
770 bidi_cache_idx = idx + 1;
773 static bidi_type_t
774 bidi_cache_find (ptrdiff_t charpos, int level, struct bidi_it *bidi_it)
776 ptrdiff_t i = bidi_cache_search (charpos, level, bidi_it->scan_dir);
778 if (i >= bidi_cache_start)
780 bidi_dir_t current_scan_dir = bidi_it->scan_dir;
782 bidi_copy_it (bidi_it, &bidi_cache[i]);
783 bidi_cache_last_idx = i;
784 /* Don't let scan direction from the cached state override
785 the current scan direction. */
786 bidi_it->scan_dir = current_scan_dir;
787 return bidi_it->type;
790 return UNKNOWN_BT;
793 static int
794 bidi_peek_at_next_level (struct bidi_it *bidi_it)
796 if (bidi_cache_idx == bidi_cache_start || bidi_cache_last_idx == -1)
797 emacs_abort ();
798 return bidi_cache[bidi_cache_last_idx + bidi_it->scan_dir].resolved_level;
802 /***********************************************************************
803 Pushing and popping the bidi iterator state
804 ***********************************************************************/
806 /* Push the bidi iterator state in preparation for reordering a
807 different object, e.g. display string found at certain buffer
808 position. Pushing the bidi iterator boils down to saving its
809 entire state on the cache and starting a new cache "stacked" on top
810 of the current cache. */
811 void
812 bidi_push_it (struct bidi_it *bidi_it)
814 /* Save the current iterator state in its entirety after the last
815 used cache slot. */
816 bidi_cache_ensure_space (bidi_cache_idx);
817 bidi_cache[bidi_cache_idx++] = *bidi_it;
819 /* Push the current cache start onto the stack. */
820 eassert (bidi_cache_sp < IT_STACK_SIZE);
821 bidi_cache_start_stack[bidi_cache_sp++] = bidi_cache_start;
823 /* Start a new level of cache, and make it empty. */
824 bidi_cache_start = bidi_cache_idx;
825 bidi_cache_last_idx = -1;
828 /* Restore the iterator state saved by bidi_push_it and return the
829 cache to the corresponding state. */
830 void
831 bidi_pop_it (struct bidi_it *bidi_it)
833 if (bidi_cache_start <= 0)
834 emacs_abort ();
836 /* Reset the next free cache slot index to what it was before the
837 call to bidi_push_it. */
838 bidi_cache_idx = bidi_cache_start - 1;
840 /* Restore the bidi iterator state saved in the cache. */
841 *bidi_it = bidi_cache[bidi_cache_idx];
843 /* Pop the previous cache start from the stack. */
844 if (bidi_cache_sp <= 0)
845 emacs_abort ();
846 bidi_cache_start = bidi_cache_start_stack[--bidi_cache_sp];
848 /* Invalidate the last-used cache slot data. */
849 bidi_cache_last_idx = -1;
852 static ptrdiff_t bidi_cache_total_alloc;
854 /* Stash away a copy of the cache and its control variables. */
855 void *
856 bidi_shelve_cache (void)
858 unsigned char *databuf;
859 ptrdiff_t alloc;
861 /* Empty cache. */
862 if (bidi_cache_idx == 0)
863 return NULL;
865 alloc = (bidi_shelve_header_size
866 + bidi_cache_idx * sizeof (struct bidi_it));
867 databuf = xmalloc (alloc);
868 bidi_cache_total_alloc += alloc;
870 memcpy (databuf, &bidi_cache_idx, sizeof (bidi_cache_idx));
871 memcpy (databuf + sizeof (bidi_cache_idx),
872 bidi_cache, bidi_cache_idx * sizeof (struct bidi_it));
873 memcpy (databuf + sizeof (bidi_cache_idx)
874 + bidi_cache_idx * sizeof (struct bidi_it),
875 bidi_cache_start_stack, sizeof (bidi_cache_start_stack));
876 memcpy (databuf + sizeof (bidi_cache_idx)
877 + bidi_cache_idx * sizeof (struct bidi_it)
878 + sizeof (bidi_cache_start_stack),
879 &bidi_cache_sp, sizeof (bidi_cache_sp));
880 memcpy (databuf + sizeof (bidi_cache_idx)
881 + bidi_cache_idx * sizeof (struct bidi_it)
882 + sizeof (bidi_cache_start_stack) + sizeof (bidi_cache_sp),
883 &bidi_cache_start, sizeof (bidi_cache_start));
884 memcpy (databuf + sizeof (bidi_cache_idx)
885 + bidi_cache_idx * sizeof (struct bidi_it)
886 + sizeof (bidi_cache_start_stack) + sizeof (bidi_cache_sp)
887 + sizeof (bidi_cache_start),
888 &bidi_cache_last_idx, sizeof (bidi_cache_last_idx));
890 return databuf;
893 /* Restore the cache state from a copy stashed away by
894 bidi_shelve_cache, and free the buffer used to stash that copy.
895 JUST_FREE means free the buffer, but don't restore the
896 cache; used when the corresponding iterator is discarded instead of
897 being restored. */
898 void
899 bidi_unshelve_cache (void *databuf, bool just_free)
901 unsigned char *p = databuf;
903 if (!p)
905 if (!just_free)
907 /* A NULL pointer means an empty cache. */
908 bidi_cache_start = 0;
909 bidi_cache_sp = 0;
910 bidi_cache_reset ();
913 else
915 if (just_free)
917 ptrdiff_t idx;
919 memcpy (&idx, p, sizeof (bidi_cache_idx));
920 bidi_cache_total_alloc
921 -= bidi_shelve_header_size + idx * sizeof (struct bidi_it);
923 else
925 memcpy (&bidi_cache_idx, p, sizeof (bidi_cache_idx));
926 bidi_cache_ensure_space (bidi_cache_idx);
927 memcpy (bidi_cache, p + sizeof (bidi_cache_idx),
928 bidi_cache_idx * sizeof (struct bidi_it));
929 memcpy (bidi_cache_start_stack,
930 p + sizeof (bidi_cache_idx)
931 + bidi_cache_idx * sizeof (struct bidi_it),
932 sizeof (bidi_cache_start_stack));
933 memcpy (&bidi_cache_sp,
934 p + sizeof (bidi_cache_idx)
935 + bidi_cache_idx * sizeof (struct bidi_it)
936 + sizeof (bidi_cache_start_stack),
937 sizeof (bidi_cache_sp));
938 memcpy (&bidi_cache_start,
939 p + sizeof (bidi_cache_idx)
940 + bidi_cache_idx * sizeof (struct bidi_it)
941 + sizeof (bidi_cache_start_stack) + sizeof (bidi_cache_sp),
942 sizeof (bidi_cache_start));
943 memcpy (&bidi_cache_last_idx,
944 p + sizeof (bidi_cache_idx)
945 + bidi_cache_idx * sizeof (struct bidi_it)
946 + sizeof (bidi_cache_start_stack) + sizeof (bidi_cache_sp)
947 + sizeof (bidi_cache_start),
948 sizeof (bidi_cache_last_idx));
949 bidi_cache_total_alloc
950 -= (bidi_shelve_header_size
951 + bidi_cache_idx * sizeof (struct bidi_it));
954 xfree (p);
959 /***********************************************************************
960 Initialization
961 ***********************************************************************/
962 static void
963 bidi_initialize (void)
965 bidi_type_table = uniprop_table (intern ("bidi-class"));
966 if (NILP (bidi_type_table))
967 emacs_abort ();
968 staticpro (&bidi_type_table);
970 bidi_mirror_table = uniprop_table (intern ("mirroring"));
971 if (NILP (bidi_mirror_table))
972 emacs_abort ();
973 staticpro (&bidi_mirror_table);
975 Qparagraph_start = intern ("paragraph-start");
976 staticpro (&Qparagraph_start);
977 paragraph_start_re = Fsymbol_value (Qparagraph_start);
978 if (!STRINGP (paragraph_start_re))
979 paragraph_start_re = build_string ("\f\\|[ \t]*$");
980 staticpro (&paragraph_start_re);
981 Qparagraph_separate = intern ("paragraph-separate");
982 staticpro (&Qparagraph_separate);
983 paragraph_separate_re = Fsymbol_value (Qparagraph_separate);
984 if (!STRINGP (paragraph_separate_re))
985 paragraph_separate_re = build_string ("[ \t\f]*$");
986 staticpro (&paragraph_separate_re);
988 bidi_cache_sp = 0;
989 bidi_cache_total_alloc = 0;
991 bidi_initialized = 1;
994 /* Do whatever UAX#9 clause X8 says should be done at paragraph's
995 end. */
996 static void
997 bidi_set_paragraph_end (struct bidi_it *bidi_it)
999 bidi_it->invalid_levels = 0;
1000 bidi_it->invalid_isolates = 0;
1001 bidi_it->stack_idx = 0;
1002 bidi_it->resolved_level = bidi_it->level_stack[0].level;
1005 /* Initialize the bidi iterator from buffer/string position CHARPOS. */
1006 void
1007 bidi_init_it (ptrdiff_t charpos, ptrdiff_t bytepos, bool frame_window_p,
1008 struct bidi_it *bidi_it)
1010 if (! bidi_initialized)
1011 bidi_initialize ();
1012 if (charpos >= 0)
1013 bidi_it->charpos = charpos;
1014 if (bytepos >= 0)
1015 bidi_it->bytepos = bytepos;
1016 bidi_it->frame_window_p = frame_window_p;
1017 bidi_it->nchars = -1; /* to be computed in bidi_resolve_explicit_1 */
1018 bidi_it->first_elt = 1;
1019 bidi_set_paragraph_end (bidi_it);
1020 bidi_it->new_paragraph = 1;
1021 bidi_it->separator_limit = -1;
1022 bidi_it->type = NEUTRAL_B;
1023 bidi_it->type_after_w1 = NEUTRAL_B;
1024 bidi_it->orig_type = NEUTRAL_B;
1025 /* FIXME: Review this!!! */
1026 bidi_it->prev.type = bidi_it->prev.type_after_w1
1027 = bidi_it->prev.orig_type = UNKNOWN_BT;
1028 bidi_it->last_strong.type = bidi_it->last_strong.type_after_w1
1029 = bidi_it->last_strong.orig_type = UNKNOWN_BT;
1030 bidi_it->next_for_neutral.charpos = -1;
1031 bidi_it->next_for_neutral.type
1032 = bidi_it->next_for_neutral.type_after_w1
1033 = bidi_it->next_for_neutral.orig_type = UNKNOWN_BT;
1034 bidi_it->prev_for_neutral.charpos = -1;
1035 bidi_it->prev_for_neutral.type
1036 = bidi_it->prev_for_neutral.type_after_w1
1037 = bidi_it->prev_for_neutral.orig_type = UNKNOWN_BT;
1038 bidi_it->sos = L2R; /* FIXME: should it be user-selectable? */
1039 bidi_it->disp_pos = -1; /* invalid/unknown */
1040 bidi_it->disp_prop = 0;
1041 /* We can only shrink the cache if we are at the bottom level of its
1042 "stack". */
1043 if (bidi_cache_start == 0)
1044 bidi_cache_shrink ();
1045 else
1046 bidi_cache_reset ();
1049 /* Perform initializations for reordering a new line of bidi text. */
1050 static void
1051 bidi_line_init (struct bidi_it *bidi_it)
1053 bidi_it->scan_dir = 1; /* FIXME: do we need to have control on this? */
1054 bidi_it->stack_idx = 0;
1055 bidi_it->resolved_level = bidi_it->level_stack[0].level;
1056 bidi_it->level_stack[0].override = NEUTRAL_DIR; /* X1 */
1057 bidi_it->level_stack[0].isolate_status = false; /* X1 */
1058 bidi_it->invalid_levels = 0;
1059 bidi_it->isolate_level = 0; /* X1 */
1060 bidi_it->invalid_isolates = 0; /* X1 */
1061 /* Setting this to zero will force its recomputation the first time
1062 we need it for W5. */
1063 bidi_it->next_en_pos = 0;
1064 bidi_it->next_en_type = UNKNOWN_BT;
1065 bidi_it->next_for_ws.type = UNKNOWN_BT;
1066 bidi_set_sos_type (bidi_it,
1067 (bidi_it->paragraph_dir == R2L ? 1 : 0),
1068 bidi_it->level_stack[0].level); /* X10 */
1070 bidi_cache_reset ();
1074 /***********************************************************************
1075 Fetching characters
1076 ***********************************************************************/
1078 /* Count bytes in string S between BEG/BEGBYTE and END. BEG and END
1079 are zero-based character positions in S, BEGBYTE is byte position
1080 corresponding to BEG. UNIBYTE means S is a unibyte string. */
1081 static ptrdiff_t
1082 bidi_count_bytes (const unsigned char *s, ptrdiff_t beg,
1083 ptrdiff_t begbyte, ptrdiff_t end, bool unibyte)
1085 ptrdiff_t pos = beg;
1086 const unsigned char *p = s + begbyte, *start = p;
1088 if (unibyte)
1089 p = s + end;
1090 else
1092 if (!CHAR_HEAD_P (*p))
1093 emacs_abort ();
1095 while (pos < end)
1097 p += BYTES_BY_CHAR_HEAD (*p);
1098 pos++;
1102 return p - start;
1105 /* Fetch and return the character at byte position BYTEPOS. If S is
1106 non-NULL, fetch the character from string S; otherwise fetch the
1107 character from the current buffer. UNIBYTE means S is a
1108 unibyte string. */
1109 static int
1110 bidi_char_at_pos (ptrdiff_t bytepos, const unsigned char *s, bool unibyte)
1112 if (s)
1114 s += bytepos;
1115 if (unibyte)
1116 return *s;
1118 else
1119 s = BYTE_POS_ADDR (bytepos);
1120 return STRING_CHAR (s);
1123 /* Fetch and return the character at CHARPOS/BYTEPOS. If that
1124 character is covered by a display string, treat the entire run of
1125 covered characters as a single character, either u+2029 or u+FFFC,
1126 and return their combined length in CH_LEN and NCHARS. DISP_POS
1127 specifies the character position of the next display string, or -1
1128 if not yet computed. When the next character is at or beyond that
1129 position, the function updates DISP_POS with the position of the
1130 next display string. *DISP_PROP non-zero means that there's really
1131 a display string at DISP_POS, as opposed to when we searched till
1132 DISP_POS without finding one. If *DISP_PROP is 2, it means the
1133 display spec is of the form `(space ...)', which is replaced with
1134 u+2029 to handle it as a paragraph separator. STRING->s is the C
1135 string to iterate, or NULL if iterating over a buffer or a Lisp
1136 string; in the latter case, STRING->lstring is the Lisp string. */
1137 static int
1138 bidi_fetch_char (ptrdiff_t charpos, ptrdiff_t bytepos, ptrdiff_t *disp_pos,
1139 int *disp_prop, struct bidi_string_data *string,
1140 struct window *w,
1141 bool frame_window_p, ptrdiff_t *ch_len, ptrdiff_t *nchars)
1143 int ch;
1144 ptrdiff_t endpos
1145 = (string->s || STRINGP (string->lstring)) ? string->schars : ZV;
1146 struct text_pos pos;
1147 int len;
1149 /* If we got past the last known position of display string, compute
1150 the position of the next one. That position could be at CHARPOS. */
1151 if (charpos < endpos && charpos > *disp_pos)
1153 SET_TEXT_POS (pos, charpos, bytepos);
1154 *disp_pos = compute_display_string_pos (&pos, string, w, frame_window_p,
1155 disp_prop);
1158 /* Fetch the character at BYTEPOS. */
1159 if (charpos >= endpos)
1161 ch = BIDI_EOB;
1162 *ch_len = 1;
1163 *nchars = 1;
1164 *disp_pos = endpos;
1165 *disp_prop = 0;
1167 else if (charpos >= *disp_pos && *disp_prop)
1169 ptrdiff_t disp_end_pos;
1171 /* We don't expect to find ourselves in the middle of a display
1172 property. Hopefully, it will never be needed. */
1173 if (charpos > *disp_pos)
1174 emacs_abort ();
1175 /* Text covered by `display' properties and overlays with
1176 display properties or display strings is handled as a single
1177 character that represents the entire run of characters
1178 covered by the display property. */
1179 if (*disp_prop == 2)
1181 /* `(space ...)' display specs are handled as paragraph
1182 separators for the purposes of the reordering; see UAX#9
1183 section 3 and clause HL1 in section 4.3 there. */
1184 ch = 0x2029;
1186 else
1188 /* All other display specs are handled as the Unicode Object
1189 Replacement Character. */
1190 ch = 0xFFFC;
1192 disp_end_pos = compute_display_string_end (*disp_pos, string);
1193 if (disp_end_pos < 0)
1195 /* Somebody removed the display string from the buffer
1196 behind our back. Recover by processing this buffer
1197 position as if no display property were present there to
1198 begin with. */
1199 *disp_prop = 0;
1200 goto normal_char;
1202 *nchars = disp_end_pos - *disp_pos;
1203 if (*nchars <= 0)
1204 emacs_abort ();
1205 if (string->s)
1206 *ch_len = bidi_count_bytes (string->s, *disp_pos, bytepos,
1207 disp_end_pos, string->unibyte);
1208 else if (STRINGP (string->lstring))
1209 *ch_len = bidi_count_bytes (SDATA (string->lstring), *disp_pos,
1210 bytepos, disp_end_pos, string->unibyte);
1211 else
1212 *ch_len = CHAR_TO_BYTE (disp_end_pos) - bytepos;
1214 else
1216 normal_char:
1217 if (string->s)
1220 if (!string->unibyte)
1222 ch = STRING_CHAR_AND_LENGTH (string->s + bytepos, len);
1223 *ch_len = len;
1225 else
1227 ch = UNIBYTE_TO_CHAR (string->s[bytepos]);
1228 *ch_len = 1;
1231 else if (STRINGP (string->lstring))
1233 if (!string->unibyte)
1235 ch = STRING_CHAR_AND_LENGTH (SDATA (string->lstring) + bytepos,
1236 len);
1237 *ch_len = len;
1239 else
1241 ch = UNIBYTE_TO_CHAR (SREF (string->lstring, bytepos));
1242 *ch_len = 1;
1245 else
1247 ch = STRING_CHAR_AND_LENGTH (BYTE_POS_ADDR (bytepos), len);
1248 *ch_len = len;
1250 *nchars = 1;
1253 /* If we just entered a run of characters covered by a display
1254 string, compute the position of the next display string. */
1255 if (charpos + *nchars <= endpos && charpos + *nchars > *disp_pos
1256 && *disp_prop)
1258 SET_TEXT_POS (pos, charpos + *nchars, bytepos + *ch_len);
1259 *disp_pos = compute_display_string_pos (&pos, string, w, frame_window_p,
1260 disp_prop);
1263 return ch;
1266 /* Like bidi_fetch_char, but ignore any text between an isolate
1267 initiator and its matching PDI or, if it has no matching PDI, the
1268 end of the paragraph. If isolates were skipped, CH_LEN and NCHARS
1269 are set to the number of bytes and characters between BYTEPOS/CHARPOS
1270 and the character that was fetched after skipping the isolates. */
1271 static int
1272 bidi_fetch_char_skip_isolates (ptrdiff_t charpos, ptrdiff_t bytepos,
1273 ptrdiff_t *disp_pos, int *disp_prop,
1274 struct bidi_string_data *string,
1275 struct window *w, bool frame_window_p,
1276 ptrdiff_t *ch_len, ptrdiff_t *nchars)
1278 ptrdiff_t orig_charpos = charpos, orig_bytepos = bytepos;
1279 int ch = bidi_fetch_char (charpos, bytepos, disp_pos, disp_prop, string, w,
1280 frame_window_p, ch_len, nchars);
1281 bidi_type_t ch_type = bidi_get_type (ch, NEUTRAL_DIR);
1282 ptrdiff_t level = 0;
1284 if (ch_type == LRI || ch_type == RLI || ch_type == FSI)
1286 level++;
1287 while (level > 0 && ch_type != NEUTRAL_B)
1289 charpos += *nchars;
1290 bytepos += *ch_len;
1291 ch = bidi_fetch_char (charpos, bytepos, disp_pos, disp_prop, string,
1292 w, frame_window_p, ch_len, nchars);
1293 ch_type = bidi_get_type (ch, NEUTRAL_DIR);
1294 /* A Note to P2 says to ignore max_depth limit. */
1295 if (ch_type == LRI || ch_type == RLI || ch_type == FSI)
1296 level++;
1297 else if (ch_type == PDI)
1298 level--;
1302 /* Communicate to the caller how much did we skip, so it could get
1303 past the last character position we examined. */
1304 *nchars += charpos - orig_charpos;
1305 *ch_len += bytepos - orig_bytepos;
1306 return ch;
1311 /***********************************************************************
1312 Determining paragraph direction
1313 ***********************************************************************/
1315 /* Check if buffer position CHARPOS/BYTEPOS is the end of a paragraph.
1316 Value is the non-negative length of the paragraph separator
1317 following the buffer position, -1 if position is at the beginning
1318 of a new paragraph, or -2 if position is neither at beginning nor
1319 at end of a paragraph. */
1320 static ptrdiff_t
1321 bidi_at_paragraph_end (ptrdiff_t charpos, ptrdiff_t bytepos)
1323 Lisp_Object sep_re;
1324 Lisp_Object start_re;
1325 ptrdiff_t val;
1327 sep_re = paragraph_separate_re;
1328 start_re = paragraph_start_re;
1330 val = fast_looking_at (sep_re, charpos, bytepos, ZV, ZV_BYTE, Qnil);
1331 if (val < 0)
1333 if (fast_looking_at (start_re, charpos, bytepos, ZV, ZV_BYTE, Qnil) >= 0)
1334 val = -1;
1335 else
1336 val = -2;
1339 return val;
1342 /* If the user has requested the long scans caching, make sure that
1343 BIDI cache is enabled. Otherwise, make sure it's disabled. */
1345 static struct region_cache *
1346 bidi_paragraph_cache_on_off (void)
1348 struct buffer *cache_buffer = current_buffer;
1349 bool indirect_p = false;
1351 /* For indirect buffers, make sure to use the cache of their base
1352 buffer. */
1353 if (cache_buffer->base_buffer)
1355 cache_buffer = cache_buffer->base_buffer;
1356 indirect_p = true;
1359 /* Don't turn on or off the cache in the base buffer, if the value
1360 of cache-long-scans of the base buffer is inconsistent with that.
1361 This is because doing so will just make the cache pure overhead,
1362 since if we turn it on via indirect buffer, it will be
1363 immediately turned off by its base buffer. */
1364 if (NILP (BVAR (current_buffer, cache_long_scans)))
1366 if (!indirect_p
1367 || NILP (BVAR (cache_buffer, cache_long_scans)))
1369 if (cache_buffer->bidi_paragraph_cache)
1371 free_region_cache (cache_buffer->bidi_paragraph_cache);
1372 cache_buffer->bidi_paragraph_cache = 0;
1375 return NULL;
1377 else
1379 if (!indirect_p
1380 || !NILP (BVAR (cache_buffer, cache_long_scans)))
1382 if (!cache_buffer->bidi_paragraph_cache)
1383 cache_buffer->bidi_paragraph_cache = new_region_cache ();
1385 return cache_buffer->bidi_paragraph_cache;
1389 /* On my 2005-vintage machine, searching back for paragraph start
1390 takes ~1 ms per line. And bidi_paragraph_init is called 4 times
1391 when user types C-p. The number below limits each call to
1392 bidi_paragraph_init to about 10 ms. */
1393 #define MAX_PARAGRAPH_SEARCH 7500
1395 /* Find the beginning of this paragraph by looking back in the buffer.
1396 Value is the byte position of the paragraph's beginning, or
1397 BEGV_BYTE if paragraph_start_re is still not found after looking
1398 back MAX_PARAGRAPH_SEARCH lines in the buffer. */
1399 static ptrdiff_t
1400 bidi_find_paragraph_start (ptrdiff_t pos, ptrdiff_t pos_byte)
1402 Lisp_Object re = paragraph_start_re;
1403 ptrdiff_t limit = ZV, limit_byte = ZV_BYTE;
1404 struct region_cache *bpc = bidi_paragraph_cache_on_off ();
1405 ptrdiff_t n = 0, oldpos = pos, next;
1406 struct buffer *cache_buffer = current_buffer;
1408 if (cache_buffer->base_buffer)
1409 cache_buffer = cache_buffer->base_buffer;
1411 while (pos_byte > BEGV_BYTE
1412 && n++ < MAX_PARAGRAPH_SEARCH
1413 && fast_looking_at (re, pos, pos_byte, limit, limit_byte, Qnil) < 0)
1415 /* FIXME: What if the paragraph beginning is covered by a
1416 display string? And what if a display string covering some
1417 of the text over which we scan back includes
1418 paragraph_start_re? */
1419 DEC_BOTH (pos, pos_byte);
1420 if (bpc && region_cache_backward (cache_buffer, bpc, pos, &next))
1422 pos = next, pos_byte = CHAR_TO_BYTE (pos);
1423 break;
1425 else
1426 pos = find_newline_no_quit (pos, pos_byte, -1, &pos_byte);
1428 if (n >= MAX_PARAGRAPH_SEARCH)
1429 pos = BEGV, pos_byte = BEGV_BYTE;
1430 if (bpc)
1431 know_region_cache (cache_buffer, bpc, pos, oldpos);
1432 /* Positions returned by the region cache are not limited to
1433 BEGV..ZV range, so we limit them here. */
1434 pos_byte = clip_to_bounds (BEGV_BYTE, pos_byte, ZV_BYTE);
1435 return pos_byte;
1438 /* On a 3.4 GHz machine, searching forward for a strong directional
1439 character in a long paragraph full of weaks or neutrals takes about
1440 1 ms for each 20K characters. The number below limits each call to
1441 bidi_paragraph_init to less than 10 ms even on slow machines. */
1442 #define MAX_STRONG_CHAR_SEARCH 100000
1444 /* Starting from POS, find the first strong (L, R, or AL) character,
1445 while skipping over any characters between an isolate initiator and
1446 its matching PDI. STOP_AT_PDI non-zero means stop at the PDI that
1447 matches the isolate initiator at POS. Return the bidi type of the
1448 character where the search stopped. Give up if after examining
1449 MAX_STRONG_CHAR_SEARCH buffer or string positions no strong
1450 character was found. */
1451 static bidi_type_t
1452 find_first_strong_char (ptrdiff_t pos, ptrdiff_t bytepos, ptrdiff_t end,
1453 ptrdiff_t *disp_pos, int *disp_prop,
1454 struct bidi_string_data *string, struct window *w,
1455 bool string_p, bool frame_window_p,
1456 ptrdiff_t *ch_len, ptrdiff_t *nchars, bool stop_at_pdi)
1458 ptrdiff_t pos1;
1459 bidi_type_t type;
1460 int ch;
1462 if (stop_at_pdi)
1464 /* If STOP_AT_PDI is non-zero, we must have been called with FSI
1465 at POS. Get past it. */
1466 #ifdef ENABLE_CHECKING
1467 ch = bidi_fetch_char (pos, bytepos, disp_pos, disp_prop, string, w,
1468 frame_window_p, ch_len, nchars);
1469 type = bidi_get_type (ch, NEUTRAL_DIR);
1470 eassert (type == FSI /* || type == LRI || type == RLI */);
1471 #endif
1472 pos += *nchars;
1473 bytepos += *ch_len;
1475 ch = bidi_fetch_char_skip_isolates (pos, bytepos, disp_pos, disp_prop, string,
1476 w, frame_window_p, ch_len, nchars);
1477 type = bidi_get_type (ch, NEUTRAL_DIR);
1479 pos1 = pos;
1480 for (pos += *nchars, bytepos += *ch_len;
1481 bidi_get_category (type) != STRONG
1482 /* If requested to stop at first PDI, stop there. */
1483 && !(stop_at_pdi && type == PDI)
1484 /* Stop when searched too far into an abnormally large
1485 paragraph full of weak or neutral characters. */
1486 && pos - pos1 < MAX_STRONG_CHAR_SEARCH;
1487 type = bidi_get_type (ch, NEUTRAL_DIR))
1489 if (pos >= end)
1491 /* Pretend there's a paragraph separator at end of
1492 buffer/string. */
1493 type = NEUTRAL_B;
1494 break;
1496 if (!string_p
1497 && type == NEUTRAL_B
1498 && bidi_at_paragraph_end (pos, bytepos) >= -1)
1499 break;
1500 /* Fetch next character and advance to get past it. */
1501 ch = bidi_fetch_char_skip_isolates (pos, bytepos, disp_pos, disp_prop,
1502 string, w, frame_window_p,
1503 ch_len, nchars);
1504 pos += *nchars;
1505 bytepos += *ch_len;
1507 return type;
1510 /* Determine the base direction, a.k.a. base embedding level, of the
1511 paragraph we are about to iterate through. If DIR is either L2R or
1512 R2L, just use that. Otherwise, determine the paragraph direction
1513 from the first strong directional character of the paragraph.
1515 NO_DEFAULT_P means don't default to L2R if the paragraph
1516 has no strong directional characters and both DIR and
1517 bidi_it->paragraph_dir are NEUTRAL_DIR. In that case, search back
1518 in the buffer until a paragraph is found with a strong character,
1519 or until hitting BEGV. In the latter case, fall back to L2R. This
1520 flag is used in current-bidi-paragraph-direction.
1522 Note that this function gives the paragraph separator the same
1523 direction as the preceding paragraph, even though Emacs generally
1524 views the separator as not belonging to any paragraph. */
1525 void
1526 bidi_paragraph_init (bidi_dir_t dir, struct bidi_it *bidi_it, bool no_default_p)
1528 ptrdiff_t bytepos = bidi_it->bytepos;
1529 bool string_p = bidi_it->string.s || STRINGP (bidi_it->string.lstring);
1530 ptrdiff_t pstartbyte;
1531 /* Note that begbyte is a byte position, while end is a character
1532 position. Yes, this is ugly, but we are trying to avoid costly
1533 calls to BYTE_TO_CHAR and its ilk. */
1534 ptrdiff_t begbyte = string_p ? 0 : BEGV_BYTE;
1535 ptrdiff_t end = string_p ? bidi_it->string.schars : ZV;
1537 /* Special case for an empty buffer. */
1538 if (bytepos == begbyte && bidi_it->charpos == end)
1539 dir = L2R;
1540 /* We should never be called at EOB or before BEGV. */
1541 else if (bidi_it->charpos >= end || bytepos < begbyte)
1542 emacs_abort ();
1544 if (dir == L2R)
1546 bidi_it->paragraph_dir = L2R;
1547 bidi_it->new_paragraph = 0;
1549 else if (dir == R2L)
1551 bidi_it->paragraph_dir = R2L;
1552 bidi_it->new_paragraph = 0;
1554 else if (dir == NEUTRAL_DIR) /* P2 */
1556 ptrdiff_t ch_len, nchars;
1557 ptrdiff_t pos, disp_pos = -1;
1558 int disp_prop = 0;
1559 bidi_type_t type;
1560 const unsigned char *s;
1562 if (!bidi_initialized)
1563 bidi_initialize ();
1565 /* If we are inside a paragraph separator, we are just waiting
1566 for the separator to be exhausted; use the previous paragraph
1567 direction. But don't do that if we have been just reseated,
1568 because we need to reinitialize below in that case. */
1569 if (!bidi_it->first_elt
1570 && bidi_it->charpos < bidi_it->separator_limit)
1571 return;
1573 /* If we are on a newline, get past it to where the next
1574 paragraph might start. But don't do that at BEGV since then
1575 we are potentially in a new paragraph that doesn't yet
1576 exist. */
1577 pos = bidi_it->charpos;
1578 s = (STRINGP (bidi_it->string.lstring)
1579 ? SDATA (bidi_it->string.lstring)
1580 : bidi_it->string.s);
1581 if (bytepos > begbyte
1582 && bidi_char_at_pos (bytepos, s, bidi_it->string.unibyte) == '\n')
1584 bytepos++;
1585 pos++;
1588 /* We are either at the beginning of a paragraph or in the
1589 middle of it. Find where this paragraph starts. */
1590 if (string_p)
1592 /* We don't support changes of paragraph direction inside a
1593 string. It is treated as a single paragraph. */
1594 pstartbyte = 0;
1596 else
1597 pstartbyte = bidi_find_paragraph_start (pos, bytepos);
1598 bidi_it->separator_limit = -1;
1599 bidi_it->new_paragraph = 0;
1601 /* The following loop is run more than once only if NO_DEFAULT_P,
1602 and only if we are iterating on a buffer. */
1603 do {
1604 bytepos = pstartbyte;
1605 if (!string_p)
1606 pos = BYTE_TO_CHAR (bytepos);
1607 type = find_first_strong_char (pos, bytepos, end, &disp_pos, &disp_prop,
1608 &bidi_it->string, bidi_it->w,
1609 string_p, bidi_it->frame_window_p,
1610 &ch_len, &nchars, false);
1611 if (type == STRONG_R || type == STRONG_AL) /* P3 */
1612 bidi_it->paragraph_dir = R2L;
1613 else if (type == STRONG_L)
1614 bidi_it->paragraph_dir = L2R;
1615 if (!string_p
1616 && no_default_p && bidi_it->paragraph_dir == NEUTRAL_DIR)
1618 /* If this paragraph is at BEGV, default to L2R. */
1619 if (pstartbyte == BEGV_BYTE)
1620 bidi_it->paragraph_dir = L2R; /* P3 and HL1 */
1621 else
1623 ptrdiff_t prevpbyte = pstartbyte;
1624 ptrdiff_t p = BYTE_TO_CHAR (pstartbyte), pbyte = pstartbyte;
1626 /* Find the beginning of the previous paragraph, if any. */
1627 while (pbyte > BEGV_BYTE && prevpbyte >= pstartbyte)
1629 /* FXIME: What if p is covered by a display
1630 string? See also a FIXME inside
1631 bidi_find_paragraph_start. */
1632 DEC_BOTH (p, pbyte);
1633 prevpbyte = bidi_find_paragraph_start (p, pbyte);
1635 pstartbyte = prevpbyte;
1638 } while (!string_p
1639 && no_default_p && bidi_it->paragraph_dir == NEUTRAL_DIR);
1641 else
1642 emacs_abort ();
1644 /* Contrary to UAX#9 clause P3, we only default the paragraph
1645 direction to L2R if we have no previous usable paragraph
1646 direction. This is allowed by the HL1 clause. */
1647 if (bidi_it->paragraph_dir != L2R && bidi_it->paragraph_dir != R2L)
1648 bidi_it->paragraph_dir = L2R; /* P3 and HL1 ``higher-level protocols'' */
1649 if (bidi_it->paragraph_dir == R2L)
1650 bidi_it->level_stack[0].level = 1;
1651 else
1652 bidi_it->level_stack[0].level = 0;
1654 bidi_line_init (bidi_it);
1658 /***********************************************************************
1659 Resolving explicit and implicit levels.
1660 The rest of this file constitutes the core of the UBA implementation.
1661 ***********************************************************************/
1663 static bool
1664 bidi_explicit_dir_char (int ch)
1666 bidi_type_t ch_type;
1668 if (!bidi_initialized)
1669 emacs_abort ();
1670 ch_type = (bidi_type_t) XINT (CHAR_TABLE_REF (bidi_type_table, ch));
1671 return (ch_type == LRE || ch_type == LRO
1672 || ch_type == RLE || ch_type == RLO
1673 || ch_type == PDF);
1676 /* A helper function for bidi_resolve_explicit. It advances to the
1677 next character in logical order and determines the new embedding
1678 level and directional override, but does not take into account
1679 empty embeddings. */
1680 static int
1681 bidi_resolve_explicit_1 (struct bidi_it *bidi_it)
1683 int curchar;
1684 bidi_type_t type, typ1;
1685 int current_level;
1686 int new_level;
1687 bidi_dir_t override;
1688 bool isolate_status;
1689 bool string_p = bidi_it->string.s || STRINGP (bidi_it->string.lstring);
1690 ptrdiff_t ch_len, nchars, disp_pos, end;
1691 int disp_prop;
1693 /* If reseat()'ed, don't advance, so as to start iteration from the
1694 position where we were reseated. bidi_it->bytepos can be less
1695 than BEGV_BYTE after reseat to BEGV. */
1696 if (bidi_it->bytepos < (string_p ? 0 : BEGV_BYTE)
1697 || bidi_it->first_elt)
1699 bidi_it->first_elt = 0;
1700 if (string_p)
1702 const unsigned char *p
1703 = (STRINGP (bidi_it->string.lstring)
1704 ? SDATA (bidi_it->string.lstring)
1705 : bidi_it->string.s);
1707 if (bidi_it->charpos < 0)
1708 bidi_it->charpos = bidi_it->bytepos = 0;
1709 eassert (bidi_it->bytepos == bidi_count_bytes (p, 0, 0,
1710 bidi_it->charpos,
1711 bidi_it->string.unibyte));
1713 else
1715 if (bidi_it->charpos < BEGV)
1717 bidi_it->charpos = BEGV;
1718 bidi_it->bytepos = BEGV_BYTE;
1720 eassert (bidi_it->bytepos == CHAR_TO_BYTE (bidi_it->charpos));
1723 /* Don't move at end of buffer/string. */
1724 else if (bidi_it->charpos < (string_p ? bidi_it->string.schars : ZV))
1726 /* Advance to the next character, skipping characters covered by
1727 display strings (nchars > 1). */
1728 if (bidi_it->nchars <= 0)
1729 emacs_abort ();
1730 bidi_it->charpos += bidi_it->nchars;
1731 if (bidi_it->ch_len == 0)
1732 emacs_abort ();
1733 bidi_it->bytepos += bidi_it->ch_len;
1736 current_level = bidi_it->level_stack[bidi_it->stack_idx].level; /* X1 */
1737 override = bidi_it->level_stack[bidi_it->stack_idx].override;
1738 isolate_status = bidi_it->level_stack[bidi_it->stack_idx].isolate_status;
1739 new_level = current_level;
1740 bidi_it->resolved_level = new_level;
1742 if (bidi_it->charpos >= (string_p ? bidi_it->string.schars : ZV))
1744 curchar = BIDI_EOB;
1745 bidi_it->ch_len = 1;
1746 bidi_it->nchars = 1;
1747 bidi_it->disp_pos = (string_p ? bidi_it->string.schars : ZV);
1748 bidi_it->disp_prop = 0;
1750 else
1752 /* Fetch the character at BYTEPOS. If it is covered by a
1753 display string, treat the entire run of covered characters as
1754 a single character u+FFFC. */
1755 curchar = bidi_fetch_char (bidi_it->charpos, bidi_it->bytepos,
1756 &bidi_it->disp_pos, &bidi_it->disp_prop,
1757 &bidi_it->string, bidi_it->w,
1758 bidi_it->frame_window_p,
1759 &bidi_it->ch_len, &bidi_it->nchars);
1761 bidi_it->ch = curchar;
1763 /* Don't apply directional override here, as all the types we handle
1764 below will not be affected by the override anyway, and we need
1765 the original type unaltered. The override will be applied in
1766 bidi_resolve_weak. */
1767 type = bidi_get_type (curchar, NEUTRAL_DIR);
1768 bidi_it->orig_type = type;
1769 bidi_check_type (bidi_it->orig_type);
1771 bidi_it->type_after_w1 = UNKNOWN_BT;
1773 switch (type)
1775 case RLE: /* X2 */
1776 case RLO: /* X4 */
1777 bidi_it->type_after_w1 = type;
1778 bidi_check_type (bidi_it->type_after_w1);
1779 type = WEAK_BN; /* X9/Retaining */
1780 if (bidi_it->ignore_bn_limit <= -1)
1782 if (current_level < BIDI_MAXDEPTH
1783 && bidi_it->invalid_levels == 0
1784 && bidi_it->invalid_isolates == 0)
1786 /* Compute the least odd embedding level greater than
1787 the current level. */
1788 new_level = ((current_level + 1) & ~1) + 1;
1789 if (bidi_it->type_after_w1 == RLE)
1790 override = NEUTRAL_DIR;
1791 else
1792 override = R2L;
1793 bidi_push_embedding_level (bidi_it, new_level, override, false);
1794 bidi_it->resolved_level = new_level;
1796 else
1798 if (bidi_it->invalid_isolates == 0)
1799 bidi_it->invalid_levels++;
1802 else if (bidi_it->prev.type_after_w1 == WEAK_EN /* W5/Retaining */
1803 || (bidi_it->next_en_pos > bidi_it->charpos
1804 && bidi_it->next_en_type == WEAK_EN))
1805 type = WEAK_EN;
1806 break;
1807 case LRE: /* X3 */
1808 case LRO: /* X5 */
1809 bidi_it->type_after_w1 = type;
1810 bidi_check_type (bidi_it->type_after_w1);
1811 type = WEAK_BN; /* X9/Retaining */
1812 if (bidi_it->ignore_bn_limit <= -1)
1814 if (current_level < BIDI_MAXDEPTH - 1
1815 && bidi_it->invalid_levels == 0
1816 && bidi_it->invalid_isolates == 0)
1818 /* Compute the least even embedding level greater than
1819 the current level. */
1820 new_level = ((current_level + 2) & ~1);
1821 if (bidi_it->type_after_w1 == LRE)
1822 override = NEUTRAL_DIR;
1823 else
1824 override = L2R;
1825 bidi_push_embedding_level (bidi_it, new_level, override, false);
1826 bidi_it->resolved_level = new_level;
1828 else
1830 if (bidi_it->invalid_isolates == 0)
1831 bidi_it->invalid_levels++;
1834 else if (bidi_it->prev.type_after_w1 == WEAK_EN /* W5/Retaining */
1835 || (bidi_it->next_en_pos > bidi_it->charpos
1836 && bidi_it->next_en_type == WEAK_EN))
1837 type = WEAK_EN;
1838 break;
1839 case FSI: /* X5c */
1840 end = string_p ? bidi_it->string.schars : ZV;
1841 disp_pos = bidi_it->disp_pos;
1842 disp_prop = bidi_it->disp_prop;
1843 nchars = bidi_it->nchars;
1844 ch_len = bidi_it->ch_len;
1845 typ1 = find_first_strong_char (bidi_it->charpos, bidi_it->bytepos, end,
1846 &disp_pos, &disp_prop, &bidi_it->string,
1847 bidi_it->w, string_p, bidi_it->frame_window_p,
1848 &ch_len, &nchars, true);
1849 if (typ1 != STRONG_R && typ1 != STRONG_AL)
1851 type = LRI;
1852 goto fsi_as_lri;
1854 else
1855 type = RLI;
1856 /* FALLTHROUGH */
1857 case RLI: /* X5a */
1858 if (override == NEUTRAL_DIR)
1859 bidi_it->type_after_w1 = type;
1860 else /* Unicode 8.0 correction. */
1861 bidi_it->type_after_w1 = (override == L2R ? STRONG_L : STRONG_R);
1862 bidi_check_type (bidi_it->type_after_w1);
1863 if (current_level < BIDI_MAXDEPTH
1864 && bidi_it->invalid_levels == 0
1865 && bidi_it->invalid_isolates == 0)
1867 new_level = ((current_level + 1) & ~1) + 1;
1868 bidi_it->isolate_level++;
1869 bidi_push_embedding_level (bidi_it, new_level, NEUTRAL_DIR, true);
1871 else
1872 bidi_it->invalid_isolates++;
1873 break;
1874 case LRI: /* X5b */
1875 fsi_as_lri:
1876 if (override == NEUTRAL_DIR)
1877 bidi_it->type_after_w1 = type;
1878 else /* Unicode 8.0 correction. */
1879 bidi_it->type_after_w1 = (override == L2R ? STRONG_L : STRONG_R);
1880 bidi_check_type (bidi_it->type_after_w1);
1881 if (current_level < BIDI_MAXDEPTH - 1
1882 && bidi_it->invalid_levels == 0
1883 && bidi_it->invalid_isolates == 0)
1885 new_level = ((current_level + 2) & ~1);
1886 bidi_it->isolate_level++;
1887 bidi_push_embedding_level (bidi_it, new_level, NEUTRAL_DIR, true);
1889 else
1890 bidi_it->invalid_isolates++;
1891 break;
1892 case PDI: /* X6a */
1893 if (bidi_it->invalid_isolates)
1895 bidi_it->invalid_isolates--;
1896 new_level = current_level;
1898 else if (bidi_it->isolate_level > 0)
1900 bidi_it->invalid_levels = 0;
1901 while (!bidi_it->level_stack[bidi_it->stack_idx].isolate_status)
1902 bidi_pop_embedding_level (bidi_it);
1903 eassert (bidi_it->stack_idx > 0);
1904 new_level = bidi_pop_embedding_level (bidi_it);
1905 bidi_it->isolate_level--;
1907 bidi_it->resolved_level = new_level;
1908 /* Unicode 8.0 correction. */
1909 if (bidi_it->level_stack[bidi_it->stack_idx].override == L2R)
1910 bidi_it->type_after_w1 = STRONG_L;
1911 else if (bidi_it->level_stack[bidi_it->stack_idx].override == R2L)
1912 bidi_it->type_after_w1 = STRONG_R;
1913 else
1914 bidi_it->type_after_w1 = type;
1915 break;
1916 case PDF: /* X7 */
1917 bidi_it->type_after_w1 = type;
1918 bidi_check_type (bidi_it->type_after_w1);
1919 type = WEAK_BN; /* X9/Retaining */
1920 if (bidi_it->ignore_bn_limit <= -1)
1922 if (!bidi_it->invalid_isolates)
1924 if (bidi_it->invalid_levels)
1925 bidi_it->invalid_levels--;
1926 else if (!isolate_status && bidi_it->stack_idx > 1)
1927 bidi_pop_embedding_level (bidi_it);
1930 else if (bidi_it->prev.type_after_w1 == WEAK_EN /* W5/Retaining */
1931 || (bidi_it->next_en_pos > bidi_it->charpos
1932 && bidi_it->next_en_type == WEAK_EN))
1933 type = WEAK_EN;
1934 break;
1935 default:
1936 /* Nothing. */
1937 break;
1940 bidi_it->type = type;
1941 bidi_check_type (bidi_it->type);
1943 eassert (bidi_it->resolved_level >= 0);
1944 return bidi_it->resolved_level;
1947 /* Given an iterator state in BIDI_IT, advance one character position
1948 in the buffer/string to the next character (in the logical order),
1949 resolve any explicit embeddings and directional overrides, and
1950 return the embedding level of the character after resolving
1951 explicit directives and ignoring empty embeddings. */
1952 static int
1953 bidi_resolve_explicit (struct bidi_it *bidi_it)
1955 int prev_level = bidi_it->level_stack[bidi_it->stack_idx].level;
1956 int new_level = bidi_resolve_explicit_1 (bidi_it);
1957 ptrdiff_t eob = bidi_it->string.s ? bidi_it->string.schars : ZV;
1958 const unsigned char *s
1959 = (STRINGP (bidi_it->string.lstring)
1960 ? SDATA (bidi_it->string.lstring)
1961 : bidi_it->string.s);
1963 eassert (prev_level >= 0);
1964 if (prev_level < new_level
1965 && bidi_it->type == WEAK_BN
1966 && bidi_it->ignore_bn_limit == -1 /* only if not already known */
1967 && bidi_it->charpos < eob /* not already at EOB */
1968 && bidi_explicit_dir_char (bidi_char_at_pos (bidi_it->bytepos
1969 + bidi_it->ch_len, s,
1970 bidi_it->string.unibyte)))
1972 /* Avoid pushing and popping embedding levels if the level run
1973 is empty, as this breaks level runs where it shouldn't.
1974 UAX#9 removes all the explicit embedding and override codes,
1975 so empty embeddings disappear without a trace. We need to
1976 behave as if we did the same. */
1977 struct bidi_it saved_it;
1978 int level = prev_level;
1980 bidi_copy_it (&saved_it, bidi_it);
1982 while (bidi_explicit_dir_char (bidi_char_at_pos (bidi_it->bytepos
1983 + bidi_it->ch_len, s,
1984 bidi_it->string.unibyte)))
1986 /* This advances to the next character, skipping any
1987 characters covered by display strings. */
1988 level = bidi_resolve_explicit_1 (bidi_it);
1989 /* If string.lstring was relocated inside bidi_resolve_explicit_1,
1990 a pointer to its data is no longer valid. */
1991 if (STRINGP (bidi_it->string.lstring))
1992 s = SDATA (bidi_it->string.lstring);
1995 if (bidi_it->nchars <= 0)
1996 emacs_abort ();
1997 if (level == prev_level) /* empty embedding */
1998 saved_it.ignore_bn_limit = bidi_it->charpos + bidi_it->nchars;
1999 else /* this embedding is non-empty */
2000 saved_it.ignore_bn_limit = -2;
2002 bidi_copy_it (bidi_it, &saved_it);
2003 if (bidi_it->ignore_bn_limit > -1)
2005 /* We pushed a level, but we shouldn't have. Undo that. */
2006 if (!bidi_it->invalid_levels)
2007 new_level = bidi_pop_embedding_level (bidi_it);
2008 else
2009 bidi_it->invalid_levels--;
2013 if (bidi_it->type == NEUTRAL_B) /* X8 */
2015 bidi_set_paragraph_end (bidi_it);
2016 /* This is needed by bidi_resolve_weak below, and in L1. */
2017 bidi_it->type_after_w1 = bidi_it->type;
2018 bidi_check_type (bidi_it->type_after_w1);
2021 return new_level;
2024 static bool
2025 bidi_isolate_fmt_char (bidi_type_t ch_type)
2027 return (ch_type == LRI || ch_type == RLI || ch_type == PDI);
2030 /* Advance in the buffer/string, resolve weak types and return the
2031 type of the next character after weak type resolution. */
2032 static bidi_type_t
2033 bidi_resolve_weak (struct bidi_it *bidi_it)
2035 bidi_type_t type;
2036 bidi_dir_t override;
2037 int prev_level = bidi_it->level_stack[bidi_it->stack_idx].level;
2038 int new_level = bidi_resolve_explicit (bidi_it);
2039 int next_char;
2040 bidi_type_t type_of_next;
2041 struct bidi_it saved_it;
2042 ptrdiff_t eob
2043 = ((STRINGP (bidi_it->string.lstring) || bidi_it->string.s)
2044 ? bidi_it->string.schars : ZV);
2046 type = bidi_it->type;
2047 override = bidi_it->level_stack[bidi_it->stack_idx].override;
2049 eassert (!(type == UNKNOWN_BT
2050 || type == LRE
2051 || type == LRO
2052 || type == RLE
2053 || type == RLO
2054 || type == PDF));
2056 eassert (prev_level >= 0);
2057 if (new_level > prev_level
2058 /* When the embedding level goes down, we only need to compute
2059 the type of sos if this level is not an isolate, because the
2060 sos type of the isolating sequence was already computed and
2061 saved on the stack. */
2062 || (new_level < prev_level
2063 && !bidi_it->level_stack[bidi_it->stack_idx].isolate_status)
2064 || bidi_it->type == NEUTRAL_B)
2066 /* We've got a new isolating sequence, compute the directional
2067 type of sos and initialize per-run variables (UAX#9, clause
2068 X10). */
2069 bidi_set_sos_type (bidi_it, prev_level, new_level);
2071 else if (type == NEUTRAL_S || type == NEUTRAL_WS
2072 || type == WEAK_BN || type == STRONG_AL)
2073 bidi_it->type_after_w1 = type; /* needed in L1 */
2074 bidi_check_type (bidi_it->type_after_w1);
2076 /* Level and directional override status are already recorded in
2077 bidi_it, and do not need any change; see X6. */
2078 if (override == R2L) /* X6 */
2079 type = STRONG_R;
2080 else if (override == L2R)
2081 type = STRONG_L;
2082 else
2084 if (type == WEAK_NSM) /* W1 */
2086 /* Note that we don't need to consider the case where the
2087 prev character has its type overridden by an RLO or LRO,
2088 because then either the type of this NSM would have been
2089 also overridden, or the previous character is outside the
2090 current level run, and thus not relevant to this NSM.
2091 This is why NSM gets the type_after_w1 of the previous
2092 character. */
2093 if (bidi_it->prev.type_after_w1 != UNKNOWN_BT
2094 /* if type_after_w1 is NEUTRAL_B, this NSM is at sos */
2095 && bidi_it->prev.type_after_w1 != NEUTRAL_B)
2097 if (bidi_isolate_fmt_char (bidi_it->prev.type_after_w1))
2098 type = NEUTRAL_ON;
2099 else
2100 type = bidi_it->prev.type_after_w1;
2102 else if (bidi_it->sos == R2L)
2103 type = STRONG_R;
2104 else if (bidi_it->sos == L2R)
2105 type = STRONG_L;
2106 else /* shouldn't happen! */
2107 emacs_abort ();
2109 if (type == WEAK_EN /* W2 */
2110 && bidi_it->last_strong.type_after_w1 == STRONG_AL)
2111 type = WEAK_AN;
2112 else if (type == STRONG_AL) /* W3 */
2113 type = STRONG_R;
2114 else if ((type == WEAK_ES /* W4 */
2115 && bidi_it->prev.type_after_w1 == WEAK_EN
2116 && bidi_it->prev.orig_type == WEAK_EN)
2117 || (type == WEAK_CS
2118 && ((bidi_it->prev.type_after_w1 == WEAK_EN
2119 && bidi_it->prev.orig_type == WEAK_EN)
2120 || bidi_it->prev.type_after_w1 == WEAK_AN)))
2122 const unsigned char *s
2123 = (STRINGP (bidi_it->string.lstring)
2124 ? SDATA (bidi_it->string.lstring)
2125 : bidi_it->string.s);
2127 next_char = (bidi_it->charpos + bidi_it->nchars >= eob
2128 ? BIDI_EOB
2129 : bidi_char_at_pos (bidi_it->bytepos + bidi_it->ch_len,
2130 s, bidi_it->string.unibyte));
2131 type_of_next = bidi_get_type (next_char, override);
2133 if (type_of_next == WEAK_BN
2134 || bidi_explicit_dir_char (next_char))
2136 bidi_copy_it (&saved_it, bidi_it);
2137 while (bidi_resolve_explicit (bidi_it) == new_level
2138 && bidi_it->type == WEAK_BN)
2140 type_of_next = bidi_it->type;
2141 bidi_copy_it (bidi_it, &saved_it);
2144 /* If the next character is EN, but the last strong-type
2145 character is AL, that next EN will be changed to AN when
2146 we process it in W2 above. So in that case, this ES
2147 should not be changed into EN. */
2148 if (type == WEAK_ES
2149 && type_of_next == WEAK_EN
2150 && bidi_it->last_strong.type_after_w1 != STRONG_AL)
2151 type = WEAK_EN;
2152 else if (type == WEAK_CS)
2154 if (bidi_it->prev.type_after_w1 == WEAK_AN
2155 && (type_of_next == WEAK_AN
2156 /* If the next character is EN, but the last
2157 strong-type character is AL, EN will be later
2158 changed to AN when we process it in W2 above.
2159 So in that case, this ES should not be
2160 changed into EN. */
2161 || (type_of_next == WEAK_EN
2162 && bidi_it->last_strong.type_after_w1 == STRONG_AL)))
2163 type = WEAK_AN;
2164 else if (bidi_it->prev.type_after_w1 == WEAK_EN
2165 && type_of_next == WEAK_EN
2166 && bidi_it->last_strong.type_after_w1 != STRONG_AL)
2167 type = WEAK_EN;
2170 else if (type == WEAK_ET /* W5: ET with EN before or after it */
2171 || type == WEAK_BN) /* W5/Retaining */
2173 if (bidi_it->prev.type_after_w1 == WEAK_EN) /* ET/BN w/EN before it */
2174 type = WEAK_EN;
2175 else if (bidi_it->next_en_pos > bidi_it->charpos
2176 && bidi_it->next_en_type != WEAK_BN)
2178 if (bidi_it->next_en_type == WEAK_EN) /* ET/BN with EN after it */
2179 type = WEAK_EN;
2181 else if (bidi_it->next_en_pos >=0)
2183 ptrdiff_t en_pos = bidi_it->charpos + bidi_it->nchars;
2184 const unsigned char *s = (STRINGP (bidi_it->string.lstring)
2185 ? SDATA (bidi_it->string.lstring)
2186 : bidi_it->string.s);
2188 if (bidi_it->nchars <= 0)
2189 emacs_abort ();
2190 next_char
2191 = (bidi_it->charpos + bidi_it->nchars >= eob
2192 ? BIDI_EOB
2193 : bidi_char_at_pos (bidi_it->bytepos + bidi_it->ch_len, s,
2194 bidi_it->string.unibyte));
2195 type_of_next = bidi_get_type (next_char, override);
2197 if (type_of_next == WEAK_ET
2198 || type_of_next == WEAK_BN
2199 || bidi_explicit_dir_char (next_char))
2201 bidi_copy_it (&saved_it, bidi_it);
2202 while (bidi_resolve_explicit (bidi_it) == new_level
2203 && (bidi_it->type == WEAK_BN
2204 || bidi_it->type == WEAK_ET))
2206 type_of_next = bidi_it->type;
2207 en_pos = bidi_it->charpos;
2208 bidi_copy_it (bidi_it, &saved_it);
2210 /* Remember this position, to speed up processing of the
2211 next ETs. */
2212 bidi_it->next_en_pos = en_pos;
2213 if (type_of_next == WEAK_EN)
2215 /* If the last strong character is AL, the EN we've
2216 found will become AN when we get to it (W2). */
2217 if (bidi_it->last_strong.type_after_w1 == STRONG_AL)
2218 type_of_next = WEAK_AN;
2219 else if (type == WEAK_BN)
2220 type = NEUTRAL_ON; /* W6/Retaining */
2221 else
2222 type = WEAK_EN;
2224 else if (type_of_next == NEUTRAL_B)
2225 /* Record the fact that there are no more ENs from
2226 here to the end of paragraph, to avoid entering the
2227 loop above ever again in this paragraph. */
2228 bidi_it->next_en_pos = -1;
2229 /* Record the type of the character where we ended our search. */
2230 bidi_it->next_en_type = type_of_next;
2235 if (type == WEAK_ES || type == WEAK_ET || type == WEAK_CS /* W6 */
2236 || (type == WEAK_BN
2237 && (bidi_it->prev.type_after_w1 == WEAK_CS /* W6/Retaining */
2238 || bidi_it->prev.type_after_w1 == WEAK_ES
2239 || bidi_it->prev.type_after_w1 == WEAK_ET)))
2240 type = NEUTRAL_ON;
2242 /* Store the type we've got so far, before we clobber it with strong
2243 types in W7 and while resolving neutral types. But leave alone
2244 the original types that were recorded above, because we will need
2245 them for the L1 clause. */
2246 if (bidi_it->type_after_w1 == UNKNOWN_BT)
2247 bidi_it->type_after_w1 = type;
2248 bidi_check_type (bidi_it->type_after_w1);
2250 if (type == WEAK_EN) /* W7 */
2252 if ((bidi_it->last_strong.type_after_w1 == STRONG_L)
2253 || (bidi_it->last_strong.type == UNKNOWN_BT && bidi_it->sos == L2R))
2254 type = STRONG_L;
2257 bidi_it->type = type;
2258 bidi_check_type (bidi_it->type);
2259 return type;
2262 /* Resolve the type of a neutral character according to the type of
2263 surrounding strong text and the current embedding level. */
2264 static bidi_type_t
2265 bidi_resolve_neutral_1 (bidi_type_t prev_type, bidi_type_t next_type, int lev)
2267 /* N1: European and Arabic numbers are treated as though they were R. */
2268 if (next_type == WEAK_EN || next_type == WEAK_AN)
2269 next_type = STRONG_R;
2270 if (prev_type == WEAK_EN || prev_type == WEAK_AN)
2271 prev_type = STRONG_R;
2273 if (next_type == prev_type) /* N1 */
2274 return next_type;
2275 else if ((lev & 1) == 0) /* N2 */
2276 return STRONG_L;
2277 else
2278 return STRONG_R;
2281 static bidi_type_t
2282 bidi_resolve_neutral (struct bidi_it *bidi_it)
2284 int prev_level = bidi_it->level_stack[bidi_it->stack_idx].level;
2285 bidi_type_t type = bidi_resolve_weak (bidi_it);
2286 int current_level = bidi_it->level_stack[bidi_it->stack_idx].level;
2288 eassert ((type == STRONG_R
2289 || type == STRONG_L
2290 || type == WEAK_BN
2291 || type == WEAK_EN
2292 || type == WEAK_AN
2293 || type == NEUTRAL_B
2294 || type == NEUTRAL_S
2295 || type == NEUTRAL_WS
2296 || type == NEUTRAL_ON));
2298 eassert (prev_level >= 0);
2299 eassert (current_level >= 0);
2300 if ((type != NEUTRAL_B /* Don't risk entering the long loop below if
2301 we are already at paragraph end. */
2302 && bidi_get_category (type) == NEUTRAL)
2303 || (type == WEAK_BN && prev_level == current_level))
2305 if (bidi_it->next_for_neutral.type != UNKNOWN_BT)
2306 type = bidi_resolve_neutral_1 (bidi_it->prev_for_neutral.type,
2307 bidi_it->next_for_neutral.type,
2308 current_level);
2309 /* The next two "else if" clauses are shortcuts for the
2310 important special case when we have a long sequence of
2311 neutral or WEAK_BN characters, such as whitespace or nulls or
2312 other control characters, on the base embedding level of the
2313 paragraph, and that sequence goes all the way to the end of
2314 the paragraph and follows a character whose resolved
2315 directionality is identical to the base embedding level.
2316 (This is what happens in a buffer with plain L2R text that
2317 happens to include long sequences of control characters.) By
2318 virtue of N1, the result of examining this long sequence will
2319 always be either STRONG_L or STRONG_R, depending on the base
2320 embedding level. So we use this fact directly instead of
2321 entering the expensive loop in the "else" clause. */
2322 else if (current_level == 0
2323 && bidi_it->prev_for_neutral.type == STRONG_L
2324 && !bidi_explicit_dir_char (bidi_it->ch))
2325 type = bidi_resolve_neutral_1 (bidi_it->prev_for_neutral.type,
2326 STRONG_L, current_level);
2327 else if (/* current level is 1 */
2328 current_level == 1
2329 /* base embedding level is also 1 */
2330 && bidi_it->level_stack[0].level == 1
2331 /* previous character is one of those considered R for
2332 the purposes of W5 */
2333 && (bidi_it->prev_for_neutral.type == STRONG_R
2334 || bidi_it->prev_for_neutral.type == WEAK_EN
2335 || bidi_it->prev_for_neutral.type == WEAK_AN)
2336 && !bidi_explicit_dir_char (bidi_it->ch))
2337 type = bidi_resolve_neutral_1 (bidi_it->prev_for_neutral.type,
2338 STRONG_R, current_level);
2339 else
2341 /* Arrrgh!! The UAX#9 algorithm is too deeply entrenched in
2342 the assumption of batch-style processing; see clauses W4,
2343 W5, and especially N1, which require to look far forward
2344 (as well as back) in the buffer/string. May the fleas of
2345 a thousand camels infest the armpits of those who design
2346 supposedly general-purpose algorithms by looking at their
2347 own implementations, and fail to consider other possible
2348 implementations! */
2349 struct bidi_it saved_it;
2350 bidi_type_t next_type;
2352 if (bidi_it->scan_dir == -1)
2353 emacs_abort ();
2355 bidi_copy_it (&saved_it, bidi_it);
2356 /* Scan the text forward until we find the first non-neutral
2357 character, and then use that to resolve the neutral we
2358 are dealing with now. We also cache the scanned iterator
2359 states, to salvage some of the effort later. */
2360 bidi_cache_iterator_state (bidi_it, 0);
2361 do {
2362 /* Record the info about the previous character, so that
2363 it will be cached below with this state. */
2364 if (bidi_it->type_after_w1 != WEAK_BN /* W1/Retaining */
2365 && bidi_it->type != WEAK_BN)
2366 bidi_remember_char (&bidi_it->prev, bidi_it);
2367 type = bidi_resolve_weak (bidi_it);
2368 /* Paragraph separators have their levels fully resolved
2369 at this point, so cache them as resolved. */
2370 bidi_cache_iterator_state (bidi_it, type == NEUTRAL_B);
2371 /* FIXME: implement L1 here, by testing for a newline and
2372 resetting the level for any sequence of whitespace
2373 characters adjacent to it. */
2374 } while (!(type == NEUTRAL_B
2375 || (type != WEAK_BN
2376 && bidi_get_category (type) != NEUTRAL)
2377 /* This is all per level run, so stop when we
2378 reach the end of this level run. */
2379 || (bidi_it->level_stack[bidi_it->stack_idx].level
2380 != current_level)));
2382 bidi_remember_char (&saved_it.next_for_neutral, bidi_it);
2384 switch (type)
2386 case STRONG_L:
2387 case STRONG_R:
2388 case STRONG_AL:
2389 /* Actually, STRONG_AL cannot happen here, because
2390 bidi_resolve_weak converts it to STRONG_R, per W3. */
2391 eassert (type != STRONG_AL);
2392 next_type = type;
2393 break;
2394 case WEAK_EN:
2395 case WEAK_AN:
2396 /* N1: ``European and Arabic numbers are treated as
2397 though they were R.'' */
2398 next_type = STRONG_R;
2399 break;
2400 case WEAK_BN:
2401 case NEUTRAL_ON: /* W6/Retaining */
2402 if (!bidi_explicit_dir_char (bidi_it->ch))
2403 emacs_abort (); /* can't happen: BNs are skipped */
2404 /* FALLTHROUGH */
2405 case NEUTRAL_B:
2406 /* Marched all the way to the end of this level run.
2407 We need to use the eos type, whose information is
2408 stored by bidi_set_sos_type in the prev_for_neutral
2409 member. */
2410 if (saved_it.type != WEAK_BN
2411 || bidi_get_category (bidi_it->prev.type_after_w1) == NEUTRAL)
2412 next_type = bidi_it->prev_for_neutral.type;
2413 else
2415 /* This is a BN which does not adjoin neutrals.
2416 Leave its type alone. */
2417 bidi_copy_it (bidi_it, &saved_it);
2418 return bidi_it->type;
2420 break;
2421 default:
2422 emacs_abort ();
2424 type = bidi_resolve_neutral_1 (saved_it.prev_for_neutral.type,
2425 next_type, current_level);
2426 saved_it.next_for_neutral.type = next_type;
2427 saved_it.type = type;
2428 bidi_check_type (next_type);
2429 bidi_check_type (type);
2430 bidi_copy_it (bidi_it, &saved_it);
2433 return type;
2436 /* Given an iterator state in BIDI_IT, advance one character position
2437 in the buffer/string to the next character (in the logical order),
2438 resolve the bidi type of that next character, and return that
2439 type. */
2440 static bidi_type_t
2441 bidi_type_of_next_char (struct bidi_it *bidi_it)
2443 bidi_type_t type;
2445 /* This should always be called during a forward scan. */
2446 if (bidi_it->scan_dir != 1)
2447 emacs_abort ();
2449 /* Reset the limit until which to ignore BNs if we step out of the
2450 area where we found only empty levels. */
2451 if ((bidi_it->ignore_bn_limit > -1
2452 && bidi_it->ignore_bn_limit <= bidi_it->charpos)
2453 || (bidi_it->ignore_bn_limit == -2
2454 && !bidi_explicit_dir_char (bidi_it->ch)))
2455 bidi_it->ignore_bn_limit = -1;
2457 type = bidi_resolve_neutral (bidi_it);
2459 return type;
2462 /* Given an iterator state BIDI_IT, advance one character position in
2463 the buffer/string to the next character (in the current scan
2464 direction), resolve the embedding and implicit levels of that next
2465 character, and return the resulting level. */
2466 static int
2467 bidi_level_of_next_char (struct bidi_it *bidi_it)
2469 bidi_type_t type;
2470 int level, prev_level = -1;
2471 struct bidi_saved_info next_for_neutral;
2472 ptrdiff_t next_char_pos = -2;
2474 if (bidi_it->scan_dir == 1)
2476 ptrdiff_t eob
2477 = ((bidi_it->string.s || STRINGP (bidi_it->string.lstring))
2478 ? bidi_it->string.schars : ZV);
2480 /* There's no sense in trying to advance if we hit end of text. */
2481 if (bidi_it->charpos >= eob)
2483 eassert (bidi_it->resolved_level >= 0);
2484 return bidi_it->resolved_level;
2487 /* Record the info about the previous character. */
2488 if (bidi_it->type_after_w1 != WEAK_BN /* W1/Retaining */
2489 && bidi_it->type != WEAK_BN)
2490 bidi_remember_char (&bidi_it->prev, bidi_it);
2491 if (bidi_it->type_after_w1 == STRONG_R
2492 || bidi_it->type_after_w1 == STRONG_L
2493 || bidi_it->type_after_w1 == STRONG_AL)
2494 bidi_remember_char (&bidi_it->last_strong, bidi_it);
2495 /* FIXME: it sounds like we don't need both prev and
2496 prev_for_neutral members, but I'm leaving them both for now. */
2497 if (bidi_it->type == STRONG_R || bidi_it->type == STRONG_L
2498 || bidi_it->type == WEAK_EN || bidi_it->type == WEAK_AN)
2499 bidi_remember_char (&bidi_it->prev_for_neutral, bidi_it);
2501 /* If we overstepped the characters used for resolving neutrals
2502 and whitespace, invalidate their info in the iterator. */
2503 if (bidi_it->charpos >= bidi_it->next_for_neutral.charpos)
2504 bidi_it->next_for_neutral.type = UNKNOWN_BT;
2505 if (bidi_it->next_en_pos >= 0
2506 && bidi_it->charpos >= bidi_it->next_en_pos)
2508 bidi_it->next_en_pos = 0;
2509 bidi_it->next_en_type = UNKNOWN_BT;
2511 if (bidi_it->next_for_ws.type != UNKNOWN_BT
2512 && bidi_it->charpos >= bidi_it->next_for_ws.charpos)
2513 bidi_it->next_for_ws.type = UNKNOWN_BT;
2515 /* This must be taken before we fill the iterator with the info
2516 about the next char. If we scan backwards, the iterator
2517 state must be already cached, so there's no need to know the
2518 embedding level of the previous character, since we will be
2519 returning to our caller shortly. */
2520 prev_level = bidi_it->level_stack[bidi_it->stack_idx].level;
2521 eassert (prev_level >= 0);
2523 next_for_neutral = bidi_it->next_for_neutral;
2525 /* Perhaps the character we want is already cached. If it is, the
2526 call to bidi_cache_find below will return a type other than
2527 UNKNOWN_BT. */
2528 if (bidi_cache_idx > bidi_cache_start && !bidi_it->first_elt)
2530 int bob = ((bidi_it->string.s || STRINGP (bidi_it->string.lstring))
2531 ? 0 : 1);
2532 if (bidi_it->scan_dir > 0)
2534 if (bidi_it->nchars <= 0)
2535 emacs_abort ();
2536 next_char_pos = bidi_it->charpos + bidi_it->nchars;
2538 else if (bidi_it->charpos >= bob)
2539 /* Implementation note: we allow next_char_pos to be as low as
2540 0 for buffers or -1 for strings, and that is okay because
2541 that's the "position" of the sentinel iterator state we
2542 cached at the beginning of the iteration. */
2543 next_char_pos = bidi_it->charpos - 1;
2544 if (next_char_pos >= bob - 1)
2545 type = bidi_cache_find (next_char_pos, -1, bidi_it);
2546 else
2547 type = UNKNOWN_BT;
2549 else
2550 type = UNKNOWN_BT;
2551 if (type != UNKNOWN_BT)
2553 /* Don't lose the information for resolving neutrals! The
2554 cached states could have been cached before their
2555 next_for_neutral member was computed. If we are on our way
2556 forward, we can simply take the info from the previous
2557 state. */
2558 if (bidi_it->scan_dir == 1
2559 && bidi_it->next_for_neutral.type == UNKNOWN_BT)
2560 bidi_it->next_for_neutral = next_for_neutral;
2562 /* If resolved_level is -1, it means this state was cached
2563 before it was completely resolved, so we cannot return
2564 it. */
2565 if (bidi_it->resolved_level != -1)
2567 eassert (bidi_it->resolved_level >= 0);
2568 return bidi_it->resolved_level;
2571 if (bidi_it->scan_dir == -1)
2572 /* If we are going backwards, the iterator state is already cached
2573 from previous scans, and should be fully resolved. */
2574 emacs_abort ();
2576 if (type == UNKNOWN_BT)
2577 type = bidi_type_of_next_char (bidi_it);
2579 if (type == NEUTRAL_B)
2581 eassert (bidi_it->resolved_level >= 0);
2582 return bidi_it->resolved_level;
2585 level = bidi_it->level_stack[bidi_it->stack_idx].level;
2586 if ((bidi_get_category (type) == NEUTRAL /* && type != NEUTRAL_B */)
2587 || (type == WEAK_BN && prev_level == level))
2589 if (bidi_it->next_for_neutral.type == UNKNOWN_BT)
2590 emacs_abort ();
2592 /* If the cached state shows a neutral character, it was not
2593 resolved by bidi_resolve_neutral, so do it now. */
2594 type = bidi_resolve_neutral_1 (bidi_it->prev_for_neutral.type,
2595 bidi_it->next_for_neutral.type,
2596 level);
2599 eassert ((type == STRONG_R
2600 || type == STRONG_L
2601 || type == WEAK_BN
2602 || type == WEAK_EN
2603 || type == WEAK_AN));
2604 bidi_it->type = type;
2605 bidi_check_type (bidi_it->type);
2607 /* For L1 below, we need to know, for each WS character, whether
2608 it belongs to a sequence of WS characters preceding a newline
2609 or a TAB or a paragraph separator. */
2610 if (bidi_it->orig_type == NEUTRAL_WS
2611 && bidi_it->next_for_ws.type == UNKNOWN_BT)
2613 int ch;
2614 ptrdiff_t clen = bidi_it->ch_len;
2615 ptrdiff_t bpos = bidi_it->bytepos;
2616 ptrdiff_t cpos = bidi_it->charpos;
2617 ptrdiff_t disp_pos = bidi_it->disp_pos;
2618 ptrdiff_t nc = bidi_it->nchars;
2619 struct bidi_string_data bs = bidi_it->string;
2620 bidi_type_t chtype;
2621 bool fwp = bidi_it->frame_window_p;
2622 int dpp = bidi_it->disp_prop;
2624 if (bidi_it->nchars <= 0)
2625 emacs_abort ();
2626 do {
2627 ch = bidi_fetch_char (cpos += nc, bpos += clen, &disp_pos, &dpp, &bs,
2628 bidi_it->w, fwp, &clen, &nc);
2629 chtype = bidi_get_type (ch, NEUTRAL_DIR);
2630 } while (chtype == NEUTRAL_WS || chtype == WEAK_BN
2631 || bidi_explicit_dir_char (ch)); /* L1/Retaining */
2632 bidi_it->next_for_ws.type = chtype;
2633 bidi_check_type (bidi_it->next_for_ws.type);
2634 bidi_it->next_for_ws.charpos = cpos;
2635 bidi_it->next_for_ws.bytepos = bpos;
2638 /* Resolve implicit levels, with a twist: PDFs get the embedding
2639 level of the embedding they terminate. See below for the
2640 reason. */
2641 if (bidi_it->orig_type == PDF
2642 /* Don't do this if this formatting code didn't change the
2643 embedding level due to invalid or empty embeddings. */
2644 && prev_level != level)
2646 /* Don't look in UAX#9 for the reason for this: it's our own
2647 private quirk. The reason is that we want the formatting
2648 codes to be delivered so that they bracket the text of their
2649 embedding. For example, given the text
2651 {RLO}teST{PDF}
2653 we want it to be displayed as
2655 {PDF}STet{RLO}
2657 not as
2659 STet{RLO}{PDF}
2661 which will result because we bump up the embedding level as
2662 soon as we see the RLO and pop it as soon as we see the PDF,
2663 so RLO itself has the same embedding level as "teST", and
2664 thus would be normally delivered last, just before the PDF.
2665 The switch below fiddles with the level of PDF so that this
2666 ugly side effect does not happen.
2668 (This is, of course, only important if the formatting codes
2669 are actually displayed, but Emacs does need to display them
2670 if the user wants to.) */
2671 level = prev_level;
2673 else if (bidi_it->orig_type == NEUTRAL_B /* L1 */
2674 || bidi_it->orig_type == NEUTRAL_S
2675 || bidi_it->ch == '\n' || bidi_it->ch == BIDI_EOB
2676 || (bidi_it->orig_type == NEUTRAL_WS
2677 && (bidi_it->next_for_ws.type == NEUTRAL_B
2678 || bidi_it->next_for_ws.type == NEUTRAL_S)))
2679 level = bidi_it->level_stack[0].level;
2680 else if ((level & 1) == 0) /* I1 */
2682 if (type == STRONG_R)
2683 level++;
2684 else if (type == WEAK_EN || type == WEAK_AN)
2685 level += 2;
2687 else /* I2 */
2689 if (type == STRONG_L || type == WEAK_EN || type == WEAK_AN)
2690 level++;
2693 /* FIXME: Exempt explicit directional characters from the assignment
2694 below, and remove the PDF hack above. */
2695 bidi_it->resolved_level = level;
2696 return level;
2699 /* Move to the other edge of a level given by LEVEL. If END_FLAG,
2700 we are at the end of a level, and we need to prepare to
2701 resume the scan of the lower level.
2703 If this level's other edge is cached, we simply jump to it, filling
2704 the iterator structure with the iterator state on the other edge.
2705 Otherwise, we walk the buffer or string until we come back to the
2706 same level as LEVEL.
2708 Note: we are not talking here about a ``level run'' in the UAX#9
2709 sense of the term, but rather about a ``level'' which includes
2710 all the levels higher than it. In other words, given the levels
2711 like this:
2713 11111112222222333333334443343222222111111112223322111
2714 A B C
2716 and assuming we are at point A scanning left to right, this
2717 function moves to point C, whereas the UAX#9 ``level 2 run'' ends
2718 at point B. */
2719 static void
2720 bidi_find_other_level_edge (struct bidi_it *bidi_it, int level, bool end_flag)
2722 int dir = end_flag ? -bidi_it->scan_dir : bidi_it->scan_dir;
2723 ptrdiff_t idx;
2725 /* Try the cache first. */
2726 if ((idx = bidi_cache_find_level_change (level, dir, end_flag))
2727 >= bidi_cache_start)
2728 bidi_cache_fetch_state (idx, bidi_it);
2729 else
2731 int new_level;
2733 /* If we are at end of level, its edges must be cached. */
2734 if (end_flag)
2735 emacs_abort ();
2737 bidi_cache_iterator_state (bidi_it, 1);
2738 do {
2739 new_level = bidi_level_of_next_char (bidi_it);
2740 bidi_cache_iterator_state (bidi_it, 1);
2741 } while (new_level >= level);
2745 void
2746 bidi_move_to_visually_next (struct bidi_it *bidi_it)
2748 int old_level, new_level, next_level;
2749 struct bidi_it sentinel;
2750 struct gcpro gcpro1;
2752 if (bidi_it->charpos < 0 || bidi_it->bytepos < 0)
2753 emacs_abort ();
2755 if (bidi_it->scan_dir == 0)
2757 bidi_it->scan_dir = 1; /* default to logical order */
2760 /* The code below can call eval, and thus cause GC. If we are
2761 iterating a Lisp string, make sure it won't be GCed. */
2762 if (STRINGP (bidi_it->string.lstring))
2763 GCPRO1 (bidi_it->string.lstring);
2765 /* If we just passed a newline, initialize for the next line. */
2766 if (!bidi_it->first_elt
2767 && (bidi_it->ch == '\n' || bidi_it->ch == BIDI_EOB))
2768 bidi_line_init (bidi_it);
2770 /* Prepare the sentinel iterator state, and cache it. When we bump
2771 into it, scanning backwards, we'll know that the last non-base
2772 level is exhausted. */
2773 if (bidi_cache_idx == bidi_cache_start)
2775 bidi_copy_it (&sentinel, bidi_it);
2776 if (bidi_it->first_elt)
2778 sentinel.charpos--; /* cached charpos needs to be monotonic */
2779 sentinel.bytepos--;
2780 sentinel.ch = '\n'; /* doesn't matter, but why not? */
2781 sentinel.ch_len = 1;
2782 sentinel.nchars = 1;
2784 bidi_cache_iterator_state (&sentinel, 1);
2787 old_level = bidi_it->resolved_level;
2788 new_level = bidi_level_of_next_char (bidi_it);
2790 /* Reordering of resolved levels (clause L2) is implemented by
2791 jumping to the other edge of the level and flipping direction of
2792 scanning the text whenever we find a level change. */
2793 if (new_level != old_level)
2795 bool ascending = new_level > old_level;
2796 int level_to_search = ascending ? old_level + 1 : old_level;
2797 int incr = ascending ? 1 : -1;
2798 int expected_next_level = old_level + incr;
2800 /* Jump (or walk) to the other edge of this level. */
2801 bidi_find_other_level_edge (bidi_it, level_to_search, !ascending);
2802 /* Switch scan direction and peek at the next character in the
2803 new direction. */
2804 bidi_it->scan_dir = -bidi_it->scan_dir;
2806 /* The following loop handles the case where the resolved level
2807 jumps by more than one. This is typical for numbers inside a
2808 run of text with left-to-right embedding direction, but can
2809 also happen in other situations. In those cases the decision
2810 where to continue after a level change, and in what direction,
2811 is tricky. For example, given a text like below:
2813 abcdefgh
2814 11336622
2816 (where the numbers below the text show the resolved levels),
2817 the result of reordering according to UAX#9 should be this:
2819 efdcghba
2821 This is implemented by the loop below which flips direction
2822 and jumps to the other edge of the level each time it finds
2823 the new level not to be the expected one. The expected level
2824 is always one more or one less than the previous one. */
2825 next_level = bidi_peek_at_next_level (bidi_it);
2826 while (next_level != expected_next_level)
2828 /* If next_level is -1, it means we have an unresolved level
2829 in the cache, which at this point should not happen. If
2830 it does, we will infloop. */
2831 eassert (next_level >= 0);
2832 /* If next_level is not consistent with incr, we might
2833 infloop. */
2834 eassert (incr > 0
2835 ? next_level > expected_next_level
2836 : next_level < expected_next_level);
2837 expected_next_level += incr;
2838 level_to_search += incr;
2839 bidi_find_other_level_edge (bidi_it, level_to_search, !ascending);
2840 bidi_it->scan_dir = -bidi_it->scan_dir;
2841 next_level = bidi_peek_at_next_level (bidi_it);
2844 /* Finally, deliver the next character in the new direction. */
2845 next_level = bidi_level_of_next_char (bidi_it);
2848 /* Take note when we have just processed the newline that precedes
2849 the end of the paragraph. The next time we are about to be
2850 called, set_iterator_to_next will automatically reinit the
2851 paragraph direction, if needed. We do this at the newline before
2852 the paragraph separator, because the next character might not be
2853 the first character of the next paragraph, due to the bidi
2854 reordering, whereas we _must_ know the paragraph base direction
2855 _before_ we process the paragraph's text, since the base
2856 direction affects the reordering. */
2857 if (bidi_it->scan_dir == 1
2858 && (bidi_it->ch == '\n' || bidi_it->ch == BIDI_EOB))
2860 /* The paragraph direction of the entire string, once
2861 determined, is in effect for the entire string. Setting the
2862 separator limit to the end of the string prevents
2863 bidi_paragraph_init from being called automatically on this
2864 string. */
2865 if (bidi_it->string.s || STRINGP (bidi_it->string.lstring))
2866 bidi_it->separator_limit = bidi_it->string.schars;
2867 else if (bidi_it->bytepos < ZV_BYTE)
2869 ptrdiff_t sep_len
2870 = bidi_at_paragraph_end (bidi_it->charpos + bidi_it->nchars,
2871 bidi_it->bytepos + bidi_it->ch_len);
2872 if (bidi_it->nchars <= 0)
2873 emacs_abort ();
2874 if (sep_len >= 0)
2876 bidi_it->new_paragraph = 1;
2877 /* Record the buffer position of the last character of the
2878 paragraph separator. */
2879 bidi_it->separator_limit
2880 = bidi_it->charpos + bidi_it->nchars + sep_len;
2885 if (bidi_it->scan_dir == 1 && bidi_cache_idx > bidi_cache_start)
2887 /* If we are at paragraph's base embedding level and beyond the
2888 last cached position, the cache's job is done and we can
2889 discard it. */
2890 if (bidi_it->resolved_level == bidi_it->level_stack[0].level
2891 && bidi_it->charpos > (bidi_cache[bidi_cache_idx - 1].charpos
2892 + bidi_cache[bidi_cache_idx - 1].nchars - 1))
2893 bidi_cache_reset ();
2894 /* But as long as we are caching during forward scan, we must
2895 cache each state, or else the cache integrity will be
2896 compromised: it assumes cached states correspond to buffer
2897 positions 1:1. */
2898 else
2899 bidi_cache_iterator_state (bidi_it, 1);
2902 if (STRINGP (bidi_it->string.lstring))
2903 UNGCPRO;
2906 /* This is meant to be called from within the debugger, whenever you
2907 wish to examine the cache contents. */
2908 void bidi_dump_cached_states (void) EXTERNALLY_VISIBLE;
2909 void
2910 bidi_dump_cached_states (void)
2912 ptrdiff_t i;
2913 int ndigits = 1;
2915 if (bidi_cache_idx == 0)
2917 fprintf (stderr, "The cache is empty.\n");
2918 return;
2920 fprintf (stderr, "Total of %"pD"d state%s in cache:\n",
2921 bidi_cache_idx, bidi_cache_idx == 1 ? "" : "s");
2923 for (i = bidi_cache[bidi_cache_idx - 1].charpos; i > 0; i /= 10)
2924 ndigits++;
2925 fputs ("ch ", stderr);
2926 for (i = 0; i < bidi_cache_idx; i++)
2927 fprintf (stderr, "%*c", ndigits, bidi_cache[i].ch);
2928 fputs ("\n", stderr);
2929 fputs ("lvl ", stderr);
2930 for (i = 0; i < bidi_cache_idx; i++)
2931 fprintf (stderr, "%*d", ndigits, bidi_cache[i].resolved_level);
2932 fputs ("\n", stderr);
2933 fputs ("pos ", stderr);
2934 for (i = 0; i < bidi_cache_idx; i++)
2935 fprintf (stderr, "%*"pD"d", ndigits, bidi_cache[i].charpos);
2936 fputs ("\n", stderr);