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