* bidi.c (bidi_mirror_char): Don't possibly truncate the integer
[bpt/emacs.git] / src / bidi.c
CommitLineData
cbb09f04 1/* Low-level bidirectional buffer/string-scanning functions for GNU Emacs.
acaf905b 2 Copyright (C) 2000-2001, 2004-2005, 2009-2012
b118e65f 3 Free Software Foundation, Inc.
b7b65b15
EZ
4
5This file is part of GNU Emacs.
6
a8d11bd3 7GNU Emacs is free software: you can redistribute it and/or modify
b7b65b15 8it under the terms of the GNU General Public License as published by
a8d11bd3
EZ
9the Free Software Foundation, either version 3 of the License, or
10(at your option) any later version.
b7b65b15
EZ
11
12GNU Emacs is distributed in the hope that it will be useful,
13but WITHOUT ANY WARRANTY; without even the implied warranty of
14MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15GNU General Public License for more details.
16
b7b65b15 17You should have received a copy of the GNU General Public License
a8d11bd3 18along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
b7b65b15 19
2d6e4628
EZ
20/* Written by Eli Zaretskii <eliz@gnu.org>.
21
22 A sequential implementation of the Unicode Bidirectional algorithm,
cbb09f04 23 (UBA) as per UAX#9, a part of the Unicode Standard.
b7b65b15
EZ
24
25 Unlike the reference and most other implementations, this one is
940afb59
EZ
26 designed to be called once for every character in the buffer or
27 string.
b7b65b15 28
4b292a22 29 The main entry point is bidi_move_to_visually_next. Each time it
b7b65b15
EZ
30 is called, it finds the next character in the visual order, and
31 returns its information in a special structure. The caller is then
32 expected to process this character for display or any other
4b292a22
EZ
33 purposes, and call bidi_move_to_visually_next for the next
34 character. See the comments in bidi_move_to_visually_next for more
35 details about its algorithm that finds the next visual-order
b7b65b15
EZ
36 character by resolving their levels on the fly.
37
95e1afc6 38 Two other entry points are bidi_paragraph_init and
940afb59
EZ
39 bidi_mirror_char. The first determines the base direction of a
40 paragraph, while the second returns the mirrored version of its
41 argument character.
42
95e1afc6
EZ
43 A few auxiliary entry points are used to initialize the bidi
44 iterator for iterating an object (buffer or string), push and pop
45 the bidi iterator state, and save and restore the state of the bidi
46 cache.
47
89d3374a
EZ
48 If you want to understand the code, you will have to read it
49 together with the relevant portions of UAX#9. The comments include
50 references to UAX#9 rules, for that very reason.
51
b7b65b15
EZ
52 A note about references to UAX#9 rules: if the reference says
53 something like "X9/Retaining", it means that you need to refer to
cd1181db 54 rule X9 and to its modifications described in the "Implementation
b7b65b15
EZ
55 Notes" section of UAX#9, under "Retaining Format Codes". */
56
b7b65b15 57#include <config.h>
b7b65b15 58#include <stdio.h>
29e3d8d1
EZ
59#include <setjmp.h>
60
b7b65b15
EZ
61#include "lisp.h"
62#include "buffer.h"
63#include "character.h"
64#include "dispextern.h"
65
66static int bidi_initialized = 0;
67
cbc4fd20 68static Lisp_Object bidi_type_table, bidi_mirror_table;
b7b65b15
EZ
69
70#define LRM_CHAR 0x200E
71#define RLM_CHAR 0x200F
b7b65b15 72#define BIDI_EOB -1
b7b65b15 73
b7b65b15
EZ
74/* Data type for describing the bidirectional character categories. */
75typedef enum {
76 UNKNOWN_BC,
77 NEUTRAL,
78 WEAK,
79 STRONG
80} bidi_category_t;
81
32413314
EZ
82/* UAX#9 says to search only for L, AL, or R types of characters, and
83 ignore RLE, RLO, LRE, and LRO, when determining the base paragraph
84 level. Yudit indeed ignores them. This variable is therefore set
85 by default to ignore them, but setting it to zero will take them
86 into account. */
e78aecca 87extern int bidi_ignore_explicit_marks_for_paragraph_level EXTERNALLY_VISIBLE;
b7b65b15
EZ
88int bidi_ignore_explicit_marks_for_paragraph_level = 1;
89
372b7a95 90static Lisp_Object paragraph_start_re, paragraph_separate_re;
6bff6497 91static Lisp_Object Qparagraph_start, Qparagraph_separate;
b7b65b15 92
cbb09f04
EZ
93\f
94/***********************************************************************
95 Utilities
96 ***********************************************************************/
b7b65b15 97
6bff6497
EZ
98/* Return the bidi type of a character CH, subject to the current
99 directional OVERRIDE. */
55d4c1b2 100static inline bidi_type_t
6bff6497 101bidi_get_type (int ch, bidi_dir_t override)
b7b65b15 102{
6bff6497
EZ
103 bidi_type_t default_type;
104
e7402cb2
EZ
105 if (ch == BIDI_EOB)
106 return NEUTRAL_B;
e342a24d
EZ
107 if (ch < 0 || ch > MAX_CHAR)
108 abort ();
6bff6497
EZ
109
110 default_type = (bidi_type_t) XINT (CHAR_TABLE_REF (bidi_type_table, ch));
bca633fb
EZ
111 /* Every valid character code, even those that are unassigned by the
112 UCD, have some bidi-class property, according to
113 DerivedBidiClass.txt file. Therefore, if we ever get UNKNOWN_BT
114 (= zero) code from CHAR_TABLE_REF, that's a bug. */
115 if (default_type == UNKNOWN_BT)
116 abort ();
6bff6497
EZ
117
118 if (override == NEUTRAL_DIR)
119 return default_type;
120
121 switch (default_type)
122 {
123 /* Although UAX#9 does not tell, it doesn't make sense to
124 override NEUTRAL_B and LRM/RLM characters. */
125 case NEUTRAL_B:
126 case LRE:
127 case LRO:
128 case RLE:
129 case RLO:
130 case PDF:
131 return default_type;
132 default:
133 switch (ch)
134 {
135 case LRM_CHAR:
136 case RLM_CHAR:
137 return default_type;
138 default:
139 if (override == L2R) /* X6 */
140 return STRONG_L;
141 else if (override == R2L)
142 return STRONG_R;
143 else
144 abort (); /* can't happen: handled above */
145 }
146 }
b7b65b15
EZ
147}
148
f67cdd7f 149static inline void
2d6e4628
EZ
150bidi_check_type (bidi_type_t type)
151{
f67cdd7f 152 xassert (UNKNOWN_BT <= type && type <= NEUTRAL_ON);
2d6e4628
EZ
153}
154
b7b65b15 155/* Given a bidi TYPE of a character, return its category. */
55d4c1b2 156static inline bidi_category_t
b7b65b15
EZ
157bidi_get_category (bidi_type_t type)
158{
159 switch (type)
160 {
161 case UNKNOWN_BT:
162 return UNKNOWN_BC;
163 case STRONG_L:
164 case STRONG_R:
165 case STRONG_AL:
166 case LRE:
167 case LRO:
168 case RLE:
169 case RLO:
170 return STRONG;
171 case PDF: /* ??? really?? */
172 case WEAK_EN:
173 case WEAK_ES:
174 case WEAK_ET:
175 case WEAK_AN:
176 case WEAK_CS:
177 case WEAK_NSM:
178 case WEAK_BN:
179 return WEAK;
180 case NEUTRAL_B:
181 case NEUTRAL_S:
182 case NEUTRAL_WS:
183 case NEUTRAL_ON:
184 return NEUTRAL;
185 default:
186 abort ();
187 }
188}
189
a6e8d97c
EZ
190/* Return the mirrored character of C, if it has one. If C has no
191 mirrored counterpart, return C.
192 Note: The conditions in UAX#9 clause L4 regarding the surrounding
193 context must be tested by the caller. */
b7b65b15
EZ
194int
195bidi_mirror_char (int c)
196{
cbc4fd20
EZ
197 Lisp_Object val;
198
199 if (c == BIDI_EOB)
200 return c;
201 if (c < 0 || c > MAX_CHAR)
202 abort ();
b7b65b15 203
cbc4fd20
EZ
204 val = CHAR_TABLE_REF (bidi_mirror_table, c);
205 if (INTEGERP (val))
b7b65b15 206 {
81899c91
PE
207 eassert (CHAR_VALID_P (XINT (val)));
208 return XINT (val);
b7b65b15 209 }
cbc4fd20 210
b7b65b15
EZ
211 return c;
212}
213
cbb09f04
EZ
214/* Determine the start-of-run (sor) directional type given the two
215 embedding levels on either side of the run boundary. Also, update
216 the saved info about previously seen characters, since that info is
217 generally valid for a single level run. */
58b9f433 218static inline void
cbb09f04
EZ
219bidi_set_sor_type (struct bidi_it *bidi_it, int level_before, int level_after)
220{
512a289d 221 int higher_level = (level_before > level_after ? level_before : level_after);
cbb09f04
EZ
222
223 /* The prev_was_pdf gork is required for when we have several PDFs
224 in a row. In that case, we want to compute the sor type for the
225 next level run only once: when we see the first PDF. That's
226 because the sor type depends only on the higher of the two levels
227 that we find on the two sides of the level boundary (see UAX#9,
228 clause X10), and so we don't need to know the final embedding
229 level to which we descend after processing all the PDFs. */
230 if (!bidi_it->prev_was_pdf || level_before < level_after)
231 /* FIXME: should the default sor direction be user selectable? */
512a289d 232 bidi_it->sor = ((higher_level & 1) != 0 ? R2L : L2R);
cbb09f04
EZ
233 if (level_before > level_after)
234 bidi_it->prev_was_pdf = 1;
235
236 bidi_it->prev.type = UNKNOWN_BT;
512a289d
RS
237 bidi_it->last_strong.type = bidi_it->last_strong.type_after_w1
238 = bidi_it->last_strong.orig_type = UNKNOWN_BT;
239 bidi_it->prev_for_neutral.type = (bidi_it->sor == R2L ? STRONG_R : STRONG_L);
cbb09f04
EZ
240 bidi_it->prev_for_neutral.charpos = bidi_it->charpos;
241 bidi_it->prev_for_neutral.bytepos = bidi_it->bytepos;
512a289d
RS
242 bidi_it->next_for_neutral.type = bidi_it->next_for_neutral.type_after_w1
243 = bidi_it->next_for_neutral.orig_type = UNKNOWN_BT;
cbb09f04
EZ
244 bidi_it->ignore_bn_limit = -1; /* meaning it's unknown */
245}
246
247/* Push the current embedding level and override status; reset the
248 current level to LEVEL and the current override status to OVERRIDE. */
58b9f433 249static inline void
cbb09f04
EZ
250bidi_push_embedding_level (struct bidi_it *bidi_it,
251 int level, bidi_dir_t override)
252{
253 bidi_it->stack_idx++;
7e2ad32c 254 xassert (bidi_it->stack_idx < BIDI_MAXLEVEL);
cbb09f04
EZ
255 bidi_it->level_stack[bidi_it->stack_idx].level = level;
256 bidi_it->level_stack[bidi_it->stack_idx].override = override;
257}
258
259/* Pop the embedding level and directional override status from the
260 stack, and return the new level. */
58b9f433 261static inline int
cbb09f04
EZ
262bidi_pop_embedding_level (struct bidi_it *bidi_it)
263{
264 /* UAX#9 says to ignore invalid PDFs. */
265 if (bidi_it->stack_idx > 0)
266 bidi_it->stack_idx--;
267 return bidi_it->level_stack[bidi_it->stack_idx].level;
268}
269
270/* Record in SAVED_INFO the information about the current character. */
58b9f433 271static inline void
cbb09f04
EZ
272bidi_remember_char (struct bidi_saved_info *saved_info,
273 struct bidi_it *bidi_it)
274{
275 saved_info->charpos = bidi_it->charpos;
276 saved_info->bytepos = bidi_it->bytepos;
277 saved_info->type = bidi_it->type;
278 bidi_check_type (bidi_it->type);
279 saved_info->type_after_w1 = bidi_it->type_after_w1;
280 bidi_check_type (bidi_it->type_after_w1);
281 saved_info->orig_type = bidi_it->orig_type;
282 bidi_check_type (bidi_it->orig_type);
283}
284
b7b65b15
EZ
285/* Copy the bidi iterator from FROM to TO. To save cycles, this only
286 copies the part of the level stack that is actually in use. */
55d4c1b2 287static inline void
b7b65b15
EZ
288bidi_copy_it (struct bidi_it *to, struct bidi_it *from)
289{
290 int i;
291
e69a9370 292 /* Copy everything except the level stack and beyond. */
182ce2d2 293 memcpy (to, from, offsetof (struct bidi_it, level_stack[0]));
b7b65b15
EZ
294
295 /* Copy the active part of the level stack. */
296 to->level_stack[0] = from->level_stack[0]; /* level zero is always in use */
297 for (i = 1; i <= from->stack_idx; i++)
298 to->level_stack[i] = from->level_stack[i];
299}
300
cbb09f04
EZ
301\f
302/***********************************************************************
303 Caching the bidi iterator states
304 ***********************************************************************/
b7b65b15 305
2fe72643
EZ
306#define BIDI_CACHE_CHUNK 200
307static struct bidi_it *bidi_cache;
39e378da 308static ptrdiff_t bidi_cache_size = 0;
ad6042bb 309enum { elsz = sizeof (struct bidi_it) };
39e378da
PE
310static ptrdiff_t bidi_cache_idx; /* next unused cache slot */
311static ptrdiff_t bidi_cache_last_idx; /* slot of last cache hit */
312static ptrdiff_t bidi_cache_start = 0; /* start of cache for this
87e67904
EZ
313 "stack" level */
314
bc18e09d
PE
315/* 5-slot stack for saving the start of the previous level of the
316 cache. xdisp.c maintains a 5-slot stack for its iterator state,
317 and we need the same size of our stack. */
318static ptrdiff_t bidi_cache_start_stack[IT_STACK_SIZE];
319static int bidi_cache_sp;
320
321/* Size of header used by bidi_shelve_cache. */
322enum
323 {
512a289d
RS
324 bidi_shelve_header_size
325 = (sizeof (bidi_cache_idx) + sizeof (bidi_cache_start_stack)
326 + sizeof (bidi_cache_sp) + sizeof (bidi_cache_start)
327 + sizeof (bidi_cache_last_idx))
bc18e09d
PE
328 };
329
87e67904
EZ
330/* Reset the cache state to the empty state. We only reset the part
331 of the cache relevant to iteration of the current object. Previous
332 objects, which are pushed on the display iterator's stack, are left
333 intact. This is called when the cached information is no more
334 useful for the current iteration, e.g. when we were reseated to a
335 new position on the same object. */
55d4c1b2 336static inline void
b7b65b15
EZ
337bidi_cache_reset (void)
338{
87e67904 339 bidi_cache_idx = bidi_cache_start;
b7b65b15
EZ
340 bidi_cache_last_idx = -1;
341}
342
87e67904
EZ
343/* Shrink the cache to its minimal size. Called when we init the bidi
344 iterator for reordering a buffer or a string that does not come
345 from display properties, because that means all the previously
346 cached info is of no further use. */
55d4c1b2 347static inline void
2fe72643
EZ
348bidi_cache_shrink (void)
349{
350 if (bidi_cache_size > BIDI_CACHE_CHUNK)
351 {
512a289d
RS
352 bidi_cache
353 = (struct bidi_it *) xrealloc (bidi_cache, BIDI_CACHE_CHUNK * elsz);
51f30bc5 354 bidi_cache_size = BIDI_CACHE_CHUNK;
2fe72643
EZ
355 }
356 bidi_cache_reset ();
357}
358
55d4c1b2 359static inline void
39e378da 360bidi_cache_fetch_state (ptrdiff_t idx, struct bidi_it *bidi_it)
b7b65b15
EZ
361{
362 int current_scan_dir = bidi_it->scan_dir;
363
87e67904 364 if (idx < bidi_cache_start || idx >= bidi_cache_idx)
b7b65b15
EZ
365 abort ();
366
367 bidi_copy_it (bidi_it, &bidi_cache[idx]);
368 bidi_it->scan_dir = current_scan_dir;
369 bidi_cache_last_idx = idx;
370}
371
372/* Find a cached state with a given CHARPOS and resolved embedding
373 level less or equal to LEVEL. if LEVEL is -1, disregard the
374 resolved levels in cached states. DIR, if non-zero, means search
375 in that direction from the last cache hit. */
39e378da 376static inline ptrdiff_t
d311d28c 377bidi_cache_search (ptrdiff_t charpos, int level, int dir)
b7b65b15 378{
39e378da 379 ptrdiff_t i, i_start;
b7b65b15 380
6eec7596 381 if (bidi_cache_idx > bidi_cache_start)
b7b65b15 382 {
6eec7596
EZ
383 if (bidi_cache_last_idx == -1)
384 bidi_cache_last_idx = bidi_cache_idx - 1;
b7b65b15 385 if (charpos < bidi_cache[bidi_cache_last_idx].charpos)
182ce2d2
EZ
386 {
387 dir = -1;
388 i_start = bidi_cache_last_idx - 1;
389 }
390 else if (charpos > (bidi_cache[bidi_cache_last_idx].charpos
391 + bidi_cache[bidi_cache_last_idx].nchars - 1))
392 {
393 dir = 1;
394 i_start = bidi_cache_last_idx + 1;
395 }
396 else if (dir)
b7b65b15
EZ
397 i_start = bidi_cache_last_idx;
398 else
399 {
400 dir = -1;
401 i_start = bidi_cache_idx - 1;
402 }
403
404 if (dir < 0)
405 {
406 /* Linear search for now; FIXME! */
87e67904 407 for (i = i_start; i >= bidi_cache_start; i--)
182ce2d2
EZ
408 if (bidi_cache[i].charpos <= charpos
409 && charpos < bidi_cache[i].charpos + bidi_cache[i].nchars
b7b65b15
EZ
410 && (level == -1 || bidi_cache[i].resolved_level <= level))
411 return i;
412 }
413 else
414 {
415 for (i = i_start; i < bidi_cache_idx; i++)
182ce2d2
EZ
416 if (bidi_cache[i].charpos <= charpos
417 && charpos < bidi_cache[i].charpos + bidi_cache[i].nchars
b7b65b15
EZ
418 && (level == -1 || bidi_cache[i].resolved_level <= level))
419 return i;
420 }
421 }
422
423 return -1;
424}
425
426/* Find a cached state where the resolved level changes to a value
427 that is lower than LEVEL, and return its cache slot index. DIR is
428 the direction to search, starting with the last used cache slot.
87e67904
EZ
429 If DIR is zero, we search backwards from the last occupied cache
430 slot. BEFORE, if non-zero, means return the index of the slot that
431 is ``before'' the level change in the search direction. That is,
b7b65b15
EZ
432 given the cached levels like this:
433
434 1122333442211
435 AB C
436
437 and assuming we are at the position cached at the slot marked with
438 C, searching backwards (DIR = -1) for LEVEL = 2 will return the
439 index of slot B or A, depending whether BEFORE is, respectively,
440 non-zero or zero. */
39e378da 441static ptrdiff_t
b7b65b15
EZ
442bidi_cache_find_level_change (int level, int dir, int before)
443{
444 if (bidi_cache_idx)
445 {
39e378da 446 ptrdiff_t i = dir ? bidi_cache_last_idx : bidi_cache_idx - 1;
b7b65b15
EZ
447 int incr = before ? 1 : 0;
448
6eec7596
EZ
449 xassert (!dir || bidi_cache_last_idx >= 0);
450
b7b65b15
EZ
451 if (!dir)
452 dir = -1;
453 else if (!incr)
454 i += dir;
455
456 if (dir < 0)
457 {
87e67904 458 while (i >= bidi_cache_start + incr)
b7b65b15
EZ
459 {
460 if (bidi_cache[i - incr].resolved_level >= 0
461 && bidi_cache[i - incr].resolved_level < level)
462 return i;
463 i--;
464 }
465 }
466 else
467 {
468 while (i < bidi_cache_idx - incr)
469 {
470 if (bidi_cache[i + incr].resolved_level >= 0
471 && bidi_cache[i + incr].resolved_level < level)
472 return i;
473 i++;
474 }
475 }
476 }
477
478 return -1;
479}
480
58b9f433 481static inline void
39e378da 482bidi_cache_ensure_space (ptrdiff_t idx)
58b9f433
EZ
483{
484 /* Enlarge the cache as needed. */
485 if (idx >= bidi_cache_size)
486 {
f0eb61e9
PE
487 /* The bidi cache cannot be larger than the largest Lisp string
488 or buffer. */
512a289d
RS
489 ptrdiff_t string_or_buffer_bound
490 = max (BUF_BYTES_MAX, STRING_BYTES_BOUND);
f0eb61e9
PE
491
492 /* Also, it cannot be larger than what C can represent. */
512a289d
RS
493 ptrdiff_t c_bound
494 = (min (PTRDIFF_MAX, SIZE_MAX) - bidi_shelve_header_size) / elsz;
f0eb61e9 495
512a289d
RS
496 bidi_cache
497 = xpalloc (bidi_cache, &bidi_cache_size,
498 max (BIDI_CACHE_CHUNK, idx - bidi_cache_size + 1),
499 min (string_or_buffer_bound, c_bound), elsz);
58b9f433
EZ
500 }
501}
502
55d4c1b2 503static inline void
b7b65b15
EZ
504bidi_cache_iterator_state (struct bidi_it *bidi_it, int resolved)
505{
39e378da 506 ptrdiff_t idx;
b7b65b15
EZ
507
508 /* We should never cache on backward scans. */
509 if (bidi_it->scan_dir == -1)
510 abort ();
511 idx = bidi_cache_search (bidi_it->charpos, -1, 1);
512
513 if (idx < 0)
514 {
515 idx = bidi_cache_idx;
58b9f433 516 bidi_cache_ensure_space (idx);
bd924a5d
EZ
517 /* Character positions should correspond to cache positions 1:1.
518 If we are outside the range of cached positions, the cache is
519 useless and must be reset. */
87e67904 520 if (idx > bidi_cache_start &&
182ce2d2
EZ
521 (bidi_it->charpos > (bidi_cache[idx - 1].charpos
522 + bidi_cache[idx - 1].nchars)
a1344e7d 523 || bidi_it->charpos < bidi_cache[bidi_cache_start].charpos))
bd924a5d
EZ
524 {
525 bidi_cache_reset ();
87e67904 526 idx = bidi_cache_start;
bd924a5d 527 }
102ebb00
EZ
528 if (bidi_it->nchars <= 0)
529 abort ();
b7b65b15
EZ
530 bidi_copy_it (&bidi_cache[idx], bidi_it);
531 if (!resolved)
532 bidi_cache[idx].resolved_level = -1;
533 }
534 else
535 {
536 /* Copy only the members which could have changed, to avoid
537 costly copying of the entire struct. */
538 bidi_cache[idx].type = bidi_it->type;
2d6e4628 539 bidi_check_type (bidi_it->type);
89d3374a
EZ
540 bidi_cache[idx].type_after_w1 = bidi_it->type_after_w1;
541 bidi_check_type (bidi_it->type_after_w1);
b7b65b15
EZ
542 if (resolved)
543 bidi_cache[idx].resolved_level = bidi_it->resolved_level;
544 else
545 bidi_cache[idx].resolved_level = -1;
546 bidi_cache[idx].invalid_levels = bidi_it->invalid_levels;
547 bidi_cache[idx].invalid_rl_levels = bidi_it->invalid_rl_levels;
548 bidi_cache[idx].next_for_neutral = bidi_it->next_for_neutral;
549 bidi_cache[idx].next_for_ws = bidi_it->next_for_ws;
550 bidi_cache[idx].ignore_bn_limit = bidi_it->ignore_bn_limit;
f67cdd7f 551 bidi_cache[idx].disp_pos = bidi_it->disp_pos;
0c95fcf7 552 bidi_cache[idx].disp_prop = bidi_it->disp_prop;
b7b65b15
EZ
553 }
554
555 bidi_cache_last_idx = idx;
556 if (idx >= bidi_cache_idx)
557 bidi_cache_idx = idx + 1;
558}
559
55d4c1b2 560static inline bidi_type_t
d311d28c 561bidi_cache_find (ptrdiff_t charpos, int level, struct bidi_it *bidi_it)
b7b65b15 562{
39e378da 563 ptrdiff_t i = bidi_cache_search (charpos, level, bidi_it->scan_dir);
b7b65b15 564
87e67904 565 if (i >= bidi_cache_start)
b7b65b15
EZ
566 {
567 bidi_dir_t current_scan_dir = bidi_it->scan_dir;
568
5009f85e 569 bidi_copy_it (bidi_it, &bidi_cache[i]);
b7b65b15 570 bidi_cache_last_idx = i;
5a5fa834 571 /* Don't let scan direction from the cached state override
b7b65b15
EZ
572 the current scan direction. */
573 bidi_it->scan_dir = current_scan_dir;
574 return bidi_it->type;
575 }
576
577 return UNKNOWN_BT;
578}
579
55d4c1b2 580static inline int
b7b65b15
EZ
581bidi_peek_at_next_level (struct bidi_it *bidi_it)
582{
87e67904 583 if (bidi_cache_idx == bidi_cache_start || bidi_cache_last_idx == -1)
b7b65b15
EZ
584 abort ();
585 return bidi_cache[bidi_cache_last_idx + bidi_it->scan_dir].resolved_level;
586}
587
cbb09f04 588\f
58b9f433
EZ
589/***********************************************************************
590 Pushing and popping the bidi iterator state
591 ***********************************************************************/
58b9f433
EZ
592
593/* Push the bidi iterator state in preparation for reordering a
594 different object, e.g. display string found at certain buffer
7e2ad32c
EZ
595 position. Pushing the bidi iterator boils down to saving its
596 entire state on the cache and starting a new cache "stacked" on top
597 of the current cache. */
58b9f433
EZ
598void
599bidi_push_it (struct bidi_it *bidi_it)
b7b65b15 600{
58b9f433
EZ
601 /* Save the current iterator state in its entirety after the last
602 used cache slot. */
603 bidi_cache_ensure_space (bidi_cache_idx);
604 memcpy (&bidi_cache[bidi_cache_idx++], bidi_it, sizeof (struct bidi_it));
be39f003 605
58b9f433 606 /* Push the current cache start onto the stack. */
7e2ad32c 607 xassert (bidi_cache_sp < IT_STACK_SIZE);
58b9f433 608 bidi_cache_start_stack[bidi_cache_sp++] = bidi_cache_start;
be39f003 609
58b9f433
EZ
610 /* Start a new level of cache, and make it empty. */
611 bidi_cache_start = bidi_cache_idx;
612 bidi_cache_last_idx = -1;
613}
614
615/* Restore the iterator state saved by bidi_push_it and return the
616 cache to the corresponding state. */
617void
618bidi_pop_it (struct bidi_it *bidi_it)
619{
620 if (bidi_cache_start <= 0)
621 abort ();
622
623 /* Reset the next free cache slot index to what it was before the
624 call to bidi_push_it. */
625 bidi_cache_idx = bidi_cache_start - 1;
626
627 /* Restore the bidi iterator state saved in the cache. */
628 memcpy (bidi_it, &bidi_cache[bidi_cache_idx], sizeof (struct bidi_it));
629
630 /* Pop the previous cache start from the stack. */
631 if (bidi_cache_sp <= 0)
632 abort ();
633 bidi_cache_start = bidi_cache_start_stack[--bidi_cache_sp];
634
635 /* Invalidate the last-used cache slot data. */
636 bidi_cache_last_idx = -1;
637}
638
ec7cc85b 639static ptrdiff_t bidi_cache_total_alloc;
35928349 640
ed94e6d7
EZ
641/* Stash away a copy of the cache and its control variables. */
642void *
643bidi_shelve_cache (void)
644{
645 unsigned char *databuf;
458bfed3 646 ptrdiff_t alloc;
ed94e6d7 647
35928349 648 /* Empty cache. */
ed94e6d7
EZ
649 if (bidi_cache_idx == 0)
650 return NULL;
651
458bfed3
PE
652 alloc = (bidi_shelve_header_size
653 + bidi_cache_idx * sizeof (struct bidi_it));
654 databuf = xmalloc (alloc);
655 bidi_cache_total_alloc += alloc;
35928349 656
ed94e6d7
EZ
657 memcpy (databuf, &bidi_cache_idx, sizeof (bidi_cache_idx));
658 memcpy (databuf + sizeof (bidi_cache_idx),
659 bidi_cache, bidi_cache_idx * sizeof (struct bidi_it));
660 memcpy (databuf + sizeof (bidi_cache_idx)
661 + bidi_cache_idx * sizeof (struct bidi_it),
662 bidi_cache_start_stack, sizeof (bidi_cache_start_stack));
663 memcpy (databuf + sizeof (bidi_cache_idx)
664 + bidi_cache_idx * sizeof (struct bidi_it)
665 + sizeof (bidi_cache_start_stack),
666 &bidi_cache_sp, sizeof (bidi_cache_sp));
667 memcpy (databuf + sizeof (bidi_cache_idx)
668 + bidi_cache_idx * sizeof (struct bidi_it)
669 + sizeof (bidi_cache_start_stack) + sizeof (bidi_cache_sp),
670 &bidi_cache_start, sizeof (bidi_cache_start));
671 memcpy (databuf + sizeof (bidi_cache_idx)
672 + bidi_cache_idx * sizeof (struct bidi_it)
673 + sizeof (bidi_cache_start_stack) + sizeof (bidi_cache_sp)
674 + sizeof (bidi_cache_start),
675 &bidi_cache_last_idx, sizeof (bidi_cache_last_idx));
676
677 return databuf;
678}
679
d1410150
EZ
680/* Restore the cache state from a copy stashed away by
681 bidi_shelve_cache, and free the buffer used to stash that copy.
682 JUST_FREE non-zero means free the buffer, but don't restore the
683 cache; used when the corresponding iterator is discarded instead of
684 being restored. */
ed94e6d7 685void
35928349 686bidi_unshelve_cache (void *databuf, int just_free)
ed94e6d7
EZ
687{
688 unsigned char *p = databuf;
689
690 if (!p)
be39f003 691 {
d1410150
EZ
692 if (!just_free)
693 {
694 /* A NULL pointer means an empty cache. */
695 bidi_cache_start = 0;
696 bidi_cache_sp = 0;
697 bidi_cache_reset ();
698 }
be39f003 699 }
ed94e6d7
EZ
700 else
701 {
35928349
EZ
702 if (just_free)
703 {
704 ptrdiff_t idx;
705
706 memcpy (&idx, p, sizeof (bidi_cache_idx));
512a289d
RS
707 bidi_cache_total_alloc
708 -= bidi_shelve_header_size + idx * sizeof (struct bidi_it);
35928349
EZ
709 }
710 else
711 {
712 memcpy (&bidi_cache_idx, p, sizeof (bidi_cache_idx));
713 bidi_cache_ensure_space (bidi_cache_idx);
714 memcpy (bidi_cache, p + sizeof (bidi_cache_idx),
715 bidi_cache_idx * sizeof (struct bidi_it));
716 memcpy (bidi_cache_start_stack,
717 p + sizeof (bidi_cache_idx)
718 + bidi_cache_idx * sizeof (struct bidi_it),
719 sizeof (bidi_cache_start_stack));
720 memcpy (&bidi_cache_sp,
721 p + sizeof (bidi_cache_idx)
722 + bidi_cache_idx * sizeof (struct bidi_it)
723 + sizeof (bidi_cache_start_stack),
724 sizeof (bidi_cache_sp));
725 memcpy (&bidi_cache_start,
726 p + sizeof (bidi_cache_idx)
727 + bidi_cache_idx * sizeof (struct bidi_it)
728 + sizeof (bidi_cache_start_stack) + sizeof (bidi_cache_sp),
729 sizeof (bidi_cache_start));
730 memcpy (&bidi_cache_last_idx,
731 p + sizeof (bidi_cache_idx)
732 + bidi_cache_idx * sizeof (struct bidi_it)
733 + sizeof (bidi_cache_start_stack) + sizeof (bidi_cache_sp)
734 + sizeof (bidi_cache_start),
735 sizeof (bidi_cache_last_idx));
512a289d
RS
736 bidi_cache_total_alloc
737 -= (bidi_shelve_header_size
738 + bidi_cache_idx * sizeof (struct bidi_it));
35928349 739 }
ed94e6d7
EZ
740
741 xfree (p);
742 }
743}
b7b65b15 744
58b9f433 745\f
cbb09f04
EZ
746/***********************************************************************
747 Initialization
748 ***********************************************************************/
749static void
750bidi_initialize (void)
b7b65b15 751{
474a8465
EZ
752 bidi_type_table = uniprop_table (intern ("bidi-class"));
753 if (NILP (bidi_type_table))
754 abort ();
cbb09f04
EZ
755 staticpro (&bidi_type_table);
756
474a8465
EZ
757 bidi_mirror_table = uniprop_table (intern ("mirroring"));
758 if (NILP (bidi_mirror_table))
759 abort ();
cbb09f04
EZ
760 staticpro (&bidi_mirror_table);
761
cbb09f04
EZ
762 Qparagraph_start = intern ("paragraph-start");
763 staticpro (&Qparagraph_start);
764 paragraph_start_re = Fsymbol_value (Qparagraph_start);
765 if (!STRINGP (paragraph_start_re))
766 paragraph_start_re = build_string ("\f\\|[ \t]*$");
767 staticpro (&paragraph_start_re);
768 Qparagraph_separate = intern ("paragraph-separate");
769 staticpro (&Qparagraph_separate);
770 paragraph_separate_re = Fsymbol_value (Qparagraph_separate);
771 if (!STRINGP (paragraph_separate_re))
772 paragraph_separate_re = build_string ("[ \t\f]*$");
773 staticpro (&paragraph_separate_re);
58b9f433
EZ
774
775 bidi_cache_sp = 0;
ec7cc85b 776 bidi_cache_total_alloc = 0;
58b9f433 777
cbb09f04 778 bidi_initialized = 1;
b7b65b15
EZ
779}
780
cbb09f04
EZ
781/* Do whatever UAX#9 clause X8 says should be done at paragraph's
782 end. */
55d4c1b2 783static inline void
cbb09f04 784bidi_set_paragraph_end (struct bidi_it *bidi_it)
b7b65b15 785{
cbb09f04
EZ
786 bidi_it->invalid_levels = 0;
787 bidi_it->invalid_rl_levels = -1;
788 bidi_it->stack_idx = 0;
789 bidi_it->resolved_level = bidi_it->level_stack[0].level;
790}
b7b65b15 791
cbb09f04
EZ
792/* Initialize the bidi iterator from buffer/string position CHARPOS. */
793void
d311d28c 794bidi_init_it (ptrdiff_t charpos, ptrdiff_t bytepos, int frame_window_p,
cbb09f04
EZ
795 struct bidi_it *bidi_it)
796{
797 if (! bidi_initialized)
798 bidi_initialize ();
799 if (charpos >= 0)
800 bidi_it->charpos = charpos;
801 if (bytepos >= 0)
802 bidi_it->bytepos = bytepos;
803 bidi_it->frame_window_p = frame_window_p;
804 bidi_it->nchars = -1; /* to be computed in bidi_resolve_explicit_1 */
805 bidi_it->first_elt = 1;
806 bidi_set_paragraph_end (bidi_it);
807 bidi_it->new_paragraph = 1;
808 bidi_it->separator_limit = -1;
809 bidi_it->type = NEUTRAL_B;
810 bidi_it->type_after_w1 = NEUTRAL_B;
811 bidi_it->orig_type = NEUTRAL_B;
812 bidi_it->prev_was_pdf = 0;
512a289d
RS
813 bidi_it->prev.type = bidi_it->prev.type_after_w1
814 = bidi_it->prev.orig_type = UNKNOWN_BT;
815 bidi_it->last_strong.type = bidi_it->last_strong.type_after_w1
816 = bidi_it->last_strong.orig_type = UNKNOWN_BT;
cbb09f04 817 bidi_it->next_for_neutral.charpos = -1;
512a289d
RS
818 bidi_it->next_for_neutral.type
819 = bidi_it->next_for_neutral.type_after_w1
820 = bidi_it->next_for_neutral.orig_type = UNKNOWN_BT;
cbb09f04 821 bidi_it->prev_for_neutral.charpos = -1;
512a289d
RS
822 bidi_it->prev_for_neutral.type
823 = bidi_it->prev_for_neutral.type_after_w1
824 = bidi_it->prev_for_neutral.orig_type = UNKNOWN_BT;
cbb09f04
EZ
825 bidi_it->sor = L2R; /* FIXME: should it be user-selectable? */
826 bidi_it->disp_pos = -1; /* invalid/unknown */
0c95fcf7 827 bidi_it->disp_prop = 0;
cbb09f04
EZ
828 /* We can only shrink the cache if we are at the bottom level of its
829 "stack". */
830 if (bidi_cache_start == 0)
831 bidi_cache_shrink ();
58b9f433
EZ
832 else
833 bidi_cache_reset ();
b7b65b15
EZ
834}
835
182ce2d2 836/* Perform initializations for reordering a new line of bidi text. */
6bff6497 837static void
be39f003
EZ
838bidi_line_init (struct bidi_it *bidi_it)
839{
840 bidi_it->scan_dir = 1; /* FIXME: do we need to have control on this? */
841 bidi_it->resolved_level = bidi_it->level_stack[0].level;
842 bidi_it->level_stack[0].override = NEUTRAL_DIR; /* X1 */
843 bidi_it->invalid_levels = 0;
844 bidi_it->invalid_rl_levels = -1;
4787455f
EZ
845 /* Setting this to zero will force its recomputation the first time
846 we need it for W5. */
847 bidi_it->next_en_pos = 0;
7b5d6677 848 bidi_it->next_en_type = UNKNOWN_BT;
be39f003 849 bidi_it->next_for_ws.type = UNKNOWN_BT;
b44d9321 850 bidi_set_sor_type (bidi_it,
512a289d 851 (bidi_it->paragraph_dir == R2L ? 1 : 0),
be39f003
EZ
852 bidi_it->level_stack[0].level); /* X10 */
853
854 bidi_cache_reset ();
855}
856
cbb09f04
EZ
857\f
858/***********************************************************************
859 Fetching characters
860 ***********************************************************************/
861
f3014ef5
EZ
862/* Count bytes in string S between BEG/BEGBYTE and END. BEG and END
863 are zero-based character positions in S, BEGBYTE is byte position
864 corresponding to BEG. UNIBYTE, if non-zero, means S is a unibyte
865 string. */
d311d28c
PE
866static inline ptrdiff_t
867bidi_count_bytes (const unsigned char *s, const ptrdiff_t beg,
868 const ptrdiff_t begbyte, const ptrdiff_t end, int unibyte)
87e67904 869{
d311d28c 870 ptrdiff_t pos = beg;
87e67904
EZ
871 const unsigned char *p = s + begbyte, *start = p;
872
f3014ef5
EZ
873 if (unibyte)
874 p = s + end;
875 else
87e67904 876 {
f3014ef5
EZ
877 if (!CHAR_HEAD_P (*p))
878 abort ();
879
880 while (pos < end)
881 {
882 p += BYTES_BY_CHAR_HEAD (*p);
883 pos++;
884 }
87e67904
EZ
885 }
886
887 return p - start;
888}
889
890/* Fetch and returns the character at byte position BYTEPOS. If S is
891 non-NULL, fetch the character from string S; otherwise fetch the
f3014ef5
EZ
892 character from the current buffer. UNIBYTE non-zero means S is a
893 unibyte string. */
87e67904 894static inline int
d311d28c 895bidi_char_at_pos (ptrdiff_t bytepos, const unsigned char *s, int unibyte)
87e67904
EZ
896{
897 if (s)
f3014ef5
EZ
898 {
899 if (unibyte)
900 return s[bytepos];
901 else
902 return STRING_CHAR (s + bytepos);
903 }
87e67904
EZ
904 else
905 return FETCH_MULTIBYTE_CHAR (bytepos);
906}
907
102ebb00
EZ
908/* Fetch and return the character at BYTEPOS/CHARPOS. If that
909 character is covered by a display string, treat the entire run of
0c95fcf7
EZ
910 covered characters as a single character, either u+2029 or u+FFFC,
911 and return their combined length in CH_LEN and NCHARS. DISP_POS
912 specifies the character position of the next display string, or -1
b75258b3
EZ
913 if not yet computed. When the next character is at or beyond that
914 position, the function updates DISP_POS with the position of the
915 next display string. DISP_PROP non-zero means that there's really
0c95fcf7
EZ
916 a display string at DISP_POS, as opposed to when we searched till
917 DISP_POS without finding one. If DISP_PROP is 2, it means the
918 display spec is of the form `(space ...)', which is replaced with
b75258b3
EZ
919 u+2029 to handle it as a paragraph separator. STRING->s is the C
920 string to iterate, or NULL if iterating over a buffer or a Lisp
921 string; in the latter case, STRING->lstring is the Lisp string. */
fec2107c 922static inline int
d311d28c 923bidi_fetch_char (ptrdiff_t bytepos, ptrdiff_t charpos, ptrdiff_t *disp_pos,
0c95fcf7 924 int *disp_prop, struct bidi_string_data *string,
d311d28c 925 int frame_window_p, ptrdiff_t *ch_len, ptrdiff_t *nchars)
182ce2d2
EZ
926{
927 int ch;
5895d7b9 928 ptrdiff_t endpos
512a289d 929 = (string->s || STRINGP (string->lstring)) ? string->schars : ZV;
6db161be 930 struct text_pos pos;
e99a9b8b 931 int len;
182ce2d2 932
182ce2d2 933 /* If we got past the last known position of display string, compute
87e67904
EZ
934 the position of the next one. That position could be at CHARPOS. */
935 if (charpos < endpos && charpos > *disp_pos)
6db161be
EZ
936 {
937 SET_TEXT_POS (pos, charpos, bytepos);
55439c61 938 *disp_pos = compute_display_string_pos (&pos, string, frame_window_p,
0c95fcf7 939 disp_prop);
6db161be 940 }
102ebb00
EZ
941
942 /* Fetch the character at BYTEPOS. */
87e67904 943 if (charpos >= endpos)
182ce2d2
EZ
944 {
945 ch = BIDI_EOB;
946 *ch_len = 1;
947 *nchars = 1;
87e67904 948 *disp_pos = endpos;
0c95fcf7 949 *disp_prop = 0;
182ce2d2 950 }
0c95fcf7 951 else if (charpos >= *disp_pos && *disp_prop)
182ce2d2 952 {
d311d28c 953 ptrdiff_t disp_end_pos;
7b600102
EZ
954
955 /* We don't expect to find ourselves in the middle of a display
956 property. Hopefully, it will never be needed. */
957 if (charpos > *disp_pos)
958 abort ();
0c95fcf7
EZ
959 /* Text covered by `display' properties and overlays with
960 display properties or display strings is handled as a single
961 character that represents the entire run of characters
962 covered by the display property. */
963 if (*disp_prop == 2)
964 {
965 /* `(space ...)' display specs are handled as paragraph
966 separators for the purposes of the reordering; see UAX#9
967 section 3 and clause HL1 in section 4.3 there. */
968 ch = 0x2029;
969 }
970 else
971 {
972 /* All other display specs are handled as the Unicode Object
973 Replacement Character. */
974 ch = 0xFFFC;
975 }
87e67904 976 disp_end_pos = compute_display_string_end (*disp_pos, string);
fbcaa2f3
EZ
977 if (disp_end_pos < 0)
978 {
979 /* Somebody removed the display string from the buffer
980 behind our back. Recover by processing this buffer
981 position as if no display property were present there to
982 begin with. */
983 *disp_prop = 0;
984 goto normal_char;
985 }
7b600102 986 *nchars = disp_end_pos - *disp_pos;
f3014ef5
EZ
987 if (*nchars <= 0)
988 abort ();
87e67904
EZ
989 if (string->s)
990 *ch_len = bidi_count_bytes (string->s, *disp_pos, bytepos,
f3014ef5 991 disp_end_pos, string->unibyte);
9f257352
EZ
992 else if (STRINGP (string->lstring))
993 *ch_len = bidi_count_bytes (SDATA (string->lstring), *disp_pos,
f3014ef5 994 bytepos, disp_end_pos, string->unibyte);
87e67904
EZ
995 else
996 *ch_len = CHAR_TO_BYTE (disp_end_pos) - bytepos;
182ce2d2 997 }
182ce2d2
EZ
998 else
999 {
fbcaa2f3 1000 normal_char:
87e67904
EZ
1001 if (string->s)
1002 {
87e67904 1003
f3014ef5
EZ
1004 if (!string->unibyte)
1005 {
1006 ch = STRING_CHAR_AND_LENGTH (string->s + bytepos, len);
1007 *ch_len = len;
1008 }
1009 else
1010 {
1011 ch = UNIBYTE_TO_CHAR (string->s[bytepos]);
1012 *ch_len = 1;
1013 }
87e67904 1014 }
9f257352
EZ
1015 else if (STRINGP (string->lstring))
1016 {
f3014ef5
EZ
1017 if (!string->unibyte)
1018 {
1019 ch = STRING_CHAR_AND_LENGTH (SDATA (string->lstring) + bytepos,
1020 len);
1021 *ch_len = len;
1022 }
1023 else
1024 {
1025 ch = UNIBYTE_TO_CHAR (SREF (string->lstring, bytepos));
1026 *ch_len = 1;
1027 }
9f257352 1028 }
87e67904
EZ
1029 else
1030 {
e99a9b8b
EZ
1031 ch = STRING_CHAR_AND_LENGTH (BYTE_POS_ADDR (bytepos), len);
1032 *ch_len = len;
87e67904 1033 }
182ce2d2
EZ
1034 *nchars = 1;
1035 }
1036
1037 /* If we just entered a run of characters covered by a display
1038 string, compute the position of the next display string. */
55439c61 1039 if (charpos + *nchars <= endpos && charpos + *nchars > *disp_pos
0c95fcf7 1040 && *disp_prop)
6db161be
EZ
1041 {
1042 SET_TEXT_POS (pos, charpos + *nchars, bytepos + *ch_len);
55439c61 1043 *disp_pos = compute_display_string_pos (&pos, string, frame_window_p,
0c95fcf7 1044 disp_prop);
6db161be 1045 }
182ce2d2
EZ
1046
1047 return ch;
1048}
1049
cbb09f04
EZ
1050\f
1051/***********************************************************************
1052 Determining paragraph direction
1053 ***********************************************************************/
1054
1055/* Check if buffer position CHARPOS/BYTEPOS is the end of a paragraph.
1056 Value is the non-negative length of the paragraph separator
1057 following the buffer position, -1 if position is at the beginning
1058 of a new paragraph, or -2 if position is neither at beginning nor
1059 at end of a paragraph. */
d311d28c
PE
1060static ptrdiff_t
1061bidi_at_paragraph_end (ptrdiff_t charpos, ptrdiff_t bytepos)
cbb09f04
EZ
1062{
1063 Lisp_Object sep_re;
1064 Lisp_Object start_re;
d311d28c 1065 ptrdiff_t val;
cbb09f04
EZ
1066
1067 sep_re = paragraph_separate_re;
1068 start_re = paragraph_start_re;
1069
1070 val = fast_looking_at (sep_re, charpos, bytepos, ZV, ZV_BYTE, Qnil);
1071 if (val < 0)
1072 {
1073 if (fast_looking_at (start_re, charpos, bytepos, ZV, ZV_BYTE, Qnil) >= 0)
1074 val = -1;
1075 else
1076 val = -2;
1077 }
1078
1079 return val;
1080}
1081
1137e8b8
EZ
1082/* On my 2005-vintage machine, searching back for paragraph start
1083 takes ~1 ms per line. And bidi_paragraph_init is called 4 times
1084 when user types C-p. The number below limits each call to
1085 bidi_paragraph_init to about 10 ms. */
1086#define MAX_PARAGRAPH_SEARCH 7500
1087
be39f003 1088/* Find the beginning of this paragraph by looking back in the buffer.
1137e8b8
EZ
1089 Value is the byte position of the paragraph's beginning, or
1090 BEGV_BYTE if paragraph_start_re is still not found after looking
1091 back MAX_PARAGRAPH_SEARCH lines in the buffer. */
d311d28c
PE
1092static ptrdiff_t
1093bidi_find_paragraph_start (ptrdiff_t pos, ptrdiff_t pos_byte)
6bff6497 1094{
372b7a95 1095 Lisp_Object re = paragraph_start_re;
d311d28c 1096 ptrdiff_t limit = ZV, limit_byte = ZV_BYTE;
4c0078d4 1097 ptrdiff_t n = 0;
6bff6497 1098
6bff6497 1099 while (pos_byte > BEGV_BYTE
1137e8b8 1100 && n++ < MAX_PARAGRAPH_SEARCH
6bff6497
EZ
1101 && fast_looking_at (re, pos, pos_byte, limit, limit_byte, Qnil) < 0)
1102 {
182ce2d2
EZ
1103 /* FIXME: What if the paragraph beginning is covered by a
1104 display string? And what if a display string covering some
1105 of the text over which we scan back includes
1106 paragraph_start_re? */
be39f003
EZ
1107 pos = find_next_newline_no_quit (pos - 1, -1);
1108 pos_byte = CHAR_TO_BYTE (pos);
6bff6497 1109 }
1137e8b8
EZ
1110 if (n >= MAX_PARAGRAPH_SEARCH)
1111 pos_byte = BEGV_BYTE;
be39f003 1112 return pos_byte;
6bff6497
EZ
1113}
1114
bea4f10c 1115/* Determine the base direction, a.k.a. base embedding level, of the
b44d9321
EZ
1116 paragraph we are about to iterate through. If DIR is either L2R or
1117 R2L, just use that. Otherwise, determine the paragraph direction
bea4f10c
EZ
1118 from the first strong directional character of the paragraph.
1119
182ce2d2 1120 NO_DEFAULT_P non-zero means don't default to L2R if the paragraph
bea4f10c
EZ
1121 has no strong directional characters and both DIR and
1122 bidi_it->paragraph_dir are NEUTRAL_DIR. In that case, search back
1123 in the buffer until a paragraph is found with a strong character,
1124 or until hitting BEGV. In the latter case, fall back to L2R. This
1125 flag is used in current-bidi-paragraph-direction.
1126
1127 Note that this function gives the paragraph separator the same
1128 direction as the preceding paragraph, even though Emacs generally
9858f6c3 1129 views the separator as not belonging to any paragraph. */
b7b65b15 1130void
bea4f10c 1131bidi_paragraph_init (bidi_dir_t dir, struct bidi_it *bidi_it, int no_default_p)
b7b65b15 1132{
d311d28c 1133 ptrdiff_t bytepos = bidi_it->bytepos;
9f257352 1134 int string_p = bidi_it->string.s != NULL || STRINGP (bidi_it->string.lstring);
d311d28c 1135 ptrdiff_t pstartbyte;
87e67904
EZ
1136 /* Note that begbyte is a byte position, while end is a character
1137 position. Yes, this is ugly, but we are trying to avoid costly
1138 calls to BYTE_TO_CHAR and its ilk. */
d311d28c
PE
1139 ptrdiff_t begbyte = string_p ? 0 : BEGV_BYTE;
1140 ptrdiff_t end = string_p ? bidi_it->string.schars : ZV;
e7402cb2 1141
5e65aec0 1142 /* Special case for an empty buffer. */
87e67904 1143 if (bytepos == begbyte && bidi_it->charpos == end)
5e65aec0 1144 dir = L2R;
9c82e145 1145 /* We should never be called at EOB or before BEGV. */
87e67904 1146 else if (bidi_it->charpos >= end || bytepos < begbyte)
9c82e145
EZ
1147 abort ();
1148
be39f003
EZ
1149 if (dir == L2R)
1150 {
1151 bidi_it->paragraph_dir = L2R;
1152 bidi_it->new_paragraph = 0;
1153 }
1154 else if (dir == R2L)
1155 {
1156 bidi_it->paragraph_dir = R2L;
1157 bidi_it->new_paragraph = 0;
1158 }
b7b65b15
EZ
1159 else if (dir == NEUTRAL_DIR) /* P2 */
1160 {
182ce2d2 1161 int ch;
d311d28c
PE
1162 ptrdiff_t ch_len, nchars;
1163 ptrdiff_t pos, disp_pos = -1;
0c95fcf7 1164 int disp_prop = 0;
6bff6497 1165 bidi_type_t type;
9f257352 1166 const unsigned char *s;
be39f003 1167
d20e1419
EZ
1168 if (!bidi_initialized)
1169 bidi_initialize ();
1170
be39f003
EZ
1171 /* If we are inside a paragraph separator, we are just waiting
1172 for the separator to be exhausted; use the previous paragraph
e5a2fec7
EZ
1173 direction. But don't do that if we have been just reseated,
1174 because we need to reinitialize below in that case. */
1175 if (!bidi_it->first_elt
1176 && bidi_it->charpos < bidi_it->separator_limit)
be39f003
EZ
1177 return;
1178
b44d9321 1179 /* If we are on a newline, get past it to where the next
5e65aec0
EZ
1180 paragraph might start. But don't do that at BEGV since then
1181 we are potentially in a new paragraph that doesn't yet
1182 exist. */
c143c213 1183 pos = bidi_it->charpos;
512a289d
RS
1184 s = (STRINGP (bidi_it->string.lstring)
1185 ? SDATA (bidi_it->string.lstring)
1186 : bidi_it->string.s);
f3014ef5
EZ
1187 if (bytepos > begbyte
1188 && bidi_char_at_pos (bytepos, s, bidi_it->string.unibyte) == '\n')
be39f003 1189 {
b44d9321 1190 bytepos++;
c143c213 1191 pos++;
be39f003 1192 }
b44d9321
EZ
1193
1194 /* We are either at the beginning of a paragraph or in the
1195 middle of it. Find where this paragraph starts. */
87e67904
EZ
1196 if (string_p)
1197 {
1198 /* We don't support changes of paragraph direction inside a
1199 string. It is treated as a single paragraph. */
1200 pstartbyte = 0;
1201 }
1202 else
1203 pstartbyte = bidi_find_paragraph_start (pos, bytepos);
be39f003
EZ
1204 bidi_it->separator_limit = -1;
1205 bidi_it->new_paragraph = 0;
bea4f10c
EZ
1206
1207 /* The following loop is run more than once only if NO_DEFAULT_P
87e67904 1208 is non-zero, and only if we are iterating on a buffer. */
bea4f10c
EZ
1209 do {
1210 bytepos = pstartbyte;
87e67904
EZ
1211 if (!string_p)
1212 pos = BYTE_TO_CHAR (bytepos);
0c95fcf7 1213 ch = bidi_fetch_char (bytepos, pos, &disp_pos, &disp_prop,
55439c61 1214 &bidi_it->string,
87e67904 1215 bidi_it->frame_window_p, &ch_len, &nchars);
bea4f10c
EZ
1216 type = bidi_get_type (ch, NEUTRAL_DIR);
1217
182ce2d2 1218 for (pos += nchars, bytepos += ch_len;
bea4f10c
EZ
1219 (bidi_get_category (type) != STRONG)
1220 || (bidi_ignore_explicit_marks_for_paragraph_level
1221 && (type == RLE || type == RLO
1222 || type == LRE || type == LRO));
1223 type = bidi_get_type (ch, NEUTRAL_DIR))
1224 {
87e67904 1225 if (pos >= end)
bea4f10c
EZ
1226 {
1227 /* Pretend there's a paragraph separator at end of
87e67904 1228 buffer/string. */
bea4f10c
EZ
1229 type = NEUTRAL_B;
1230 break;
1231 }
0bb23927
EZ
1232 if (!string_p
1233 && type == NEUTRAL_B
1234 && bidi_at_paragraph_end (pos, bytepos) >= -1)
cf99dcf8 1235 break;
102ebb00 1236 /* Fetch next character and advance to get past it. */
55439c61 1237 ch = bidi_fetch_char (bytepos, pos, &disp_pos,
0c95fcf7 1238 &disp_prop, &bidi_it->string,
fc6f18ce 1239 bidi_it->frame_window_p, &ch_len, &nchars);
182ce2d2
EZ
1240 pos += nchars;
1241 bytepos += ch_len;
bea4f10c 1242 }
32413314
EZ
1243 if ((type == STRONG_R || type == STRONG_AL) /* P3 */
1244 || (!bidi_ignore_explicit_marks_for_paragraph_level
1245 && (type == RLO || type == RLE)))
bea4f10c 1246 bidi_it->paragraph_dir = R2L;
32413314
EZ
1247 else if (type == STRONG_L
1248 || (!bidi_ignore_explicit_marks_for_paragraph_level
1249 && (type == LRO || type == LRE)))
bea4f10c 1250 bidi_it->paragraph_dir = L2R;
87e67904
EZ
1251 if (!string_p
1252 && no_default_p && bidi_it->paragraph_dir == NEUTRAL_DIR)
bea4f10c
EZ
1253 {
1254 /* If this paragraph is at BEGV, default to L2R. */
1255 if (pstartbyte == BEGV_BYTE)
1256 bidi_it->paragraph_dir = L2R; /* P3 and HL1 */
1257 else
1258 {
d311d28c
PE
1259 ptrdiff_t prevpbyte = pstartbyte;
1260 ptrdiff_t p = BYTE_TO_CHAR (pstartbyte), pbyte = pstartbyte;
bea4f10c
EZ
1261
1262 /* Find the beginning of the previous paragraph, if any. */
1263 while (pbyte > BEGV_BYTE && prevpbyte >= pstartbyte)
1264 {
182ce2d2
EZ
1265 /* FXIME: What if p is covered by a display
1266 string? See also a FIXME inside
1267 bidi_find_paragraph_start. */
bea4f10c
EZ
1268 p--;
1269 pbyte = CHAR_TO_BYTE (p);
1270 prevpbyte = bidi_find_paragraph_start (p, pbyte);
1271 }
1272 pstartbyte = prevpbyte;
1273 }
1274 }
87e67904
EZ
1275 } while (!string_p
1276 && no_default_p && bidi_it->paragraph_dir == NEUTRAL_DIR);
b7b65b15 1277 }
be39f003
EZ
1278 else
1279 abort ();
b7b65b15 1280
b44d9321
EZ
1281 /* Contrary to UAX#9 clause P3, we only default the paragraph
1282 direction to L2R if we have no previous usable paragraph
bea4f10c 1283 direction. This is allowed by the HL1 clause. */
d20e1419 1284 if (bidi_it->paragraph_dir != L2R && bidi_it->paragraph_dir != R2L)
bea4f10c 1285 bidi_it->paragraph_dir = L2R; /* P3 and HL1 ``higher-level protocols'' */
be39f003 1286 if (bidi_it->paragraph_dir == R2L)
b44d9321 1287 bidi_it->level_stack[0].level = 1;
be39f003 1288 else
b44d9321 1289 bidi_it->level_stack[0].level = 0;
be39f003
EZ
1290
1291 bidi_line_init (bidi_it);
b7b65b15
EZ
1292}
1293
cbb09f04
EZ
1294\f
1295/***********************************************************************
1296 Resolving explicit and implicit levels.
58b9f433 1297 The rest of this file constitutes the core of the UBA implementation.
cbb09f04 1298 ***********************************************************************/
b7b65b15 1299
55d4c1b2 1300static inline int
182ce2d2 1301bidi_explicit_dir_char (int ch)
b7b65b15 1302{
182ce2d2
EZ
1303 bidi_type_t ch_type;
1304
1305 if (!bidi_initialized)
1306 abort ();
1307 ch_type = (bidi_type_t) XINT (CHAR_TABLE_REF (bidi_type_table, ch));
1308 return (ch_type == LRE || ch_type == LRO
1309 || ch_type == RLE || ch_type == RLO
1310 || ch_type == PDF);
b7b65b15
EZ
1311}
1312
1313/* A helper function for bidi_resolve_explicit. It advances to the
1314 next character in logical order and determines the new embedding
1315 level and directional override, but does not take into account
1316 empty embeddings. */
1317static int
1318bidi_resolve_explicit_1 (struct bidi_it *bidi_it)
1319{
1320 int curchar;
1321 bidi_type_t type;
1322 int current_level;
1323 int new_level;
1324 bidi_dir_t override;
9f257352 1325 int string_p = bidi_it->string.s != NULL || STRINGP (bidi_it->string.lstring);
b7b65b15 1326
182ce2d2
EZ
1327 /* If reseat()'ed, don't advance, so as to start iteration from the
1328 position where we were reseated. bidi_it->bytepos can be less
1329 than BEGV_BYTE after reseat to BEGV. */
87e67904 1330 if (bidi_it->bytepos < (string_p ? 0 : BEGV_BYTE)
9c82e145 1331 || bidi_it->first_elt)
e7402cb2 1332 {
9c82e145 1333 bidi_it->first_elt = 0;
87e67904
EZ
1334 if (string_p)
1335 {
512a289d
RS
1336 const unsigned char *p
1337 = (STRINGP (bidi_it->string.lstring)
1338 ? SDATA (bidi_it->string.lstring)
1339 : bidi_it->string.s);
9f257352 1340
87e67904
EZ
1341 if (bidi_it->charpos < 0)
1342 bidi_it->charpos = 0;
f3014ef5
EZ
1343 bidi_it->bytepos = bidi_count_bytes (p, 0, 0, bidi_it->charpos,
1344 bidi_it->string.unibyte);
87e67904
EZ
1345 }
1346 else
1347 {
1348 if (bidi_it->charpos < BEGV)
1349 bidi_it->charpos = BEGV;
1350 bidi_it->bytepos = CHAR_TO_BYTE (bidi_it->charpos);
1351 }
e7402cb2 1352 }
87e67904
EZ
1353 /* Don't move at end of buffer/string. */
1354 else if (bidi_it->charpos < (string_p ? bidi_it->string.schars : ZV))
b7b65b15 1355 {
182ce2d2
EZ
1356 /* Advance to the next character, skipping characters covered by
1357 display strings (nchars > 1). */
102ebb00
EZ
1358 if (bidi_it->nchars <= 0)
1359 abort ();
182ce2d2 1360 bidi_it->charpos += bidi_it->nchars;
e7402cb2
EZ
1361 if (bidi_it->ch_len == 0)
1362 abort ();
b7b65b15
EZ
1363 bidi_it->bytepos += bidi_it->ch_len;
1364 }
1365
1366 current_level = bidi_it->level_stack[bidi_it->stack_idx].level; /* X1 */
1367 override = bidi_it->level_stack[bidi_it->stack_idx].override;
1368 new_level = current_level;
1369
87e67904 1370 if (bidi_it->charpos >= (string_p ? bidi_it->string.schars : ZV))
e7402cb2
EZ
1371 {
1372 curchar = BIDI_EOB;
1373 bidi_it->ch_len = 1;
182ce2d2 1374 bidi_it->nchars = 1;
87e67904 1375 bidi_it->disp_pos = (string_p ? bidi_it->string.schars : ZV);
0c95fcf7 1376 bidi_it->disp_prop = 0;
e7402cb2
EZ
1377 }
1378 else
1379 {
182ce2d2
EZ
1380 /* Fetch the character at BYTEPOS. If it is covered by a
1381 display string, treat the entire run of covered characters as
1382 a single character u+FFFC. */
102ebb00 1383 curchar = bidi_fetch_char (bidi_it->bytepos, bidi_it->charpos,
0c95fcf7 1384 &bidi_it->disp_pos, &bidi_it->disp_prop,
55439c61 1385 &bidi_it->string, bidi_it->frame_window_p,
102ebb00 1386 &bidi_it->ch_len, &bidi_it->nchars);
e7402cb2 1387 }
b7b65b15 1388 bidi_it->ch = curchar;
b7b65b15 1389
6bff6497
EZ
1390 /* Don't apply directional override here, as all the types we handle
1391 below will not be affected by the override anyway, and we need
1392 the original type unaltered. The override will be applied in
1393 bidi_resolve_weak. */
1394 type = bidi_get_type (curchar, NEUTRAL_DIR);
89d3374a
EZ
1395 bidi_it->orig_type = type;
1396 bidi_check_type (bidi_it->orig_type);
b7b65b15
EZ
1397
1398 if (type != PDF)
1399 bidi_it->prev_was_pdf = 0;
1400
89d3374a 1401 bidi_it->type_after_w1 = UNKNOWN_BT;
b7b65b15
EZ
1402
1403 switch (type)
1404 {
1405 case RLE: /* X2 */
1406 case RLO: /* X4 */
89d3374a
EZ
1407 bidi_it->type_after_w1 = type;
1408 bidi_check_type (bidi_it->type_after_w1);
b7b65b15 1409 type = WEAK_BN; /* X9/Retaining */
87e67904 1410 if (bidi_it->ignore_bn_limit <= -1)
b7b65b15
EZ
1411 {
1412 if (current_level <= BIDI_MAXLEVEL - 4)
1413 {
1414 /* Compute the least odd embedding level greater than
1415 the current level. */
1416 new_level = ((current_level + 1) & ~1) + 1;
89d3374a 1417 if (bidi_it->type_after_w1 == RLE)
b7b65b15
EZ
1418 override = NEUTRAL_DIR;
1419 else
1420 override = R2L;
1421 if (current_level == BIDI_MAXLEVEL - 4)
1422 bidi_it->invalid_rl_levels = 0;
1423 bidi_push_embedding_level (bidi_it, new_level, override);
1424 }
1425 else
1426 {
1427 bidi_it->invalid_levels++;
1428 /* See the commentary about invalid_rl_levels below. */
1429 if (bidi_it->invalid_rl_levels < 0)
1430 bidi_it->invalid_rl_levels = 0;
1431 bidi_it->invalid_rl_levels++;
1432 }
1433 }
89d3374a 1434 else if (bidi_it->prev.type_after_w1 == WEAK_EN /* W5/Retaining */
7b5d6677
EZ
1435 || (bidi_it->next_en_pos > bidi_it->charpos
1436 && bidi_it->next_en_type == WEAK_EN))
b7b65b15
EZ
1437 type = WEAK_EN;
1438 break;
1439 case LRE: /* X3 */
1440 case LRO: /* X5 */
89d3374a
EZ
1441 bidi_it->type_after_w1 = type;
1442 bidi_check_type (bidi_it->type_after_w1);
b7b65b15 1443 type = WEAK_BN; /* X9/Retaining */
87e67904 1444 if (bidi_it->ignore_bn_limit <= -1)
b7b65b15
EZ
1445 {
1446 if (current_level <= BIDI_MAXLEVEL - 5)
1447 {
1448 /* Compute the least even embedding level greater than
1449 the current level. */
1450 new_level = ((current_level + 2) & ~1);
89d3374a 1451 if (bidi_it->type_after_w1 == LRE)
b7b65b15
EZ
1452 override = NEUTRAL_DIR;
1453 else
1454 override = L2R;
1455 bidi_push_embedding_level (bidi_it, new_level, override);
1456 }
1457 else
1458 {
1459 bidi_it->invalid_levels++;
1460 /* invalid_rl_levels counts invalid levels encountered
1461 while the embedding level was already too high for
1462 LRE/LRO, but not for RLE/RLO. That is because
1463 there may be exactly one PDF which we should not
1464 ignore even though invalid_levels is non-zero.
1465 invalid_rl_levels helps to know what PDF is
1466 that. */
1467 if (bidi_it->invalid_rl_levels >= 0)
1468 bidi_it->invalid_rl_levels++;
1469 }
1470 }
89d3374a 1471 else if (bidi_it->prev.type_after_w1 == WEAK_EN /* W5/Retaining */
7b5d6677
EZ
1472 || (bidi_it->next_en_pos > bidi_it->charpos
1473 && bidi_it->next_en_type == WEAK_EN))
b7b65b15
EZ
1474 type = WEAK_EN;
1475 break;
1476 case PDF: /* X7 */
89d3374a
EZ
1477 bidi_it->type_after_w1 = type;
1478 bidi_check_type (bidi_it->type_after_w1);
b7b65b15 1479 type = WEAK_BN; /* X9/Retaining */
87e67904 1480 if (bidi_it->ignore_bn_limit <= -1)
b7b65b15
EZ
1481 {
1482 if (!bidi_it->invalid_rl_levels)
1483 {
1484 new_level = bidi_pop_embedding_level (bidi_it);
1485 bidi_it->invalid_rl_levels = -1;
1486 if (bidi_it->invalid_levels)
1487 bidi_it->invalid_levels--;
1488 /* else nothing: UAX#9 says to ignore invalid PDFs */
1489 }
1490 if (!bidi_it->invalid_levels)
1491 new_level = bidi_pop_embedding_level (bidi_it);
1492 else
1493 {
1494 bidi_it->invalid_levels--;
1495 bidi_it->invalid_rl_levels--;
1496 }
1497 }
89d3374a 1498 else if (bidi_it->prev.type_after_w1 == WEAK_EN /* W5/Retaining */
7b5d6677
EZ
1499 || (bidi_it->next_en_pos > bidi_it->charpos
1500 && bidi_it->next_en_type == WEAK_EN))
b7b65b15
EZ
1501 type = WEAK_EN;
1502 break;
1503 default:
1504 /* Nothing. */
1505 break;
1506 }
1507
1508 bidi_it->type = type;
2d6e4628 1509 bidi_check_type (bidi_it->type);
b7b65b15
EZ
1510
1511 return new_level;
1512}
1513
1514/* Given an iterator state in BIDI_IT, advance one character position
182ce2d2
EZ
1515 in the buffer/string to the next character (in the logical order),
1516 resolve any explicit embeddings and directional overrides, and
1517 return the embedding level of the character after resolving
1518 explicit directives and ignoring empty embeddings. */
b7b65b15
EZ
1519static int
1520bidi_resolve_explicit (struct bidi_it *bidi_it)
1521{
1522 int prev_level = bidi_it->level_stack[bidi_it->stack_idx].level;
1523 int new_level = bidi_resolve_explicit_1 (bidi_it);
d311d28c 1524 ptrdiff_t eob = bidi_it->string.s ? bidi_it->string.schars : ZV;
512a289d
RS
1525 const unsigned char *s
1526 = (STRINGP (bidi_it->string.lstring)
1527 ? SDATA (bidi_it->string.lstring)
1528 : bidi_it->string.s);
b7b65b15
EZ
1529
1530 if (prev_level < new_level
1531 && bidi_it->type == WEAK_BN
87e67904
EZ
1532 && bidi_it->ignore_bn_limit == -1 /* only if not already known */
1533 && bidi_it->charpos < eob /* not already at EOB */
1534 && bidi_explicit_dir_char (bidi_char_at_pos (bidi_it->bytepos
f3014ef5
EZ
1535 + bidi_it->ch_len, s,
1536 bidi_it->string.unibyte)))
b7b65b15
EZ
1537 {
1538 /* Avoid pushing and popping embedding levels if the level run
1539 is empty, as this breaks level runs where it shouldn't.
1540 UAX#9 removes all the explicit embedding and override codes,
1541 so empty embeddings disappear without a trace. We need to
1542 behave as if we did the same. */
1543 struct bidi_it saved_it;
1544 int level = prev_level;
1545
1546 bidi_copy_it (&saved_it, bidi_it);
1547
87e67904 1548 while (bidi_explicit_dir_char (bidi_char_at_pos (bidi_it->bytepos
f3014ef5
EZ
1549 + bidi_it->ch_len, s,
1550 bidi_it->string.unibyte)))
b7b65b15 1551 {
182ce2d2
EZ
1552 /* This advances to the next character, skipping any
1553 characters covered by display strings. */
b7b65b15 1554 level = bidi_resolve_explicit_1 (bidi_it);
9f257352
EZ
1555 /* If string.lstring was relocated inside bidi_resolve_explicit_1,
1556 a pointer to its data is no longer valid. */
1557 if (STRINGP (bidi_it->string.lstring))
1558 s = SDATA (bidi_it->string.lstring);
b7b65b15
EZ
1559 }
1560
102ebb00
EZ
1561 if (bidi_it->nchars <= 0)
1562 abort ();
b7b65b15 1563 if (level == prev_level) /* empty embedding */
182ce2d2 1564 saved_it.ignore_bn_limit = bidi_it->charpos + bidi_it->nchars;
b7b65b15 1565 else /* this embedding is non-empty */
87e67904 1566 saved_it.ignore_bn_limit = -2;
b7b65b15
EZ
1567
1568 bidi_copy_it (bidi_it, &saved_it);
87e67904 1569 if (bidi_it->ignore_bn_limit > -1)
b7b65b15
EZ
1570 {
1571 /* We pushed a level, but we shouldn't have. Undo that. */
1572 if (!bidi_it->invalid_rl_levels)
1573 {
1574 new_level = bidi_pop_embedding_level (bidi_it);
1575 bidi_it->invalid_rl_levels = -1;
1576 if (bidi_it->invalid_levels)
1577 bidi_it->invalid_levels--;
1578 }
1579 if (!bidi_it->invalid_levels)
1580 new_level = bidi_pop_embedding_level (bidi_it);
1581 else
1582 {
1583 bidi_it->invalid_levels--;
1584 bidi_it->invalid_rl_levels--;
1585 }
1586 }
1587 }
1588
b7b65b15
EZ
1589 if (bidi_it->type == NEUTRAL_B) /* X8 */
1590 {
21fce5ab 1591 bidi_set_paragraph_end (bidi_it);
6bff6497
EZ
1592 /* This is needed by bidi_resolve_weak below, and in L1. */
1593 bidi_it->type_after_w1 = bidi_it->type;
89d3374a 1594 bidi_check_type (bidi_it->type_after_w1);
b7b65b15
EZ
1595 }
1596
1597 return new_level;
1598}
1599
182ce2d2
EZ
1600/* Advance in the buffer/string, resolve weak types and return the
1601 type of the next character after weak type resolution. */
fd3998ff 1602static bidi_type_t
b7b65b15
EZ
1603bidi_resolve_weak (struct bidi_it *bidi_it)
1604{
1605 bidi_type_t type;
1606 bidi_dir_t override;
1607 int prev_level = bidi_it->level_stack[bidi_it->stack_idx].level;
1608 int new_level = bidi_resolve_explicit (bidi_it);
1609 int next_char;
1610 bidi_type_t type_of_next;
1611 struct bidi_it saved_it;
5895d7b9 1612 ptrdiff_t eob
512a289d
RS
1613 = ((STRINGP (bidi_it->string.lstring) || bidi_it->string.s)
1614 ? bidi_it->string.schars : ZV);
b7b65b15
EZ
1615
1616 type = bidi_it->type;
1617 override = bidi_it->level_stack[bidi_it->stack_idx].override;
1618
1619 if (type == UNKNOWN_BT
1620 || type == LRE
1621 || type == LRO
1622 || type == RLE
1623 || type == RLO
1624 || type == PDF)
1625 abort ();
1626
1627 if (new_level != prev_level
1628 || bidi_it->type == NEUTRAL_B)
1629 {
1630 /* We've got a new embedding level run, compute the directional
1631 type of sor and initialize per-run variables (UAX#9, clause
1632 X10). */
1633 bidi_set_sor_type (bidi_it, prev_level, new_level);
1634 }
1635 else if (type == NEUTRAL_S || type == NEUTRAL_WS
1636 || type == WEAK_BN || type == STRONG_AL)
89d3374a
EZ
1637 bidi_it->type_after_w1 = type; /* needed in L1 */
1638 bidi_check_type (bidi_it->type_after_w1);
b7b65b15
EZ
1639
1640 /* Level and directional override status are already recorded in
1641 bidi_it, and do not need any change; see X6. */
1642 if (override == R2L) /* X6 */
1643 type = STRONG_R;
1644 else if (override == L2R)
1645 type = STRONG_L;
bc5a45f3 1646 else
b7b65b15 1647 {
bc5a45f3 1648 if (type == WEAK_NSM) /* W1 */
b7b65b15 1649 {
bc5a45f3 1650 /* Note that we don't need to consider the case where the
5930fe97
EZ
1651 prev character has its type overridden by an RLO or LRO,
1652 because then either the type of this NSM would have been
1653 also overridden, or the previous character is outside the
1654 current level run, and thus not relevant to this NSM.
1655 This is why NSM gets the type_after_w1 of the previous
1656 character. */
ebb5722e
EZ
1657 if (bidi_it->prev.type_after_w1 != UNKNOWN_BT
1658 /* if type_after_w1 is NEUTRAL_B, this NSM is at sor */
1659 && bidi_it->prev.type_after_w1 != NEUTRAL_B)
5930fe97 1660 type = bidi_it->prev.type_after_w1;
bc5a45f3
EZ
1661 else if (bidi_it->sor == R2L)
1662 type = STRONG_R;
1663 else if (bidi_it->sor == L2R)
1664 type = STRONG_L;
1665 else /* shouldn't happen! */
1666 abort ();
b7b65b15 1667 }
bc5a45f3
EZ
1668 if (type == WEAK_EN /* W2 */
1669 && bidi_it->last_strong.type_after_w1 == STRONG_AL)
1670 type = WEAK_AN;
1671 else if (type == STRONG_AL) /* W3 */
1672 type = STRONG_R;
1673 else if ((type == WEAK_ES /* W4 */
1674 && bidi_it->prev.type_after_w1 == WEAK_EN
1675 && bidi_it->prev.orig_type == WEAK_EN)
1676 || (type == WEAK_CS
1677 && ((bidi_it->prev.type_after_w1 == WEAK_EN
1678 && bidi_it->prev.orig_type == WEAK_EN)
1679 || bidi_it->prev.type_after_w1 == WEAK_AN)))
b7b65b15 1680 {
512a289d
RS
1681 const unsigned char *s
1682 = (STRINGP (bidi_it->string.lstring)
1683 ? SDATA (bidi_it->string.lstring)
1684 : bidi_it->string.s);
1685
1686 next_char = (bidi_it->charpos + bidi_it->nchars >= eob
1687 ? BIDI_EOB
1688 : bidi_char_at_pos (bidi_it->bytepos + bidi_it->ch_len,
1689 s, bidi_it->string.unibyte));
6bff6497 1690 type_of_next = bidi_get_type (next_char, override);
b7b65b15 1691
bc5a45f3 1692 if (type_of_next == WEAK_BN
b7b65b15
EZ
1693 || bidi_explicit_dir_char (next_char))
1694 {
1695 bidi_copy_it (&saved_it, bidi_it);
1696 while (bidi_resolve_explicit (bidi_it) == new_level
bc5a45f3 1697 && bidi_it->type == WEAK_BN)
b7b65b15
EZ
1698 ;
1699 type_of_next = bidi_it->type;
b7b65b15
EZ
1700 bidi_copy_it (bidi_it, &saved_it);
1701 }
bc5a45f3
EZ
1702
1703 /* If the next character is EN, but the last strong-type
1704 character is AL, that next EN will be changed to AN when
1705 we process it in W2 above. So in that case, this ES
1706 should not be changed into EN. */
1707 if (type == WEAK_ES
1708 && type_of_next == WEAK_EN
1709 && bidi_it->last_strong.type_after_w1 != STRONG_AL)
1710 type = WEAK_EN;
1711 else if (type == WEAK_CS)
b7b65b15 1712 {
bc5a45f3
EZ
1713 if (bidi_it->prev.type_after_w1 == WEAK_AN
1714 && (type_of_next == WEAK_AN
1715 /* If the next character is EN, but the last
1716 strong-type character is AL, EN will be later
1717 changed to AN when we process it in W2 above.
1718 So in that case, this ES should not be
1719 changed into EN. */
1720 || (type_of_next == WEAK_EN
1721 && bidi_it->last_strong.type_after_w1 == STRONG_AL)))
1722 type = WEAK_AN;
1723 else if (bidi_it->prev.type_after_w1 == WEAK_EN
1724 && type_of_next == WEAK_EN
1725 && bidi_it->last_strong.type_after_w1 != STRONG_AL)
1726 type = WEAK_EN;
1727 }
1728 }
1729 else if (type == WEAK_ET /* W5: ET with EN before or after it */
1730 || type == WEAK_BN) /* W5/Retaining */
1731 {
7b5d6677 1732 if (bidi_it->prev.type_after_w1 == WEAK_EN) /* ET/BN w/EN before it */
bc5a45f3 1733 type = WEAK_EN;
7b5d6677
EZ
1734 else if (bidi_it->next_en_pos > bidi_it->charpos
1735 && bidi_it->next_en_type != WEAK_BN)
1736 {
1737 if (bidi_it->next_en_type == WEAK_EN) /* ET/BN with EN after it */
1738 type = WEAK_EN;
1739 }
1740 else if (bidi_it->next_en_pos >=0)
bc5a45f3 1741 {
d311d28c 1742 ptrdiff_t en_pos = bidi_it->charpos + bidi_it->nchars;
512a289d
RS
1743 const unsigned char *s = (STRINGP (bidi_it->string.lstring)
1744 ? SDATA (bidi_it->string.lstring)
1745 : bidi_it->string.s);
bc5a45f3 1746
102ebb00
EZ
1747 if (bidi_it->nchars <= 0)
1748 abort ();
512a289d
RS
1749 next_char
1750 = (bidi_it->charpos + bidi_it->nchars >= eob
1751 ? BIDI_EOB
1752 : bidi_char_at_pos (bidi_it->bytepos + bidi_it->ch_len, s,
1753 bidi_it->string.unibyte));
bc5a45f3
EZ
1754 type_of_next = bidi_get_type (next_char, override);
1755
1756 if (type_of_next == WEAK_ET
1757 || type_of_next == WEAK_BN
1758 || bidi_explicit_dir_char (next_char))
1759 {
1760 bidi_copy_it (&saved_it, bidi_it);
1761 while (bidi_resolve_explicit (bidi_it) == new_level
1762 && (bidi_it->type == WEAK_BN
1763 || bidi_it->type == WEAK_ET))
1764 ;
1765 type_of_next = bidi_it->type;
1766 en_pos = bidi_it->charpos;
1767 bidi_copy_it (bidi_it, &saved_it);
1768 }
7b5d6677
EZ
1769 /* Remember this position, to speed up processing of the
1770 next ETs. */
1771 bidi_it->next_en_pos = en_pos;
bc5a45f3 1772 if (type_of_next == WEAK_EN)
b7b65b15 1773 {
bc5a45f3
EZ
1774 /* If the last strong character is AL, the EN we've
1775 found will become AN when we get to it (W2). */
7b5d6677
EZ
1776 if (bidi_it->last_strong.type_after_w1 == STRONG_AL)
1777 type_of_next = WEAK_AN;
bc5a45f3
EZ
1778 else if (type == WEAK_BN)
1779 type = NEUTRAL_ON; /* W6/Retaining */
7b5d6677
EZ
1780 else
1781 type = WEAK_EN;
b7b65b15 1782 }
4787455f
EZ
1783 else if (type_of_next == NEUTRAL_B)
1784 /* Record the fact that there are no more ENs from
1785 here to the end of paragraph, to avoid entering the
1786 loop above ever again in this paragraph. */
1787 bidi_it->next_en_pos = -1;
7b5d6677
EZ
1788 /* Record the type of the character where we ended our search. */
1789 bidi_it->next_en_type = type_of_next;
b7b65b15
EZ
1790 }
1791 }
1792 }
1793
1794 if (type == WEAK_ES || type == WEAK_ET || type == WEAK_CS /* W6 */
89d3374a
EZ
1795 || (type == WEAK_BN
1796 && (bidi_it->prev.type_after_w1 == WEAK_CS /* W6/Retaining */
1797 || bidi_it->prev.type_after_w1 == WEAK_ES
1798 || bidi_it->prev.type_after_w1 == WEAK_ET)))
b7b65b15
EZ
1799 type = NEUTRAL_ON;
1800
1801 /* Store the type we've got so far, before we clobber it with strong
1802 types in W7 and while resolving neutral types. But leave alone
1803 the original types that were recorded above, because we will need
1804 them for the L1 clause. */
89d3374a
EZ
1805 if (bidi_it->type_after_w1 == UNKNOWN_BT)
1806 bidi_it->type_after_w1 = type;
1807 bidi_check_type (bidi_it->type_after_w1);
b7b65b15
EZ
1808
1809 if (type == WEAK_EN) /* W7 */
1810 {
89d3374a 1811 if ((bidi_it->last_strong.type_after_w1 == STRONG_L)
b7b65b15
EZ
1812 || (bidi_it->last_strong.type == UNKNOWN_BT && bidi_it->sor == L2R))
1813 type = STRONG_L;
1814 }
1815
1816 bidi_it->type = type;
2d6e4628 1817 bidi_check_type (bidi_it->type);
b7b65b15
EZ
1818 return type;
1819}
1820
cbb09f04
EZ
1821/* Resolve the type of a neutral character according to the type of
1822 surrounding strong text and the current embedding level. */
58b9f433 1823static inline bidi_type_t
cbb09f04
EZ
1824bidi_resolve_neutral_1 (bidi_type_t prev_type, bidi_type_t next_type, int lev)
1825{
1826 /* N1: European and Arabic numbers are treated as though they were R. */
1827 if (next_type == WEAK_EN || next_type == WEAK_AN)
1828 next_type = STRONG_R;
1829 if (prev_type == WEAK_EN || prev_type == WEAK_AN)
1830 prev_type = STRONG_R;
1831
1832 if (next_type == prev_type) /* N1 */
1833 return next_type;
1834 else if ((lev & 1) == 0) /* N2 */
1835 return STRONG_L;
1836 else
1837 return STRONG_R;
1838}
1839
fd3998ff 1840static bidi_type_t
b7b65b15
EZ
1841bidi_resolve_neutral (struct bidi_it *bidi_it)
1842{
1843 int prev_level = bidi_it->level_stack[bidi_it->stack_idx].level;
1844 bidi_type_t type = bidi_resolve_weak (bidi_it);
1845 int current_level = bidi_it->level_stack[bidi_it->stack_idx].level;
1846
1847 if (!(type == STRONG_R
1848 || type == STRONG_L
1849 || type == WEAK_BN
1850 || type == WEAK_EN
1851 || type == WEAK_AN
1852 || type == NEUTRAL_B
1853 || type == NEUTRAL_S
1854 || type == NEUTRAL_WS
1855 || type == NEUTRAL_ON))
1856 abort ();
1857
4787455f
EZ
1858 if ((type != NEUTRAL_B /* Don't risk entering the long loop below if
1859 we are already at paragraph end. */
1860 && bidi_get_category (type) == NEUTRAL)
b7b65b15
EZ
1861 || (type == WEAK_BN && prev_level == current_level))
1862 {
1863 if (bidi_it->next_for_neutral.type != UNKNOWN_BT)
1864 type = bidi_resolve_neutral_1 (bidi_it->prev_for_neutral.type,
1865 bidi_it->next_for_neutral.type,
1866 current_level);
4787455f
EZ
1867 /* The next two "else if" clauses are shortcuts for the
1868 important special case when we have a long sequence of
1869 neutral or WEAK_BN characters, such as whitespace or nulls or
1870 other control characters, on the base embedding level of the
1871 paragraph, and that sequence goes all the way to the end of
1872 the paragraph and follows a character whose resolved
1873 directionality is identical to the base embedding level.
1874 (This is what happens in a buffer with plain L2R text that
1875 happens to include long sequences of control characters.) By
1876 virtue of N1, the result of examining this long sequence will
1877 always be either STRONG_L or STRONG_R, depending on the base
1878 embedding level. So we use this fact directly instead of
1879 entering the expensive loop in the "else" clause. */
1880 else if (current_level == 0
1881 && bidi_it->prev_for_neutral.type == STRONG_L
1882 && !bidi_explicit_dir_char (bidi_it->ch))
1883 type = bidi_resolve_neutral_1 (bidi_it->prev_for_neutral.type,
1884 STRONG_L, current_level);
1885 else if (/* current level is 1 */
1886 current_level == 1
1887 /* base embedding level is also 1 */
1888 && bidi_it->level_stack[0].level == 1
1889 /* previous character is one of those considered R for
1890 the purposes of W5 */
1891 && (bidi_it->prev_for_neutral.type == STRONG_R
1892 || bidi_it->prev_for_neutral.type == WEAK_EN
1893 || bidi_it->prev_for_neutral.type == WEAK_AN)
1894 && !bidi_explicit_dir_char (bidi_it->ch))
1895 type = bidi_resolve_neutral_1 (bidi_it->prev_for_neutral.type,
1896 STRONG_R, current_level);
b7b65b15
EZ
1897 else
1898 {
1899 /* Arrrgh!! The UAX#9 algorithm is too deeply entrenched in
1900 the assumption of batch-style processing; see clauses W4,
1901 W5, and especially N1, which require to look far forward
182ce2d2
EZ
1902 (as well as back) in the buffer/string. May the fleas of
1903 a thousand camels infest the armpits of those who design
b7b65b15
EZ
1904 supposedly general-purpose algorithms by looking at their
1905 own implementations, and fail to consider other possible
1906 implementations! */
1907 struct bidi_it saved_it;
1908 bidi_type_t next_type;
1909
1910 if (bidi_it->scan_dir == -1)
1911 abort ();
1912
1913 bidi_copy_it (&saved_it, bidi_it);
1914 /* Scan the text forward until we find the first non-neutral
1915 character, and then use that to resolve the neutral we
1916 are dealing with now. We also cache the scanned iterator
1917 states, to salvage some of the effort later. */
1918 bidi_cache_iterator_state (bidi_it, 0);
1919 do {
1920 /* Record the info about the previous character, so that
1921 it will be cached below with this state. */
89d3374a 1922 if (bidi_it->type_after_w1 != WEAK_BN /* W1/Retaining */
b7b65b15
EZ
1923 && bidi_it->type != WEAK_BN)
1924 bidi_remember_char (&bidi_it->prev, bidi_it);
1925 type = bidi_resolve_weak (bidi_it);
1926 /* Paragraph separators have their levels fully resolved
1927 at this point, so cache them as resolved. */
1928 bidi_cache_iterator_state (bidi_it, type == NEUTRAL_B);
1929 /* FIXME: implement L1 here, by testing for a newline and
1930 resetting the level for any sequence of whitespace
1931 characters adjacent to it. */
1932 } while (!(type == NEUTRAL_B
1933 || (type != WEAK_BN
1934 && bidi_get_category (type) != NEUTRAL)
1935 /* This is all per level run, so stop when we
1936 reach the end of this level run. */
512a289d
RS
1937 || (bidi_it->level_stack[bidi_it->stack_idx].level
1938 != current_level)));
b7b65b15
EZ
1939
1940 bidi_remember_char (&saved_it.next_for_neutral, bidi_it);
1941
1942 switch (type)
1943 {
1944 case STRONG_L:
1945 case STRONG_R:
1946 case STRONG_AL:
4787455f
EZ
1947 /* Actually, STRONG_AL cannot happen here, because
1948 bidi_resolve_weak converts it to STRONG_R, per W3. */
1949 xassert (type != STRONG_AL);
b7b65b15
EZ
1950 next_type = type;
1951 break;
1952 case WEAK_EN:
1953 case WEAK_AN:
1954 /* N1: ``European and Arabic numbers are treated as
1955 though they were R.'' */
1956 next_type = STRONG_R;
b7b65b15
EZ
1957 break;
1958 case WEAK_BN:
1959 if (!bidi_explicit_dir_char (bidi_it->ch))
1960 abort (); /* can't happen: BNs are skipped */
1961 /* FALLTHROUGH */
1962 case NEUTRAL_B:
1963 /* Marched all the way to the end of this level run.
1964 We need to use the eor type, whose information is
1965 stored by bidi_set_sor_type in the prev_for_neutral
1966 member. */
1967 if (saved_it.type != WEAK_BN
89d3374a 1968 || bidi_get_category (bidi_it->prev.type_after_w1) == NEUTRAL)
4787455f 1969 next_type = bidi_it->prev_for_neutral.type;
b7b65b15
EZ
1970 else
1971 {
1972 /* This is a BN which does not adjoin neutrals.
1973 Leave its type alone. */
1974 bidi_copy_it (bidi_it, &saved_it);
1975 return bidi_it->type;
1976 }
1977 break;
1978 default:
1979 abort ();
1980 }
1981 type = bidi_resolve_neutral_1 (saved_it.prev_for_neutral.type,
1982 next_type, current_level);
4787455f 1983 saved_it.next_for_neutral.type = next_type;
b7b65b15 1984 saved_it.type = type;
4787455f 1985 bidi_check_type (next_type);
2d6e4628 1986 bidi_check_type (type);
b7b65b15
EZ
1987 bidi_copy_it (bidi_it, &saved_it);
1988 }
1989 }
1990 return type;
1991}
1992
1993/* Given an iterator state in BIDI_IT, advance one character position
182ce2d2
EZ
1994 in the buffer/string to the next character (in the logical order),
1995 resolve the bidi type of that next character, and return that
1996 type. */
fd3998ff 1997static bidi_type_t
b7b65b15
EZ
1998bidi_type_of_next_char (struct bidi_it *bidi_it)
1999{
2000 bidi_type_t type;
2001
2002 /* This should always be called during a forward scan. */
2003 if (bidi_it->scan_dir != 1)
2004 abort ();
2005
2006 /* Reset the limit until which to ignore BNs if we step out of the
2007 area where we found only empty levels. */
87e67904 2008 if ((bidi_it->ignore_bn_limit > -1
b7b65b15 2009 && bidi_it->ignore_bn_limit <= bidi_it->charpos)
87e67904 2010 || (bidi_it->ignore_bn_limit == -2
b7b65b15 2011 && !bidi_explicit_dir_char (bidi_it->ch)))
87e67904 2012 bidi_it->ignore_bn_limit = -1;
b7b65b15
EZ
2013
2014 type = bidi_resolve_neutral (bidi_it);
2015
2016 return type;
2017}
2018
2019/* Given an iterator state BIDI_IT, advance one character position in
182ce2d2
EZ
2020 the buffer/string to the next character (in the current scan
2021 direction), resolve the embedding and implicit levels of that next
2022 character, and return the resulting level. */
fd3998ff 2023static int
b7b65b15
EZ
2024bidi_level_of_next_char (struct bidi_it *bidi_it)
2025{
2026 bidi_type_t type;
2027 int level, prev_level = -1;
2028 struct bidi_saved_info next_for_neutral;
d311d28c 2029 ptrdiff_t next_char_pos = -2;
b7b65b15
EZ
2030
2031 if (bidi_it->scan_dir == 1)
2032 {
5895d7b9 2033 ptrdiff_t eob
512a289d
RS
2034 = ((bidi_it->string.s || STRINGP (bidi_it->string.lstring))
2035 ? bidi_it->string.schars : ZV);
9f257352 2036
b7b65b15 2037 /* There's no sense in trying to advance if we hit end of text. */
9f257352 2038 if (bidi_it->charpos >= eob)
b7b65b15
EZ
2039 return bidi_it->resolved_level;
2040
2041 /* Record the info about the previous character. */
89d3374a 2042 if (bidi_it->type_after_w1 != WEAK_BN /* W1/Retaining */
b7b65b15
EZ
2043 && bidi_it->type != WEAK_BN)
2044 bidi_remember_char (&bidi_it->prev, bidi_it);
89d3374a
EZ
2045 if (bidi_it->type_after_w1 == STRONG_R
2046 || bidi_it->type_after_w1 == STRONG_L
2047 || bidi_it->type_after_w1 == STRONG_AL)
b7b65b15
EZ
2048 bidi_remember_char (&bidi_it->last_strong, bidi_it);
2049 /* FIXME: it sounds like we don't need both prev and
2050 prev_for_neutral members, but I'm leaving them both for now. */
2051 if (bidi_it->type == STRONG_R || bidi_it->type == STRONG_L
2052 || bidi_it->type == WEAK_EN || bidi_it->type == WEAK_AN)
2053 bidi_remember_char (&bidi_it->prev_for_neutral, bidi_it);
2054
2055 /* If we overstepped the characters used for resolving neutrals
2056 and whitespace, invalidate their info in the iterator. */
2057 if (bidi_it->charpos >= bidi_it->next_for_neutral.charpos)
2058 bidi_it->next_for_neutral.type = UNKNOWN_BT;
2059 if (bidi_it->next_en_pos >= 0
2060 && bidi_it->charpos >= bidi_it->next_en_pos)
7b5d6677
EZ
2061 {
2062 bidi_it->next_en_pos = 0;
2063 bidi_it->next_en_type = UNKNOWN_BT;
2064 }
b7b65b15
EZ
2065 if (bidi_it->next_for_ws.type != UNKNOWN_BT
2066 && bidi_it->charpos >= bidi_it->next_for_ws.charpos)
2067 bidi_it->next_for_ws.type = UNKNOWN_BT;
2068
2069 /* This must be taken before we fill the iterator with the info
2070 about the next char. If we scan backwards, the iterator
2071 state must be already cached, so there's no need to know the
2072 embedding level of the previous character, since we will be
2073 returning to our caller shortly. */
2074 prev_level = bidi_it->level_stack[bidi_it->stack_idx].level;
2075 }
2076 next_for_neutral = bidi_it->next_for_neutral;
2077
182ce2d2
EZ
2078 /* Perhaps the character we want is already cached. If it is, the
2079 call to bidi_cache_find below will return a type other than
2080 UNKNOWN_BT. */
87e67904 2081 if (bidi_cache_idx > bidi_cache_start && !bidi_it->first_elt)
102ebb00 2082 {
512a289d
RS
2083 int bob = ((bidi_it->string.s || STRINGP (bidi_it->string.lstring))
2084 ? 0 : 1);
102ebb00
EZ
2085 if (bidi_it->scan_dir > 0)
2086 {
2087 if (bidi_it->nchars <= 0)
2088 abort ();
2089 next_char_pos = bidi_it->charpos + bidi_it->nchars;
2090 }
9f257352 2091 else if (bidi_it->charpos >= bob)
bb269206
EZ
2092 /* Implementation note: we allow next_char_pos to be as low as
2093 0 for buffers or -1 for strings, and that is okay because
2094 that's the "position" of the sentinel iterator state we
2095 cached at the beginning of the iteration. */
102ebb00 2096 next_char_pos = bidi_it->charpos - 1;
578b494e 2097 if (next_char_pos >= bob - 1)
87e67904
EZ
2098 type = bidi_cache_find (next_char_pos, -1, bidi_it);
2099 else
2100 type = UNKNOWN_BT;
102ebb00 2101 }
182ce2d2 2102 else
102ebb00 2103 type = UNKNOWN_BT;
b7b65b15
EZ
2104 if (type != UNKNOWN_BT)
2105 {
2106 /* Don't lose the information for resolving neutrals! The
2107 cached states could have been cached before their
2108 next_for_neutral member was computed. If we are on our way
2109 forward, we can simply take the info from the previous
2110 state. */
2111 if (bidi_it->scan_dir == 1
2112 && bidi_it->next_for_neutral.type == UNKNOWN_BT)
2113 bidi_it->next_for_neutral = next_for_neutral;
2114
2115 /* If resolved_level is -1, it means this state was cached
2116 before it was completely resolved, so we cannot return
2117 it. */
2118 if (bidi_it->resolved_level != -1)
2119 return bidi_it->resolved_level;
2120 }
2121 if (bidi_it->scan_dir == -1)
2122 /* If we are going backwards, the iterator state is already cached
2123 from previous scans, and should be fully resolved. */
2124 abort ();
2125
2126 if (type == UNKNOWN_BT)
2127 type = bidi_type_of_next_char (bidi_it);
2128
2129 if (type == NEUTRAL_B)
2130 return bidi_it->resolved_level;
2131
2132 level = bidi_it->level_stack[bidi_it->stack_idx].level;
2133 if ((bidi_get_category (type) == NEUTRAL /* && type != NEUTRAL_B */)
2134 || (type == WEAK_BN && prev_level == level))
2135 {
2136 if (bidi_it->next_for_neutral.type == UNKNOWN_BT)
2137 abort ();
2138
2139 /* If the cached state shows a neutral character, it was not
2140 resolved by bidi_resolve_neutral, so do it now. */
2141 type = bidi_resolve_neutral_1 (bidi_it->prev_for_neutral.type,
2142 bidi_it->next_for_neutral.type,
2143 level);
2144 }
2145
2146 if (!(type == STRONG_R
2147 || type == STRONG_L
2148 || type == WEAK_BN
2149 || type == WEAK_EN
2150 || type == WEAK_AN))
2151 abort ();
2152 bidi_it->type = type;
2d6e4628 2153 bidi_check_type (bidi_it->type);
b7b65b15
EZ
2154
2155 /* For L1 below, we need to know, for each WS character, whether
0d327994 2156 it belongs to a sequence of WS characters preceding a newline
b7b65b15 2157 or a TAB or a paragraph separator. */
89d3374a 2158 if (bidi_it->orig_type == NEUTRAL_WS
b7b65b15
EZ
2159 && bidi_it->next_for_ws.type == UNKNOWN_BT)
2160 {
2161 int ch;
d311d28c
PE
2162 ptrdiff_t clen = bidi_it->ch_len;
2163 ptrdiff_t bpos = bidi_it->bytepos;
2164 ptrdiff_t cpos = bidi_it->charpos;
2165 ptrdiff_t disp_pos = bidi_it->disp_pos;
2166 ptrdiff_t nc = bidi_it->nchars;
87e67904 2167 struct bidi_string_data bs = bidi_it->string;
b7b65b15 2168 bidi_type_t chtype;
fc6f18ce 2169 int fwp = bidi_it->frame_window_p;
0c95fcf7 2170 int dpp = bidi_it->disp_prop;
b7b65b15 2171
102ebb00
EZ
2172 if (bidi_it->nchars <= 0)
2173 abort ();
b7b65b15 2174 do {
55439c61
EZ
2175 ch = bidi_fetch_char (bpos += clen, cpos += nc, &disp_pos, &dpp, &bs,
2176 fwp, &clen, &nc);
79beb178 2177 if (ch == '\n' || ch == BIDI_EOB)
b7b65b15
EZ
2178 chtype = NEUTRAL_B;
2179 else
6bff6497 2180 chtype = bidi_get_type (ch, NEUTRAL_DIR);
b7b65b15
EZ
2181 } while (chtype == NEUTRAL_WS || chtype == WEAK_BN
2182 || bidi_explicit_dir_char (ch)); /* L1/Retaining */
2183 bidi_it->next_for_ws.type = chtype;
2d6e4628 2184 bidi_check_type (bidi_it->next_for_ws.type);
b7b65b15
EZ
2185 bidi_it->next_for_ws.charpos = cpos;
2186 bidi_it->next_for_ws.bytepos = bpos;
2187 }
2188
2189 /* Resolve implicit levels, with a twist: PDFs get the embedding
55622b93 2190 level of the embedding they terminate. See below for the
b7b65b15 2191 reason. */
89d3374a 2192 if (bidi_it->orig_type == PDF
b7b65b15
EZ
2193 /* Don't do this if this formatting code didn't change the
2194 embedding level due to invalid or empty embeddings. */
2195 && prev_level != level)
2196 {
2197 /* Don't look in UAX#9 for the reason for this: it's our own
2198 private quirk. The reason is that we want the formatting
2199 codes to be delivered so that they bracket the text of their
2200 embedding. For example, given the text
2201
2202 {RLO}teST{PDF}
2203
2204 we want it to be displayed as
2205
0d68907d 2206 {PDF}STet{RLO}
b7b65b15
EZ
2207
2208 not as
2209
2210 STet{RLO}{PDF}
2211
2212 which will result because we bump up the embedding level as
2213 soon as we see the RLO and pop it as soon as we see the PDF,
2214 so RLO itself has the same embedding level as "teST", and
2215 thus would be normally delivered last, just before the PDF.
2216 The switch below fiddles with the level of PDF so that this
2217 ugly side effect does not happen.
2218
2219 (This is, of course, only important if the formatting codes
e7402cb2
EZ
2220 are actually displayed, but Emacs does need to display them
2221 if the user wants to.) */
b7b65b15
EZ
2222 level = prev_level;
2223 }
89d3374a
EZ
2224 else if (bidi_it->orig_type == NEUTRAL_B /* L1 */
2225 || bidi_it->orig_type == NEUTRAL_S
e7402cb2 2226 || bidi_it->ch == '\n' || bidi_it->ch == BIDI_EOB
89d3374a 2227 || (bidi_it->orig_type == NEUTRAL_WS
b7b65b15
EZ
2228 && (bidi_it->next_for_ws.type == NEUTRAL_B
2229 || bidi_it->next_for_ws.type == NEUTRAL_S)))
2230 level = bidi_it->level_stack[0].level;
2231 else if ((level & 1) == 0) /* I1 */
2232 {
2233 if (type == STRONG_R)
2234 level++;
2235 else if (type == WEAK_EN || type == WEAK_AN)
2236 level += 2;
2237 }
2238 else /* I2 */
2239 {
2240 if (type == STRONG_L || type == WEAK_EN || type == WEAK_AN)
2241 level++;
2242 }
2243
2244 bidi_it->resolved_level = level;
2245 return level;
2246}
2247
2248/* Move to the other edge of a level given by LEVEL. If END_FLAG is
2249 non-zero, we are at the end of a level, and we need to prepare to
2250 resume the scan of the lower level.
2251
2252 If this level's other edge is cached, we simply jump to it, filling
2253 the iterator structure with the iterator state on the other edge.
182ce2d2
EZ
2254 Otherwise, we walk the buffer or string until we come back to the
2255 same level as LEVEL.
b7b65b15
EZ
2256
2257 Note: we are not talking here about a ``level run'' in the UAX#9
2258 sense of the term, but rather about a ``level'' which includes
2259 all the levels higher than it. In other words, given the levels
2260 like this:
2261
2262 11111112222222333333334443343222222111111112223322111
2263 A B C
2264
2265 and assuming we are at point A scanning left to right, this
2266 function moves to point C, whereas the UAX#9 ``level 2 run'' ends
2267 at point B. */
2268static void
2269bidi_find_other_level_edge (struct bidi_it *bidi_it, int level, int end_flag)
2270{
2271 int dir = end_flag ? -bidi_it->scan_dir : bidi_it->scan_dir;
39e378da 2272 ptrdiff_t idx;
b7b65b15
EZ
2273
2274 /* Try the cache first. */
87e67904
EZ
2275 if ((idx = bidi_cache_find_level_change (level, dir, end_flag))
2276 >= bidi_cache_start)
b7b65b15
EZ
2277 bidi_cache_fetch_state (idx, bidi_it);
2278 else
2279 {
2280 int new_level;
2281
2282 if (end_flag)
2283 abort (); /* if we are at end of level, its edges must be cached */
2284
2285 bidi_cache_iterator_state (bidi_it, 1);
2286 do {
2287 new_level = bidi_level_of_next_char (bidi_it);
2288 bidi_cache_iterator_state (bidi_it, 1);
2289 } while (new_level >= level);
2290 }
2291}
2292
2293void
4b292a22 2294bidi_move_to_visually_next (struct bidi_it *bidi_it)
b7b65b15
EZ
2295{
2296 int old_level, new_level, next_level;
9c82e145 2297 struct bidi_it sentinel;
acb28818 2298 struct gcpro gcpro1;
b7b65b15 2299
87e67904
EZ
2300 if (bidi_it->charpos < 0 || bidi_it->bytepos < 0)
2301 abort ();
b7b65b15
EZ
2302
2303 if (bidi_it->scan_dir == 0)
2304 {
2305 bidi_it->scan_dir = 1; /* default to logical order */
2306 }
2307
acb28818 2308 /* The code below can call eval, and thus cause GC. If we are
7e2ad32c 2309 iterating a Lisp string, make sure it won't be GCed. */
acb28818
EZ
2310 if (STRINGP (bidi_it->string.lstring))
2311 GCPRO1 (bidi_it->string.lstring);
2312
be39f003 2313 /* If we just passed a newline, initialize for the next line. */
1137e8b8
EZ
2314 if (!bidi_it->first_elt
2315 && (bidi_it->ch == '\n' || bidi_it->ch == BIDI_EOB))
be39f003
EZ
2316 bidi_line_init (bidi_it);
2317
6dcfd253
EZ
2318 /* Prepare the sentinel iterator state, and cache it. When we bump
2319 into it, scanning backwards, we'll know that the last non-base
2320 level is exhausted. */
87e67904 2321 if (bidi_cache_idx == bidi_cache_start)
9c82e145
EZ
2322 {
2323 bidi_copy_it (&sentinel, bidi_it);
2324 if (bidi_it->first_elt)
2325 {
2326 sentinel.charpos--; /* cached charpos needs to be monotonic */
2327 sentinel.bytepos--;
2328 sentinel.ch = '\n'; /* doesn't matter, but why not? */
2329 sentinel.ch_len = 1;
182ce2d2 2330 sentinel.nchars = 1;
9c82e145 2331 }
6dcfd253 2332 bidi_cache_iterator_state (&sentinel, 1);
9c82e145 2333 }
b7b65b15
EZ
2334
2335 old_level = bidi_it->resolved_level;
2336 new_level = bidi_level_of_next_char (bidi_it);
b7b65b15
EZ
2337
2338 /* Reordering of resolved levels (clause L2) is implemented by
2339 jumping to the other edge of the level and flipping direction of
c0546589 2340 scanning the text whenever we find a level change. */
b7b65b15
EZ
2341 if (new_level != old_level)
2342 {
2343 int ascending = new_level > old_level;
2344 int level_to_search = ascending ? old_level + 1 : old_level;
2345 int incr = ascending ? 1 : -1;
2346 int expected_next_level = old_level + incr;
2347
b7b65b15
EZ
2348 /* Jump (or walk) to the other edge of this level. */
2349 bidi_find_other_level_edge (bidi_it, level_to_search, !ascending);
2350 /* Switch scan direction and peek at the next character in the
2351 new direction. */
2352 bidi_it->scan_dir = -bidi_it->scan_dir;
2353
2354 /* The following loop handles the case where the resolved level
2355 jumps by more than one. This is typical for numbers inside a
2356 run of text with left-to-right embedding direction, but can
2357 also happen in other situations. In those cases the decision
2358 where to continue after a level change, and in what direction,
2359 is tricky. For example, given a text like below:
2360
2361 abcdefgh
2362 11336622
2363
2364 (where the numbers below the text show the resolved levels),
2365 the result of reordering according to UAX#9 should be this:
2366
2367 efdcghba
2368
2369 This is implemented by the loop below which flips direction
2370 and jumps to the other edge of the level each time it finds
2371 the new level not to be the expected one. The expected level
2372 is always one more or one less than the previous one. */
2373 next_level = bidi_peek_at_next_level (bidi_it);
2374 while (next_level != expected_next_level)
2375 {
2376 expected_next_level += incr;
2377 level_to_search += incr;
2378 bidi_find_other_level_edge (bidi_it, level_to_search, !ascending);
2379 bidi_it->scan_dir = -bidi_it->scan_dir;
2380 next_level = bidi_peek_at_next_level (bidi_it);
2381 }
2382
2383 /* Finally, deliver the next character in the new direction. */
2384 next_level = bidi_level_of_next_char (bidi_it);
2385 }
2386
b44d9321
EZ
2387 /* Take note when we have just processed the newline that precedes
2388 the end of the paragraph. The next time we are about to be
2389 called, set_iterator_to_next will automatically reinit the
2390 paragraph direction, if needed. We do this at the newline before
2391 the paragraph separator, because the next character might not be
2392 the first character of the next paragraph, due to the bidi
c0546589
EZ
2393 reordering, whereas we _must_ know the paragraph base direction
2394 _before_ we process the paragraph's text, since the base
2395 direction affects the reordering. */
1137e8b8
EZ
2396 if (bidi_it->scan_dir == 1
2397 && (bidi_it->ch == '\n' || bidi_it->ch == BIDI_EOB))
be39f003 2398 {
87e67904
EZ
2399 /* The paragraph direction of the entire string, once
2400 determined, is in effect for the entire string. Setting the
2401 separator limit to the end of the string prevents
2402 bidi_paragraph_init from being called automatically on this
2403 string. */
9f257352 2404 if (bidi_it->string.s || STRINGP (bidi_it->string.lstring))
87e67904
EZ
2405 bidi_it->separator_limit = bidi_it->string.schars;
2406 else if (bidi_it->bytepos < ZV_BYTE)
be39f003 2407 {
5895d7b9 2408 ptrdiff_t sep_len
512a289d
RS
2409 = bidi_at_paragraph_end (bidi_it->charpos + bidi_it->nchars,
2410 bidi_it->bytepos + bidi_it->ch_len);
87e67904
EZ
2411 if (bidi_it->nchars <= 0)
2412 abort ();
2413 if (sep_len >= 0)
2414 {
2415 bidi_it->new_paragraph = 1;
2416 /* Record the buffer position of the last character of the
2417 paragraph separator. */
512a289d
RS
2418 bidi_it->separator_limit
2419 = bidi_it->charpos + bidi_it->nchars + sep_len;
87e67904 2420 }
be39f003
EZ
2421 }
2422 }
6bff6497 2423
87e67904 2424 if (bidi_it->scan_dir == 1 && bidi_cache_idx > bidi_cache_start)
b7b65b15
EZ
2425 {
2426 /* If we are at paragraph's base embedding level and beyond the
2427 last cached position, the cache's job is done and we can
2428 discard it. */
2429 if (bidi_it->resolved_level == bidi_it->level_stack[0].level
182ce2d2
EZ
2430 && bidi_it->charpos > (bidi_cache[bidi_cache_idx - 1].charpos
2431 + bidi_cache[bidi_cache_idx - 1].nchars - 1))
b7b65b15
EZ
2432 bidi_cache_reset ();
2433 /* But as long as we are caching during forward scan, we must
2434 cache each state, or else the cache integrity will be
2435 compromised: it assumes cached states correspond to buffer
2436 positions 1:1. */
2437 else
2438 bidi_cache_iterator_state (bidi_it, 1);
2439 }
acb28818
EZ
2440
2441 if (STRINGP (bidi_it->string.lstring))
2442 UNGCPRO;
b7b65b15
EZ
2443}
2444
2445/* This is meant to be called from within the debugger, whenever you
2446 wish to examine the cache contents. */
e78aecca 2447void bidi_dump_cached_states (void) EXTERNALLY_VISIBLE;
b7b65b15
EZ
2448void
2449bidi_dump_cached_states (void)
2450{
39e378da 2451 ptrdiff_t i;
b7b65b15
EZ
2452 int ndigits = 1;
2453
2454 if (bidi_cache_idx == 0)
2455 {
2456 fprintf (stderr, "The cache is empty.\n");
2457 return;
2458 }
df9733bf 2459 fprintf (stderr, "Total of %"pD"d state%s in cache:\n",
b7b65b15
EZ
2460 bidi_cache_idx, bidi_cache_idx == 1 ? "" : "s");
2461
2462 for (i = bidi_cache[bidi_cache_idx - 1].charpos; i > 0; i /= 10)
2463 ndigits++;
2464 fputs ("ch ", stderr);
2465 for (i = 0; i < bidi_cache_idx; i++)
2466 fprintf (stderr, "%*c", ndigits, bidi_cache[i].ch);
2467 fputs ("\n", stderr);
2468 fputs ("lvl ", stderr);
2469 for (i = 0; i < bidi_cache_idx; i++)
2470 fprintf (stderr, "%*d", ndigits, bidi_cache[i].resolved_level);
2471 fputs ("\n", stderr);
2472 fputs ("pos ", stderr);
2473 for (i = 0; i < bidi_cache_idx; i++)
7c85f529 2474 fprintf (stderr, "%*"pD"d", ndigits, bidi_cache[i].charpos);
b7b65b15
EZ
2475 fputs ("\n", stderr);
2476}