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