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