Bind grep-highlight-matches around the rgrep call
[emacs.git] / src / composite.c
blob1c18165599df5cccd9100fc8dd5852c86a9b1bd2
1 /* Composite sequence support.
2 Copyright (C) 2001-2015 Free Software Foundation, Inc.
3 Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011
4 National Institute of Advanced Industrial Science and Technology (AIST)
5 Registration Number H14PRO021
6 Copyright (C) 2003, 2006
7 National Institute of Advanced Industrial Science and Technology (AIST)
8 Registration Number H13PRO009
10 This file is part of GNU Emacs.
12 GNU Emacs is free software: you can redistribute it and/or modify
13 it under the terms of the GNU General Public License as published by
14 the Free Software Foundation, either version 3 of the License, or
15 (at your option) any later version.
17 GNU Emacs is distributed in the hope that it will be useful,
18 but WITHOUT ANY WARRANTY; without even the implied warranty of
19 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 GNU General Public License for more details.
22 You should have received a copy of the GNU General Public License
23 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
25 #include <config.h>
27 #include "lisp.h"
28 #include "character.h"
29 #include "buffer.h"
30 #include "coding.h"
31 #include "intervals.h"
32 #include "window.h"
33 #include "frame.h"
34 #include "dispextern.h"
35 #include "font.h"
36 #include "termhooks.h"
39 /* Emacs uses special text property `composition' to support character
40 composition. A sequence of characters that have the same (i.e. eq)
41 `composition' property value is treated as a single composite
42 sequence (we call it just `composition' here after). Characters in
43 a composition are all composed somehow on the screen.
45 The property value has this form when the composition is made:
46 ((LENGTH . COMPONENTS) . MODIFICATION-FUNC)
47 then turns to this form:
48 (COMPOSITION-ID . (LENGTH COMPONENTS-VEC . MODIFICATION-FUNC))
49 when the composition is registered in composition_hash_table and
50 composition_table. These rather peculiar structures were designed
51 to make it easy to distinguish them quickly (we can do that by
52 checking only the first element) and to extract LENGTH (from the
53 former form) and COMPOSITION-ID (from the latter form).
55 We register a composition when it is displayed, or when the width
56 is required (for instance, to calculate columns).
58 LENGTH -- Length of the composition. This information is used to
59 check the validity of the composition.
61 COMPONENTS -- Character, string, vector, list, or nil.
63 If it is nil, characters in the text are composed relatively
64 according to their metrics in font glyphs.
66 If it is a character or a string, the character or characters
67 in the string are composed relatively.
69 If it is a vector or list of integers, the element is a
70 character or an encoded composition rule. The characters are
71 composed according to the rules. (2N)th elements are
72 characters to be composed and (2N+1)th elements are
73 composition rules to tell how to compose (2N+2)th element with
74 the previously composed 2N glyphs.
76 COMPONENTS-VEC -- Vector of integers. In a relative composition,
77 the elements are the characters to be composed. In a rule-base
78 composition, the elements are characters or encoded
79 composition rules.
81 MODIFICATION-FUNC -- If non nil, it is a function to call when the
82 composition gets invalid after a modification in a buffer. If
83 it is nil, a function in `composition-function-table' of the
84 first character in the sequence is called.
86 COMPOSITION-ID --Identification number of the composition. It is
87 used as an index to composition_table for the composition.
89 When Emacs has to display a composition or has to know its
90 displaying width, the function get_composition_id is called. It
91 returns COMPOSITION-ID so that the caller can access the
92 information about the composition through composition_table. If a
93 COMPOSITION-ID has not yet been assigned to the composition,
94 get_composition_id checks the validity of `composition' property,
95 and, if valid, assigns a new ID, registers the information in
96 composition_hash_table and composition_table, and changes the form
97 of the property value. If the property is invalid,
98 get_composition_id returns -1 without changing the property value.
100 We use two tables to keep the information about composition;
101 composition_hash_table and composition_table.
103 The former is a hash table whose keys are COMPONENTS-VECs and
104 values are the corresponding COMPOSITION-IDs. This hash table is
105 weak, but as each key (COMPONENTS-VEC) is also kept as a value of the
106 `composition' property, it won't be collected as garbage until all
107 bits of text that have the same COMPONENTS-VEC are deleted.
109 The latter is a table of pointers to `struct composition' indexed
110 by COMPOSITION-ID. This structure keeps the other information (see
111 composite.h).
113 In general, a text property holds information about individual
114 characters. But, a `composition' property holds information about
115 a sequence of characters (in this sense, it is like the `intangible'
116 property). That means that we should not share the property value
117 in adjacent compositions -- we can't distinguish them if they have the
118 same property. So, after any changes, we call
119 `update_compositions' and change a property of one of adjacent
120 compositions to a copy of it. This function also runs a proper
121 composition modification function to make a composition that gets
122 invalid by the change valid again.
124 As the value of the `composition' property holds information about a
125 specific range of text, the value gets invalid if we change the
126 text in the range. We treat the `composition' property as always
127 rear-nonsticky (currently by setting default-text-properties to
128 (rear-nonsticky (composition))) and we never make properties of
129 adjacent compositions identical. Thus, any such changes make the
130 range just shorter. So, we can check the validity of the `composition'
131 property by comparing LENGTH information with the actual length of
132 the composition.
137 /* Table of pointers to the structure `composition' indexed by
138 COMPOSITION-ID. This structure is for storing information about
139 each composition except for COMPONENTS-VEC. */
140 struct composition **composition_table;
142 /* The current size of `composition_table'. */
143 static ptrdiff_t composition_table_size;
145 /* Number of compositions currently made. */
146 ptrdiff_t n_compositions;
148 /* Hash table for compositions. The key is COMPONENTS-VEC of
149 `composition' property. The value is the corresponding
150 COMPOSITION-ID. */
151 Lisp_Object composition_hash_table;
153 /* Maximum number of characters to look back for
154 auto-compositions. */
155 #define MAX_AUTO_COMPOSITION_LOOKBACK 3
157 /* Return COMPOSITION-ID of a composition at buffer position
158 CHARPOS/BYTEPOS and length NCHARS. The `composition' property of
159 the sequence is PROP. STRING, if non-nil, is a string that
160 contains the composition instead of the current buffer.
162 If the composition is invalid, return -1. */
164 ptrdiff_t
165 get_composition_id (ptrdiff_t charpos, ptrdiff_t bytepos, ptrdiff_t nchars,
166 Lisp_Object prop, Lisp_Object string)
168 Lisp_Object id, length, components, key, *key_contents;
169 ptrdiff_t glyph_len;
170 struct Lisp_Hash_Table *hash_table = XHASH_TABLE (composition_hash_table);
171 ptrdiff_t hash_index;
172 EMACS_UINT hash_code;
173 enum composition_method method;
174 struct composition *cmp;
175 ptrdiff_t i;
176 int ch;
178 /* Maximum length of a string of glyphs. XftGlyphExtents limits
179 this to INT_MAX, and Emacs limits it further. Divide INT_MAX - 1
180 by 2 because x_produce_glyphs computes glyph_len * 2 + 1. Divide
181 the size by MAX_MULTIBYTE_LENGTH because encode_terminal_code
182 multiplies glyph_len by MAX_MULTIBYTE_LENGTH. */
183 enum {
184 GLYPH_LEN_MAX = min ((INT_MAX - 1) / 2,
185 min (PTRDIFF_MAX, SIZE_MAX) / MAX_MULTIBYTE_LENGTH)
188 /* PROP should be
189 Form-A: ((LENGTH . COMPONENTS) . MODIFICATION-FUNC)
191 Form-B: (COMPOSITION-ID . (LENGTH COMPONENTS-VEC . MODIFICATION-FUNC))
193 if (nchars == 0 || !CONSP (prop))
194 goto invalid_composition;
196 id = XCAR (prop);
197 if (INTEGERP (id))
199 /* PROP should be Form-B. */
200 if (XINT (id) < 0 || XINT (id) >= n_compositions)
201 goto invalid_composition;
202 return XINT (id);
205 /* PROP should be Form-A.
206 Thus, ID should be (LENGTH . COMPONENTS). */
207 if (!CONSP (id))
208 goto invalid_composition;
209 length = XCAR (id);
210 if (!INTEGERP (length) || XINT (length) != nchars)
211 goto invalid_composition;
213 components = XCDR (id);
215 /* Check if the same composition has already been registered or not
216 by consulting composition_hash_table. The key for this table is
217 COMPONENTS (converted to a vector COMPONENTS-VEC) or, if it is
218 nil, vector of characters in the composition range. */
219 if (INTEGERP (components))
220 key = Fmake_vector (make_number (1), components);
221 else if (STRINGP (components) || CONSP (components))
222 key = Fvconcat (1, &components);
223 else if (VECTORP (components))
224 key = components;
225 else if (NILP (components))
227 key = make_uninit_vector (nchars);
228 if (STRINGP (string))
229 for (i = 0; i < nchars; i++)
231 FETCH_STRING_CHAR_ADVANCE (ch, string, charpos, bytepos);
232 ASET (key, i, make_number (ch));
234 else
235 for (i = 0; i < nchars; i++)
237 FETCH_CHAR_ADVANCE (ch, charpos, bytepos);
238 ASET (key, i, make_number (ch));
241 else
242 goto invalid_composition;
244 hash_index = hash_lookup (hash_table, key, &hash_code);
245 if (hash_index >= 0)
247 /* We have already registered the same composition. Change PROP
248 from Form-A above to Form-B while replacing COMPONENTS with
249 COMPONENTS-VEC stored in the hash table. We can directly
250 modify the cons cell of PROP because it is not shared. */
251 key = HASH_KEY (hash_table, hash_index);
252 id = HASH_VALUE (hash_table, hash_index);
253 XSETCAR (prop, id);
254 XSETCDR (prop, Fcons (make_number (nchars), Fcons (key, XCDR (prop))));
255 return XINT (id);
258 /* This composition is a new one. We must register it. */
260 /* Check if we have sufficient memory to store this information. */
261 if (composition_table_size <= n_compositions)
262 composition_table = xpalloc (composition_table, &composition_table_size,
263 1, -1, sizeof *composition_table);
265 key_contents = XVECTOR (key)->contents;
267 /* Check if the contents of COMPONENTS are valid if COMPONENTS is a
268 vector or a list. It should be a sequence of:
269 char1 rule1 char2 rule2 char3 ... ruleN charN+1 */
271 if (VECTORP (components)
272 && ASIZE (components) >= 2
273 && VECTORP (AREF (components, 0)))
275 /* COMPONENTS is a glyph-string. */
276 ptrdiff_t len = ASIZE (key);
278 for (i = 1; i < len; i++)
279 if (! VECTORP (AREF (key, i)))
280 goto invalid_composition;
282 else if (VECTORP (components) || CONSP (components))
284 ptrdiff_t len = ASIZE (key);
286 /* The number of elements should be odd. */
287 if ((len % 2) == 0)
288 goto invalid_composition;
289 /* All elements should be integers (character or encoded
290 composition rule). */
291 for (i = 0; i < len; i++)
293 if (!INTEGERP (key_contents[i]))
294 goto invalid_composition;
298 /* Change PROP from Form-A above to Form-B. We can directly modify
299 the cons cell of PROP because it is not shared. */
300 XSETFASTINT (id, n_compositions);
301 XSETCAR (prop, id);
302 XSETCDR (prop, Fcons (make_number (nchars), Fcons (key, XCDR (prop))));
304 /* Register the composition in composition_hash_table. */
305 hash_index = hash_put (hash_table, key, id, hash_code);
307 method = (NILP (components)
308 ? COMPOSITION_RELATIVE
309 : ((INTEGERP (components) || STRINGP (components))
310 ? COMPOSITION_WITH_ALTCHARS
311 : COMPOSITION_WITH_RULE_ALTCHARS));
313 glyph_len = (method == COMPOSITION_WITH_RULE_ALTCHARS
314 ? (ASIZE (key) + 1) / 2
315 : ASIZE (key));
317 if (GLYPH_LEN_MAX < glyph_len)
318 memory_full (SIZE_MAX);
320 /* Register the composition in composition_table. */
321 cmp = xmalloc (sizeof *cmp);
323 cmp->method = method;
324 cmp->hash_index = hash_index;
325 cmp->glyph_len = glyph_len;
326 cmp->offsets = xnmalloc (glyph_len, 2 * sizeof *cmp->offsets);
327 cmp->font = NULL;
329 if (cmp->method != COMPOSITION_WITH_RULE_ALTCHARS)
331 /* Relative composition. */
332 cmp->width = 0;
333 for (i = 0; i < glyph_len; i++)
335 int this_width;
336 ch = XINT (key_contents[i]);
337 /* TAB in a composition means display glyphs with padding
338 space on the left or right. */
339 this_width = (ch == '\t' ? 1 : CHAR_WIDTH (ch));
340 if (cmp->width < this_width)
341 cmp->width = this_width;
344 else
346 /* Rule-base composition. */
347 double leftmost = 0.0, rightmost;
349 ch = XINT (key_contents[0]);
350 rightmost = ch != '\t' ? CHAR_WIDTH (ch) : 1;
352 for (i = 1; i < glyph_len; i += 2)
354 int rule, gref, nref;
355 int this_width;
356 double this_left;
358 rule = XINT (key_contents[i]);
359 ch = XINT (key_contents[i + 1]);
360 this_width = ch != '\t' ? CHAR_WIDTH (ch) : 1;
362 /* A composition rule is specified by an integer value
363 that encodes global and new reference points (GREF and
364 NREF). GREF and NREF are specified by numbers as
365 below:
366 0---1---2 -- ascent
370 9--10--11 -- center
372 ---3---4---5--- baseline
374 6---7---8 -- descent
376 COMPOSITION_DECODE_REFS (rule, gref, nref);
377 this_left = (leftmost
378 + (gref % 3) * (rightmost - leftmost) / 2.0
379 - (nref % 3) * this_width / 2.0);
381 if (this_left < leftmost)
382 leftmost = this_left;
383 if (this_left + this_width > rightmost)
384 rightmost = this_left + this_width;
387 cmp->width = rightmost - leftmost;
388 if (cmp->width < (rightmost - leftmost))
389 /* To get a ceiling integer value. */
390 cmp->width++;
393 composition_table[n_compositions] = cmp;
395 return n_compositions++;
397 invalid_composition:
398 /* Would it be better to remove this `composition' property? */
399 return -1;
403 /* Find a static composition at or nearest to position POS of OBJECT
404 (buffer or string).
406 OBJECT defaults to the current buffer. If there's a composition at
407 POS, set *START and *END to the start and end of the sequence,
408 *PROP to the `composition' property, and return 1.
410 If there's no composition at POS and LIMIT is negative, return 0.
412 Otherwise, search for a composition forward (LIMIT > POS) or
413 backward (LIMIT < POS). In this case, LIMIT bounds the search.
415 If a composition is found, set *START, *END, and *PROP as above,
416 and return 1, else return 0.
418 This doesn't check the validity of composition. */
420 bool
421 find_composition (ptrdiff_t pos, ptrdiff_t limit,
422 ptrdiff_t *start, ptrdiff_t *end,
423 Lisp_Object *prop, Lisp_Object object)
425 Lisp_Object val;
427 if (get_property_and_range (pos, Qcomposition, prop, start, end, object))
428 return 1;
430 if (limit < 0 || limit == pos)
431 return 0;
433 if (limit > pos) /* search forward */
435 val = Fnext_single_property_change (make_number (pos), Qcomposition,
436 object, make_number (limit));
437 pos = XINT (val);
438 if (pos == limit)
439 return 0;
441 else /* search backward */
443 if (get_property_and_range (pos - 1, Qcomposition, prop, start, end,
444 object))
445 return 1;
446 val = Fprevious_single_property_change (make_number (pos), Qcomposition,
447 object, make_number (limit));
448 pos = XINT (val);
449 if (pos == limit)
450 return 0;
451 pos--;
453 get_property_and_range (pos, Qcomposition, prop, start, end, object);
454 return 1;
457 /* Run a proper function to adjust the composition sitting between
458 FROM and TO with property PROP. */
460 static void
461 run_composition_function (ptrdiff_t from, ptrdiff_t to, Lisp_Object prop)
463 Lisp_Object func;
464 ptrdiff_t start, end;
466 func = COMPOSITION_MODIFICATION_FUNC (prop);
467 /* If an invalid composition precedes or follows, try to make them
468 valid too. */
469 if (from > BEGV
470 && find_composition (from - 1, -1, &start, &end, &prop, Qnil)
471 && !composition_valid_p (start, end, prop))
472 from = start;
473 if (to < ZV
474 && find_composition (to, -1, &start, &end, &prop, Qnil)
475 && !composition_valid_p (start, end, prop))
476 to = end;
477 if (!NILP (Ffboundp (func)))
478 call2 (func, make_number (from), make_number (to));
481 /* Make invalid compositions adjacent to or inside FROM and TO valid.
482 CHECK_MASK is bitwise `or' of mask bits defined by macros
483 CHECK_XXX (see the comment in composite.h).
485 It also resets the text-property `auto-composed' to a proper region
486 so that automatic character composition works correctly later while
487 displaying the region.
489 This function is called when a buffer text is changed. If the
490 change is deletion, FROM == TO. Otherwise, FROM < TO. */
492 void
493 update_compositions (ptrdiff_t from, ptrdiff_t to, int check_mask)
495 Lisp_Object prop;
496 ptrdiff_t start, end;
497 /* The beginning and end of the region to set the property
498 `auto-composed' to nil. */
499 ptrdiff_t min_pos = from, max_pos = to;
501 if (inhibit_modification_hooks)
502 return;
504 /* If FROM and TO are not in a valid range, do nothing. */
505 if (! (BEGV <= from && from <= to && to <= ZV))
506 return;
508 if (check_mask & CHECK_HEAD)
510 /* FROM should be at composition boundary. But, insertion or
511 deletion will make two compositions adjacent and
512 indistinguishable when they have same (eq) property. To
513 avoid it, in such a case, we change the property of the
514 latter to the copy of it. */
515 if (from > BEGV
516 && find_composition (from - 1, -1, &start, &end, &prop, Qnil)
517 && composition_valid_p (start, end, prop))
519 min_pos = start;
520 if (end > to)
521 max_pos = end;
522 if (from < end)
523 Fput_text_property (make_number (from), make_number (end),
524 Qcomposition,
525 Fcons (XCAR (prop), XCDR (prop)), Qnil);
526 run_composition_function (start, end, prop);
527 from = end;
529 else if (from < ZV
530 && find_composition (from, -1, &start, &from, &prop, Qnil)
531 && composition_valid_p (start, from, prop))
533 if (from > to)
534 max_pos = from;
535 run_composition_function (start, from, prop);
539 if (check_mask & CHECK_INSIDE)
541 /* In this case, we are sure that (check & CHECK_TAIL) is also
542 nonzero. Thus, here we should check only compositions before
543 (to - 1). */
544 while (from < to - 1
545 && find_composition (from, to, &start, &from, &prop, Qnil)
546 && composition_valid_p (start, from, prop)
547 && from < to - 1)
548 run_composition_function (start, from, prop);
551 if (check_mask & CHECK_TAIL)
553 if (from < to
554 && find_composition (to - 1, -1, &start, &end, &prop, Qnil)
555 && composition_valid_p (start, end, prop))
557 /* TO should be also at composition boundary. But,
558 insertion or deletion will make two compositions adjacent
559 and indistinguishable when they have same (eq) property.
560 To avoid it, in such a case, we change the property of
561 the former to the copy of it. */
562 if (to < end)
564 Fput_text_property (make_number (start), make_number (to),
565 Qcomposition,
566 Fcons (XCAR (prop), XCDR (prop)), Qnil);
567 max_pos = end;
569 run_composition_function (start, end, prop);
571 else if (to < ZV
572 && find_composition (to, -1, &start, &end, &prop, Qnil)
573 && composition_valid_p (start, end, prop))
575 run_composition_function (start, end, prop);
576 max_pos = end;
579 if (min_pos < max_pos)
581 ptrdiff_t count = SPECPDL_INDEX ();
583 specbind (Qinhibit_read_only, Qt);
584 specbind (Qinhibit_modification_hooks, Qt);
585 specbind (Qinhibit_point_motion_hooks, Qt);
586 Fremove_list_of_text_properties (make_number (min_pos),
587 make_number (max_pos),
588 list1 (Qauto_composed), Qnil);
589 unbind_to (count, Qnil);
594 /* Modify composition property values in LIST destructively. LIST is
595 a list as returned from text_property_list. Change values to the
596 top-level copies of them so that none of them are `eq'. */
598 void
599 make_composition_value_copy (Lisp_Object list)
601 Lisp_Object plist, val;
603 for (; CONSP (list); list = XCDR (list))
605 plist = XCAR (XCDR (XCDR (XCAR (list))));
606 while (CONSP (plist) && CONSP (XCDR (plist)))
608 if (EQ (XCAR (plist), Qcomposition)
609 && (val = XCAR (XCDR (plist)), CONSP (val)))
610 XSETCAR (XCDR (plist), Fcons (XCAR (val), XCDR (val)));
611 plist = XCDR (XCDR (plist));
617 /* Make text in the region between START and END a composition that
618 has COMPONENTS and MODIFICATION-FUNC.
620 If STRING is non-nil, then operate on characters contained between
621 indices START and END in STRING. */
623 void
624 compose_text (ptrdiff_t start, ptrdiff_t end, Lisp_Object components,
625 Lisp_Object modification_func, Lisp_Object string)
627 Lisp_Object prop;
629 prop = Fcons (Fcons (make_number (end - start), components),
630 modification_func);
631 Fput_text_property (make_number (start), make_number (end),
632 Qcomposition, prop, string);
635 /* Lisp glyph-string handlers. */
637 /* Hash table for automatic composition. The key is a header of a
638 lgstring (Lispy glyph-string), and the value is a body of a
639 lgstring. */
641 static Lisp_Object gstring_hash_table;
643 static Lisp_Object gstring_lookup_cache (Lisp_Object);
645 static Lisp_Object
646 gstring_lookup_cache (Lisp_Object header)
648 struct Lisp_Hash_Table *h = XHASH_TABLE (gstring_hash_table);
649 ptrdiff_t i = hash_lookup (h, header, NULL);
651 return (i >= 0 ? HASH_VALUE (h, i) : Qnil);
654 Lisp_Object
655 composition_gstring_put_cache (Lisp_Object gstring, ptrdiff_t len)
657 struct Lisp_Hash_Table *h = XHASH_TABLE (gstring_hash_table);
658 EMACS_UINT hash;
659 Lisp_Object header, copy;
660 ptrdiff_t i;
662 header = LGSTRING_HEADER (gstring);
663 hash = h->test.hashfn (&h->test, header);
664 if (len < 0)
666 ptrdiff_t j, glyph_len = LGSTRING_GLYPH_LEN (gstring);
667 for (j = 0; j < glyph_len; j++)
668 if (NILP (LGSTRING_GLYPH (gstring, j)))
669 break;
670 len = j;
673 copy = Fmake_vector (make_number (len + 2), Qnil);
674 LGSTRING_SET_HEADER (copy, Fcopy_sequence (header));
675 for (i = 0; i < len; i++)
676 LGSTRING_SET_GLYPH (copy, i, Fcopy_sequence (LGSTRING_GLYPH (gstring, i)));
677 i = hash_put (h, LGSTRING_HEADER (copy), copy, hash);
678 LGSTRING_SET_ID (copy, make_number (i));
679 return copy;
682 Lisp_Object
683 composition_gstring_from_id (ptrdiff_t id)
685 struct Lisp_Hash_Table *h = XHASH_TABLE (gstring_hash_table);
687 return HASH_VALUE (h, id);
690 bool
691 composition_gstring_p (Lisp_Object gstring)
693 Lisp_Object header;
694 ptrdiff_t i;
696 if (! VECTORP (gstring) || ASIZE (gstring) < 2)
697 return 0;
698 header = LGSTRING_HEADER (gstring);
699 if (! VECTORP (header) || ASIZE (header) < 2)
700 return 0;
701 if (! NILP (LGSTRING_FONT (gstring))
702 && (! FONT_OBJECT_P (LGSTRING_FONT (gstring))
703 && ! CODING_SYSTEM_P (LGSTRING_FONT (gstring))))
704 return 0;
705 for (i = 1; i < ASIZE (LGSTRING_HEADER (gstring)); i++)
706 if (! NATNUMP (AREF (LGSTRING_HEADER (gstring), i)))
707 return 0;
708 if (! NILP (LGSTRING_ID (gstring)) && ! NATNUMP (LGSTRING_ID (gstring)))
709 return 0;
710 for (i = 0; i < LGSTRING_GLYPH_LEN (gstring); i++)
712 Lisp_Object glyph = LGSTRING_GLYPH (gstring, i);
713 if (NILP (glyph))
714 break;
715 if (! VECTORP (glyph) || ASIZE (glyph) != LGLYPH_SIZE)
716 return 0;
718 return 1;
722 composition_gstring_width (Lisp_Object gstring, ptrdiff_t from, ptrdiff_t to,
723 struct font_metrics *metrics)
725 Lisp_Object *glyph;
726 int width = 0;
728 if (metrics)
730 Lisp_Object font_object = LGSTRING_FONT (gstring);
732 if (FONT_OBJECT_P (font_object))
734 struct font *font = XFONT_OBJECT (font_object);
735 int font_ascent, font_descent;
737 get_font_ascent_descent (font, &font_ascent, &font_descent);
738 metrics->ascent = font_ascent;
739 metrics->descent = font_descent;
741 else
743 metrics->ascent = 1;
744 metrics->descent = 0;
746 metrics->width = metrics->lbearing = metrics->rbearing = 0;
748 for (glyph = lgstring_glyph_addr (gstring, from); from < to; from++, glyph++)
750 int x;
752 if (NILP (LGLYPH_ADJUSTMENT (*glyph)))
753 width += LGLYPH_WIDTH (*glyph);
754 else
755 width += LGLYPH_WADJUST (*glyph);
756 if (metrics)
758 x = metrics->width + LGLYPH_LBEARING (*glyph) + LGLYPH_XOFF (*glyph);
759 if (metrics->lbearing > x)
760 metrics->lbearing = x;
761 x = metrics->width + LGLYPH_RBEARING (*glyph) + LGLYPH_XOFF (*glyph);
762 if (metrics->rbearing < x)
763 metrics->rbearing = x;
764 metrics->width = width;
765 x = LGLYPH_ASCENT (*glyph) - LGLYPH_YOFF (*glyph);
766 if (metrics->ascent < x)
767 metrics->ascent = x;
768 x = LGLYPH_DESCENT (*glyph) + LGLYPH_YOFF (*glyph);
769 if (metrics->descent < x)
770 metrics->descent = x;
773 return width;
777 static Lisp_Object gstring_work;
778 static Lisp_Object gstring_work_headers;
780 static Lisp_Object
781 fill_gstring_header (Lisp_Object header, ptrdiff_t from, ptrdiff_t from_byte,
782 ptrdiff_t to, Lisp_Object font_object, Lisp_Object string)
784 ptrdiff_t len = to - from, i;
786 if (len == 0)
787 error ("Attempt to shape zero-length text");
788 if (VECTORP (header))
790 if (ASIZE (header) != len + 1)
791 args_out_of_range (header, make_number (len + 1));
793 else
795 if (len <= 8)
796 header = AREF (gstring_work_headers, len - 1);
797 else
798 header = make_uninit_vector (len + 1);
801 ASET (header, 0, font_object);
802 for (i = 0; i < len; i++)
804 int c;
806 if (NILP (string))
807 FETCH_CHAR_ADVANCE_NO_CHECK (c, from, from_byte);
808 else
809 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c, string, from, from_byte);
810 ASET (header, i + 1, make_number (c));
812 return header;
815 static void
816 fill_gstring_body (Lisp_Object gstring)
818 Lisp_Object font_object = LGSTRING_FONT (gstring);
819 Lisp_Object header = AREF (gstring, 0);
820 ptrdiff_t len = LGSTRING_CHAR_LEN (gstring);
821 ptrdiff_t i;
823 for (i = 0; i < len; i++)
825 Lisp_Object g = LGSTRING_GLYPH (gstring, i);
826 int c = XFASTINT (AREF (header, i + 1));
828 if (NILP (g))
830 g = LGLYPH_NEW ();
831 LGSTRING_SET_GLYPH (gstring, i, g);
833 LGLYPH_SET_FROM (g, i);
834 LGLYPH_SET_TO (g, i);
835 LGLYPH_SET_CHAR (g, c);
836 if (FONT_OBJECT_P (font_object))
838 font_fill_lglyph_metrics (g, font_object);
840 else
842 int width = XFASTINT (CHAR_TABLE_REF (Vchar_width_table, c));
844 LGLYPH_SET_CODE (g, c);
845 LGLYPH_SET_LBEARING (g, 0);
846 LGLYPH_SET_RBEARING (g, width);
847 LGLYPH_SET_WIDTH (g, width);
848 LGLYPH_SET_ASCENT (g, 1);
849 LGLYPH_SET_DESCENT (g, 0);
851 LGLYPH_SET_ADJUSTMENT (g, Qnil);
853 if (i < LGSTRING_GLYPH_LEN (gstring))
854 LGSTRING_SET_GLYPH (gstring, i, Qnil);
858 /* Try to compose the characters at CHARPOS according to composition
859 rule RULE ([PATTERN PREV-CHARS FUNC]). LIMIT limits the characters
860 to compose. STRING, if not nil, is a target string. WIN is a
861 window where the characters are being displayed. If characters are
862 successfully composed, return the composition as a glyph-string
863 object. Otherwise return nil. */
865 static Lisp_Object
866 autocmp_chars (Lisp_Object rule, ptrdiff_t charpos, ptrdiff_t bytepos,
867 ptrdiff_t limit, struct window *win, struct face *face,
868 Lisp_Object string)
870 ptrdiff_t count = SPECPDL_INDEX ();
871 struct frame *f = XFRAME (win->frame);
872 Lisp_Object pos = make_number (charpos);
873 ptrdiff_t to;
874 ptrdiff_t pt = PT, pt_byte = PT_BYTE;
875 Lisp_Object re, font_object, lgstring;
876 ptrdiff_t len;
878 record_unwind_save_match_data ();
879 re = AREF (rule, 0);
880 if (NILP (re))
881 len = 1;
882 else if (! STRINGP (re))
883 return unbind_to (count, Qnil);
884 else if ((len = fast_looking_at (re, charpos, bytepos, limit, -1, string))
885 > 0)
887 if (NILP (string))
888 len = BYTE_TO_CHAR (bytepos + len) - charpos;
889 else
890 len = string_byte_to_char (string, bytepos + len) - charpos;
892 if (len <= 0)
893 return unbind_to (count, Qnil);
894 to = limit = charpos + len;
895 #ifdef HAVE_WINDOW_SYSTEM
896 if (FRAME_WINDOW_P (f))
898 font_object = font_range (charpos, bytepos, &to, win, face, string);
899 if (! FONT_OBJECT_P (font_object)
900 || (! NILP (re)
901 && to < limit
902 && (fast_looking_at (re, charpos, bytepos, to, -1, string) <= 0)))
903 return unbind_to (count, Qnil);
905 else
906 #endif /* not HAVE_WINDOW_SYSTEM */
907 font_object = win->frame;
908 lgstring = Fcomposition_get_gstring (pos, make_number (to), font_object,
909 string);
910 if (NILP (LGSTRING_ID (lgstring)))
912 /* Save point as marker before calling out to lisp. */
913 if (NILP (string))
914 record_unwind_protect (restore_point_unwind,
915 build_marker (current_buffer, pt, pt_byte));
916 lgstring = safe_call (6, Vauto_composition_function, AREF (rule, 2),
917 pos, make_number (to), font_object, string);
919 return unbind_to (count, lgstring);
922 /* 1 iff the character C is composable. Characters of general
923 category Z? or C? are not composable except for ZWNJ and ZWJ. */
925 static bool
926 char_composable_p (int c)
928 Lisp_Object val;
929 return (c > ' '
930 && (c == 0x200C || c == 0x200D
931 || (val = CHAR_TABLE_REF (Vunicode_category_table, c),
932 (INTEGERP (val) && (XINT (val) <= UNICODE_CATEGORY_So)))));
935 /* Update cmp_it->stop_pos to the next position after CHARPOS (and
936 BYTEPOS) where character composition may happen. If BYTEPOS is
937 negative, compute it. ENDPOS is a limit of searching. If it is
938 less than CHARPOS, search backward to ENDPOS+1 assuming that
939 set_iterator_to_next works in reverse order. In this case, if a
940 composition closest to CHARPOS is found, set cmp_it->stop_pos to
941 the last character of the composition.
943 If no composition is found, set cmp_it->ch to -2. If a static
944 composition is found, set cmp_it->ch to -1. Otherwise, set
945 cmp_it->ch to the character that triggers the automatic
946 composition. */
948 void
949 composition_compute_stop_pos (struct composition_it *cmp_it, ptrdiff_t charpos, ptrdiff_t bytepos, ptrdiff_t endpos, Lisp_Object string)
951 ptrdiff_t start, end;
952 int c;
953 Lisp_Object prop, val;
954 /* This is from forward_to_next_line_start in xdisp.c. */
955 const int MAX_NEWLINE_DISTANCE = 500;
957 if (charpos < endpos)
959 if (endpos > charpos + MAX_NEWLINE_DISTANCE)
960 endpos = charpos + MAX_NEWLINE_DISTANCE;
962 else if (endpos < charpos)
964 /* We search backward for a position to check composition. */
965 if (endpos < 0)
967 /* But we don't know where to stop the searching. */
968 endpos = NILP (string) ? BEGV - 1 : -1;
969 /* Usually we don't reach ENDPOS because we stop searching
970 at an uncomposable character (NL, LRE, etc). */
973 cmp_it->id = -1;
974 cmp_it->ch = -2;
975 cmp_it->reversed_p = 0;
976 cmp_it->stop_pos = endpos;
977 if (charpos == endpos)
978 return;
979 /* FIXME: Bidi is not yet handled well in static composition. */
980 if (charpos < endpos
981 && find_composition (charpos, endpos, &start, &end, &prop, string)
982 && start >= charpos
983 && composition_valid_p (start, end, prop))
985 cmp_it->stop_pos = endpos = start;
986 cmp_it->ch = -1;
988 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
989 || NILP (Vauto_composition_mode))
990 return;
991 if (bytepos < 0)
993 if (NILP (string))
994 bytepos = CHAR_TO_BYTE (charpos);
995 else
996 bytepos = string_char_to_byte (string, charpos);
999 start = charpos;
1000 if (charpos < endpos)
1002 /* Forward search. */
1003 while (charpos < endpos)
1005 if (STRINGP (string))
1006 FETCH_STRING_CHAR_ADVANCE (c, string, charpos, bytepos);
1007 else
1008 FETCH_CHAR_ADVANCE (c, charpos, bytepos);
1009 if (c == '\n')
1011 cmp_it->ch = -2;
1012 break;
1014 val = CHAR_TABLE_REF (Vcomposition_function_table, c);
1015 if (! NILP (val))
1017 for (int ridx = 0; CONSP (val); val = XCDR (val), ridx++)
1019 Lisp_Object elt = XCAR (val);
1020 if (VECTORP (elt) && ASIZE (elt) == 3
1021 && NATNUMP (AREF (elt, 1))
1022 && charpos - 1 - XFASTINT (AREF (elt, 1)) >= start)
1024 cmp_it->rule_idx = ridx;
1025 cmp_it->lookback = XFASTINT (AREF (elt, 1));
1026 cmp_it->stop_pos = charpos - 1 - cmp_it->lookback;
1027 cmp_it->ch = c;
1028 return;
1033 if (charpos == endpos
1034 && !(STRINGP (string) && endpos == SCHARS (string)))
1036 /* We couldn't find a composition point before ENDPOS. But,
1037 some character after ENDPOS may be composed with
1038 characters before ENDPOS. So, we should stop at the safe
1039 point. */
1040 charpos = endpos - MAX_AUTO_COMPOSITION_LOOKBACK;
1041 if (charpos < start)
1042 charpos = start;
1045 else if (charpos > endpos)
1047 /* Search backward for a pattern that may be composed and the
1048 position of (possibly) the last character of the match is
1049 closest to (but not after) START. The reason for the last
1050 character is that set_iterator_to_next works in reverse order,
1051 and thus we must stop at the last character for composition
1052 check. */
1053 unsigned char *p;
1054 int len;
1055 /* Limit byte position used in fast_looking_at. This is the
1056 byte position of the character after START. */
1057 ptrdiff_t limit;
1059 if (NILP (string))
1060 p = BYTE_POS_ADDR (bytepos);
1061 else
1062 p = SDATA (string) + bytepos;
1063 c = STRING_CHAR_AND_LENGTH (p, len);
1064 limit = bytepos + len;
1065 while (char_composable_p (c))
1067 val = CHAR_TABLE_REF (Vcomposition_function_table, c);
1068 if (! NILP (val))
1070 Lisp_Object elt;
1071 int ridx, blen;
1073 for (ridx = 0; CONSP (val); val = XCDR (val), ridx++)
1075 elt = XCAR (val);
1076 if (VECTORP (elt) && ASIZE (elt) == 3
1077 && NATNUMP (AREF (elt, 1))
1078 && charpos - XFASTINT (AREF (elt, 1)) > endpos)
1080 ptrdiff_t back = XFASTINT (AREF (elt, 1));
1081 ptrdiff_t cpos = charpos - back, bpos;
1083 if (back == 0)
1084 bpos = bytepos;
1085 else
1086 bpos = (NILP (string) ? CHAR_TO_BYTE (cpos)
1087 : string_char_to_byte (string, cpos));
1088 if (STRINGP (AREF (elt, 0)))
1089 blen = fast_looking_at (AREF (elt, 0), cpos, bpos,
1090 start + 1, limit, string);
1091 else
1092 blen = 1;
1093 if (blen > 0)
1095 /* Make CPOS point to the last character of
1096 match. Note that BLEN is byte-length. */
1097 if (blen > 1)
1099 bpos += blen;
1100 if (NILP (string))
1101 cpos = BYTE_TO_CHAR (bpos) - 1;
1102 else
1103 cpos = string_byte_to_char (string, bpos) - 1;
1105 back = cpos - (charpos - back);
1106 if (cmp_it->stop_pos < cpos
1107 || (cmp_it->stop_pos == cpos
1108 && cmp_it->lookback < back))
1110 cmp_it->rule_idx = ridx;
1111 cmp_it->stop_pos = cpos;
1112 cmp_it->ch = c;
1113 cmp_it->lookback = back;
1114 cmp_it->nchars = back + 1;
1120 if (charpos - 1 == endpos)
1121 break;
1122 if (STRINGP (string))
1124 p--, bytepos--;
1125 while (! CHAR_HEAD_P (*p))
1126 p--, bytepos--;
1127 charpos--;
1129 else
1131 DEC_BOTH (charpos, bytepos);
1132 p = BYTE_POS_ADDR (bytepos);
1134 c = STRING_CHAR (p);
1136 if (cmp_it->ch >= 0)
1137 /* We found a position to check. */
1138 return;
1139 /* Skip all uncomposable characters. */
1140 if (NILP (string))
1142 while (charpos - 1 > endpos && ! char_composable_p (c))
1144 DEC_BOTH (charpos, bytepos);
1145 c = FETCH_MULTIBYTE_CHAR (bytepos);
1148 else
1150 while (charpos - 1 > endpos && ! char_composable_p (c))
1152 p--;
1153 while (! CHAR_HEAD_P (*p))
1154 p--;
1155 charpos--;
1156 c = STRING_CHAR (p);
1160 cmp_it->stop_pos = charpos;
1163 /* Check if the character at CHARPOS (and BYTEPOS) is composed
1164 (possibly with the following characters) on window W. ENDPOS limits
1165 characters to be composed. FACE, if non-NULL, is a base face of
1166 the character. If STRING is not nil, it is a string containing the
1167 character to check, and CHARPOS and BYTEPOS are indices in the
1168 string. In that case, FACE must not be NULL.
1170 If the character is composed, setup members of CMP_IT (id, nglyphs,
1171 from, to, reversed_p), and return true. Otherwise, update
1172 CMP_IT->stop_pos, and return false. */
1174 bool
1175 composition_reseat_it (struct composition_it *cmp_it, ptrdiff_t charpos,
1176 ptrdiff_t bytepos, ptrdiff_t endpos, struct window *w,
1177 struct face *face, Lisp_Object string)
1179 if (cmp_it->ch == -2)
1181 composition_compute_stop_pos (cmp_it, charpos, bytepos, endpos, string);
1182 if (cmp_it->ch == -2 || cmp_it->stop_pos != charpos)
1183 /* The current position is not composed. */
1184 return 0;
1187 if (endpos < 0)
1188 endpos = NILP (string) ? BEGV : 0;
1190 if (cmp_it->ch < 0)
1192 /* We are looking at a static composition. */
1193 ptrdiff_t start, end;
1194 Lisp_Object prop;
1196 find_composition (charpos, -1, &start, &end, &prop, string);
1197 cmp_it->id = get_composition_id (charpos, bytepos, end - start,
1198 prop, string);
1199 if (cmp_it->id < 0)
1200 goto no_composition;
1201 cmp_it->nchars = end - start;
1202 cmp_it->nglyphs = composition_table[cmp_it->id]->glyph_len;
1204 else if (w)
1206 Lisp_Object lgstring = Qnil;
1207 Lisp_Object val, elt;
1208 ptrdiff_t i;
1210 val = CHAR_TABLE_REF (Vcomposition_function_table, cmp_it->ch);
1211 for (i = 0; i < cmp_it->rule_idx; i++, val = XCDR (val));
1212 if (charpos < endpos)
1214 for (; CONSP (val); val = XCDR (val))
1216 elt = XCAR (val);
1217 if (! VECTORP (elt) || ASIZE (elt) != 3
1218 || ! INTEGERP (AREF (elt, 1)))
1219 continue;
1220 if (XFASTINT (AREF (elt, 1)) != cmp_it->lookback)
1221 goto no_composition;
1222 lgstring = autocmp_chars (elt, charpos, bytepos, endpos,
1223 w, face, string);
1224 if (composition_gstring_p (lgstring))
1225 break;
1226 lgstring = Qnil;
1227 /* Composition failed perhaps because the font doesn't
1228 support sufficient range of characters. Try the
1229 other composition rules if any. */
1231 cmp_it->reversed_p = 0;
1233 else
1235 ptrdiff_t cpos = charpos, bpos = bytepos;
1237 cmp_it->reversed_p = 1;
1238 elt = XCAR (val);
1239 if (cmp_it->lookback > 0)
1241 cpos = charpos - cmp_it->lookback;
1242 if (STRINGP (string))
1243 bpos = string_char_to_byte (string, cpos);
1244 else
1245 bpos = CHAR_TO_BYTE (cpos);
1247 lgstring = autocmp_chars (elt, cpos, bpos, charpos + 1, w, face,
1248 string);
1249 if (! composition_gstring_p (lgstring)
1250 || cpos + LGSTRING_CHAR_LEN (lgstring) - 1 != charpos)
1251 /* Composition failed or didn't cover the current
1252 character. */
1253 goto no_composition;
1255 if (NILP (lgstring))
1256 goto no_composition;
1257 if (NILP (LGSTRING_ID (lgstring)))
1258 lgstring = composition_gstring_put_cache (lgstring, -1);
1259 cmp_it->id = XINT (LGSTRING_ID (lgstring));
1260 for (i = 0; i < LGSTRING_GLYPH_LEN (lgstring); i++)
1261 if (NILP (LGSTRING_GLYPH (lgstring, i)))
1262 break;
1263 cmp_it->nglyphs = i;
1264 cmp_it->from = 0;
1265 cmp_it->to = i;
1267 else
1268 goto no_composition;
1269 return 1;
1271 no_composition:
1272 if (charpos == endpos)
1273 return 0;
1274 if (charpos < endpos)
1276 charpos++;
1277 if (NILP (string))
1278 INC_POS (bytepos);
1279 else
1280 bytepos += BYTES_BY_CHAR_HEAD (*(SDATA (string) + bytepos));
1282 else
1284 charpos--;
1285 /* BYTEPOS is calculated in composition_compute_stop_pos */
1286 bytepos = -1;
1288 if (cmp_it->reversed_p)
1289 endpos = -1;
1290 composition_compute_stop_pos (cmp_it, charpos, bytepos, endpos, string);
1291 return 0;
1294 /* Update charpos, nchars, nbytes, and width of the current grapheme
1295 cluster.
1297 If the composition is static or automatic in L2R context, the
1298 cluster is identified by CMP_IT->from, and CHARPOS is the position
1299 of the first character of the cluster. In this case, update
1300 CMP_IT->to too.
1302 If the composition is automatic in R2L context, the cluster is
1303 identified by CMP_IT->to, and CHARPOS is the position of the last
1304 character of the cluster. In this case, update CMP_IT->from too.
1306 The return value is the character code of the first character of
1307 the cluster, or -1 if the composition is somehow broken. */
1310 composition_update_it (struct composition_it *cmp_it, ptrdiff_t charpos, ptrdiff_t bytepos, Lisp_Object string)
1312 int i, c IF_LINT (= 0);
1314 if (cmp_it->ch < 0)
1316 /* static composition */
1317 struct composition *cmp = composition_table[cmp_it->id];
1319 cmp_it->charpos = charpos;
1320 cmp_it->to = cmp_it->nglyphs;
1321 if (cmp_it->nglyphs == 0)
1322 c = -1;
1323 else
1325 for (i = 0; i < cmp->glyph_len; i++)
1326 /* TAB in a composition means display glyphs with padding
1327 space on the left or right. */
1328 if ((c = COMPOSITION_GLYPH (cmp, i)) != '\t')
1329 break;
1330 if (c == '\t')
1331 c = ' ';
1333 cmp_it->width = cmp->width;
1334 charpos += cmp_it->nchars;
1335 if (STRINGP (string))
1336 cmp_it->nbytes = string_char_to_byte (string, charpos) - bytepos;
1337 else
1338 cmp_it->nbytes = CHAR_TO_BYTE (charpos) - bytepos;
1340 else
1342 /* Automatic composition. */
1343 Lisp_Object gstring = composition_gstring_from_id (cmp_it->id);
1344 Lisp_Object glyph;
1345 ptrdiff_t from;
1347 if (cmp_it->nglyphs == 0)
1349 cmp_it->nchars = LGSTRING_CHAR_LEN (gstring);
1350 cmp_it->width = 0;
1351 cmp_it->from = cmp_it->to = 0;
1352 return -1;
1354 if (! cmp_it->reversed_p)
1356 glyph = LGSTRING_GLYPH (gstring, cmp_it->from);
1357 from = LGLYPH_FROM (glyph);
1358 for (cmp_it->to = cmp_it->from + 1; cmp_it->to < cmp_it->nglyphs;
1359 cmp_it->to++)
1361 glyph = LGSTRING_GLYPH (gstring, cmp_it->to);
1362 if (LGLYPH_FROM (glyph) != from)
1363 break;
1365 cmp_it->charpos = charpos;
1367 else
1369 glyph = LGSTRING_GLYPH (gstring, cmp_it->to - 1);
1370 from = LGLYPH_FROM (glyph);
1371 cmp_it->charpos = charpos - (LGLYPH_TO (glyph) - from);
1372 for (cmp_it->from = cmp_it->to - 1; cmp_it->from > 0;
1373 cmp_it->from--)
1375 glyph = LGSTRING_GLYPH (gstring, cmp_it->from - 1);
1376 if (LGLYPH_FROM (glyph) != from)
1377 break;
1380 glyph = LGSTRING_GLYPH (gstring, cmp_it->from);
1381 cmp_it->nchars = LGLYPH_TO (glyph) + 1 - from;
1382 cmp_it->nbytes = 0;
1383 cmp_it->width = 0;
1384 for (i = cmp_it->nchars - 1; i >= 0; i--)
1386 c = XINT (LGSTRING_CHAR (gstring, from + i));
1387 cmp_it->nbytes += CHAR_BYTES (c);
1388 cmp_it->width += CHAR_WIDTH (c);
1391 return c;
1395 struct position_record
1397 ptrdiff_t pos, pos_byte;
1398 unsigned char *p;
1401 /* Update the members of POSITION to the next character boundary. */
1402 #define FORWARD_CHAR(POSITION, STOP) \
1403 do { \
1404 (POSITION).pos++; \
1405 if ((POSITION).pos == (STOP)) \
1407 (POSITION).p = GAP_END_ADDR; \
1408 (POSITION).pos_byte = GPT_BYTE; \
1410 else \
1412 (POSITION).pos_byte += BYTES_BY_CHAR_HEAD (*((POSITION).p)); \
1413 (POSITION).p += BYTES_BY_CHAR_HEAD (*((POSITION).p)); \
1415 } while (0)
1417 /* Update the members of POSITION to the previous character boundary. */
1418 #define BACKWARD_CHAR(POSITION, STOP) \
1419 do { \
1420 if ((POSITION).pos == (STOP)) \
1421 (POSITION).p = GPT_ADDR; \
1422 do { \
1423 (POSITION).pos_byte--; \
1424 (POSITION).p--; \
1425 } while (! CHAR_HEAD_P (*((POSITION).p))); \
1426 (POSITION).pos--; \
1427 } while (0)
1429 /* This is like find_composition, but find an automatic composition
1430 instead. It is assured that POS is not within a static
1431 composition. If found, set *GSTRING to the glyph-string
1432 representing the composition, and return true. Otherwise, *GSTRING to
1433 Qnil, and return false. */
1435 static bool
1436 find_automatic_composition (ptrdiff_t pos, ptrdiff_t limit,
1437 ptrdiff_t *start, ptrdiff_t *end,
1438 Lisp_Object *gstring, Lisp_Object string)
1440 ptrdiff_t head, tail, stop;
1441 /* Forward limit position of checking a composition taking a
1442 looking-back count into account. */
1443 ptrdiff_t fore_check_limit;
1444 struct position_record cur, prev;
1445 int c;
1446 Lisp_Object window;
1447 struct window *w;
1448 bool need_adjustment = 0;
1450 window = Fget_buffer_window (Fcurrent_buffer (), Qnil);
1451 if (NILP (window))
1452 return 0;
1453 w = XWINDOW (window);
1455 cur.pos = pos;
1456 if (NILP (string))
1458 head = BEGV, tail = ZV, stop = GPT;
1459 cur.pos_byte = CHAR_TO_BYTE (cur.pos);
1460 cur.p = BYTE_POS_ADDR (cur.pos_byte);
1462 else
1464 head = 0, tail = SCHARS (string), stop = -1;
1465 cur.pos_byte = string_char_to_byte (string, cur.pos);
1466 cur.p = SDATA (string) + cur.pos_byte;
1468 if (limit < 0)
1469 /* Finding a composition covering the character after POS is the
1470 same as setting LIMIT to POS. */
1471 limit = pos;
1472 if (limit <= pos)
1473 fore_check_limit = min (tail, pos + 1 + MAX_AUTO_COMPOSITION_LOOKBACK);
1474 else
1475 fore_check_limit = min (tail, limit + MAX_AUTO_COMPOSITION_LOOKBACK);
1477 /* Provided that we have these possible compositions now:
1479 POS: 1 2 3 4 5 6 7 8 9
1480 |-A-|
1481 |-B-|-C-|--D--|
1483 Here, it is known that characters after positions 1 and 9 can
1484 never be composed (i.e. ! char_composable_p (CH)), and
1485 composition A is an invalid one because it's partially covered by
1486 the valid composition C. And to know whether a composition is
1487 valid or not, the only way is to start searching forward from a
1488 position that can not be a tail part of composition (it's 2 in
1489 the above case).
1491 Now we have these cases (1 through 4):
1493 -- character after POS is ... --
1494 not composable composable
1495 LIMIT <= POS (1) (3)
1496 POS < LIMIT (2) (4)
1498 Among them, in case (2), we simply search forward from POS.
1500 In the other cases, we at first rewind back to the position where
1501 the previous character is not composable or the beginning of
1502 buffer (string), then search compositions forward. In case (1)
1503 and (3) we repeat this process until a composition is found. */
1505 while (1)
1507 c = STRING_CHAR (cur.p);
1508 if (! char_composable_p (c))
1510 if (limit <= pos) /* case (1) */
1512 do {
1513 if (cur.pos <= limit)
1514 return 0;
1515 BACKWARD_CHAR (cur, stop);
1516 c = STRING_CHAR (cur.p);
1517 } while (! char_composable_p (c));
1518 fore_check_limit = cur.pos + 1;
1520 else /* case (2) */
1521 /* No need of rewinding back. */
1522 goto search_forward;
1525 /* Rewind back to the position where we can safely search
1526 forward for compositions. It is assured that the character
1527 at cur.pos is composable. */
1528 while (head < cur.pos)
1530 prev = cur;
1531 BACKWARD_CHAR (cur, stop);
1532 c = STRING_CHAR (cur.p);
1533 if (! char_composable_p (c))
1535 cur = prev;
1536 break;
1540 search_forward:
1541 /* Now search forward. */
1542 *gstring = Qnil;
1543 prev = cur; /* remember the start of searching position. */
1544 while (cur.pos < fore_check_limit)
1546 Lisp_Object val;
1548 c = STRING_CHAR (cur.p);
1549 for (val = CHAR_TABLE_REF (Vcomposition_function_table, c);
1550 CONSP (val); val = XCDR (val))
1552 Lisp_Object elt = XCAR (val);
1554 if (VECTORP (elt) && ASIZE (elt) == 3 && NATNUMP (AREF (elt, 1)))
1556 EMACS_INT check_pos = cur.pos - XFASTINT (AREF (elt, 1));
1557 struct position_record check;
1559 if (check_pos < head
1560 || (limit <= pos ? pos < check_pos
1561 : limit <= check_pos))
1562 continue;
1563 for (check = cur; check_pos < check.pos; )
1564 BACKWARD_CHAR (check, stop);
1565 *gstring = autocmp_chars (elt, check.pos, check.pos_byte,
1566 tail, w, NULL, string);
1567 need_adjustment = 1;
1568 if (NILP (*gstring))
1570 /* As we have called Lisp, there's a possibility
1571 that buffer/string is relocated. */
1572 if (NILP (string))
1573 cur.p = BYTE_POS_ADDR (cur.pos_byte);
1574 else
1575 cur.p = SDATA (string) + cur.pos_byte;
1577 else
1579 /* We found a candidate of a target composition. */
1580 *start = check.pos;
1581 *end = check.pos + LGSTRING_CHAR_LEN (*gstring);
1582 if (pos < limit
1583 ? pos < *end
1584 : *start <= pos && pos < *end)
1585 /* This is the target composition. */
1586 return 1;
1587 cur.pos = *end;
1588 if (NILP (string))
1590 cur.pos_byte = CHAR_TO_BYTE (cur.pos);
1591 cur.p = BYTE_POS_ADDR (cur.pos_byte);
1593 else
1595 cur.pos_byte = string_char_to_byte (string, cur.pos);
1596 cur.p = SDATA (string) + cur.pos_byte;
1598 break;
1602 if (! CONSP (val))
1603 /* We found no composition here. */
1604 FORWARD_CHAR (cur, stop);
1607 if (pos < limit) /* case (2) and (4)*/
1608 return 0;
1609 if (! NILP (*gstring))
1610 return 1;
1611 if (prev.pos == head)
1612 return 0;
1613 cur = prev;
1614 if (need_adjustment)
1616 if (NILP (string))
1617 cur.p = BYTE_POS_ADDR (cur.pos_byte);
1618 else
1619 cur.p = SDATA (string) + cur.pos_byte;
1621 BACKWARD_CHAR (cur, stop);
1625 /* Return the adjusted point provided that point is moved from LAST_PT
1626 to NEW_PT. */
1628 ptrdiff_t
1629 composition_adjust_point (ptrdiff_t last_pt, ptrdiff_t new_pt)
1631 ptrdiff_t i, beg, end;
1632 Lisp_Object val;
1634 if (new_pt == BEGV || new_pt == ZV)
1635 return new_pt;
1637 /* At first check the static composition. */
1638 if (get_property_and_range (new_pt, Qcomposition, &val, &beg, &end, Qnil)
1639 && composition_valid_p (beg, end, val))
1641 if (beg < new_pt /* && end > new_pt <- It's always the case. */
1642 && (last_pt <= beg || last_pt >= end))
1643 return (new_pt < last_pt ? beg : end);
1644 return new_pt;
1647 if (NILP (BVAR (current_buffer, enable_multibyte_characters))
1648 || NILP (Vauto_composition_mode))
1649 return new_pt;
1651 /* Next check the automatic composition. */
1652 if (! find_automatic_composition (new_pt, (ptrdiff_t) -1, &beg, &end, &val,
1653 Qnil)
1654 || beg == new_pt)
1655 return new_pt;
1656 for (i = 0; i < LGSTRING_GLYPH_LEN (val); i++)
1658 Lisp_Object glyph = LGSTRING_GLYPH (val, i);
1660 if (NILP (glyph))
1661 break;
1662 if (beg + LGLYPH_FROM (glyph) == new_pt)
1663 return new_pt;
1664 if (beg + LGLYPH_TO (glyph) >= new_pt)
1665 return (new_pt < last_pt
1666 ? beg + LGLYPH_FROM (glyph)
1667 : beg + LGLYPH_TO (glyph) + 1);
1669 return new_pt;
1672 DEFUN ("composition-get-gstring", Fcomposition_get_gstring,
1673 Scomposition_get_gstring, 4, 4, 0,
1674 doc: /* Return a glyph-string for characters between FROM and TO.
1675 If the glyph string is for graphic display, FONT-OBJECT must be
1676 a font-object to use for those characters.
1677 Otherwise (for terminal display), FONT-OBJECT must be a terminal ID, a
1678 frame, or nil for the selected frame's terminal device.
1680 If the optional 4th argument STRING is not nil, it is a string
1681 containing the target characters between indices FROM and TO,
1682 which are treated as in `substring'. Otherwise FROM and TO are
1683 character positions in current buffer; they can be in either order,
1684 and can be integers or markers.
1686 A glyph-string is a vector containing information about how to display
1687 a specific character sequence. The format is:
1688 [HEADER ID GLYPH ...]
1690 HEADER is a vector of this form:
1691 [FONT-OBJECT CHAR ...]
1692 where
1693 FONT-OBJECT is a font-object for all glyphs in the glyph-string,
1694 or the terminal coding system of the specified terminal.
1695 CHARs are characters to be composed by GLYPHs.
1697 ID is an identification number of the glyph-string. It may be nil if
1698 not yet shaped.
1700 GLYPH is a vector whose elements have this form:
1701 [ FROM-IDX TO-IDX C CODE WIDTH LBEARING RBEARING ASCENT DESCENT
1702 [ [X-OFF Y-OFF WADJUST] | nil] ]
1703 where
1704 FROM-IDX and TO-IDX are used internally and should not be touched.
1705 C is the character of the glyph.
1706 CODE is the glyph-code of C in FONT-OBJECT.
1707 WIDTH thru DESCENT are the metrics (in pixels) of the glyph.
1708 X-OFF and Y-OFF are offsets to the base position for the glyph.
1709 WADJUST is the adjustment to the normal width of the glyph.
1711 If GLYPH is nil, the remaining elements of the glyph-string vector
1712 should be ignored. */)
1713 (Lisp_Object from, Lisp_Object to, Lisp_Object font_object, Lisp_Object string)
1715 Lisp_Object gstring, header;
1716 ptrdiff_t frompos, frombyte, topos;
1718 if (! FONT_OBJECT_P (font_object))
1720 struct coding_system *coding;
1721 struct terminal *terminal = decode_live_terminal (font_object);
1723 coding = ((TERMINAL_TERMINAL_CODING (terminal)->common_flags
1724 & CODING_REQUIRE_ENCODING_MASK)
1725 ? TERMINAL_TERMINAL_CODING (terminal) : &safe_terminal_coding);
1726 font_object = CODING_ID_NAME (coding->id);
1729 if (NILP (string))
1731 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
1732 error ("Attempt to shape unibyte text");
1733 validate_region (&from, &to);
1734 frompos = XFASTINT (from);
1735 topos = XFASTINT (to);
1736 frombyte = CHAR_TO_BYTE (frompos);
1738 else
1740 CHECK_STRING (string);
1741 validate_subarray (string, from, to, SCHARS (string), &frompos, &topos);
1742 if (! STRING_MULTIBYTE (string))
1743 error ("Attempt to shape unibyte text");
1744 frombyte = string_char_to_byte (string, frompos);
1747 header = fill_gstring_header (Qnil, frompos, frombyte,
1748 topos, font_object, string);
1749 gstring = gstring_lookup_cache (header);
1750 if (! NILP (gstring))
1751 return gstring;
1753 if (LGSTRING_GLYPH_LEN (gstring_work) < topos - frompos)
1754 gstring_work = Fmake_vector (make_number (topos - frompos + 2), Qnil);
1755 LGSTRING_SET_HEADER (gstring_work, header);
1756 LGSTRING_SET_ID (gstring_work, Qnil);
1757 fill_gstring_body (gstring_work);
1758 return gstring_work;
1762 /* Emacs Lisp APIs. */
1764 DEFUN ("compose-region-internal", Fcompose_region_internal,
1765 Scompose_region_internal, 2, 4, 0,
1766 doc: /* Internal use only.
1768 Compose text in the region between START and END.
1769 Optional 3rd and 4th arguments are COMPONENTS and MODIFICATION-FUNC
1770 for the composition. See `compose-region' for more details. */)
1771 (Lisp_Object start, Lisp_Object end, Lisp_Object components, Lisp_Object modification_func)
1773 validate_region (&start, &end);
1774 if (!NILP (components)
1775 && !INTEGERP (components)
1776 && !CONSP (components)
1777 && !STRINGP (components))
1778 CHECK_VECTOR (components);
1780 compose_text (XINT (start), XINT (end), components, modification_func, Qnil);
1781 return Qnil;
1784 DEFUN ("compose-string-internal", Fcompose_string_internal,
1785 Scompose_string_internal, 3, 5, 0,
1786 doc: /* Internal use only.
1788 Compose text between indices START and END of STRING, where
1789 START and END are treated as in `substring'. Optional 4th
1790 and 5th arguments are COMPONENTS and MODIFICATION-FUNC
1791 for the composition. See `compose-string' for more details. */)
1792 (Lisp_Object string, Lisp_Object start, Lisp_Object end,
1793 Lisp_Object components, Lisp_Object modification_func)
1795 ptrdiff_t from, to;
1797 CHECK_STRING (string);
1798 validate_subarray (string, start, end, SCHARS (string), &from, &to);
1799 compose_text (from, to, components, modification_func, string);
1800 return string;
1803 DEFUN ("find-composition-internal", Ffind_composition_internal,
1804 Sfind_composition_internal, 4, 4, 0,
1805 doc: /* Internal use only.
1807 Return information about composition at or nearest to position POS.
1808 See `find-composition' for more details. */)
1809 (Lisp_Object pos, Lisp_Object limit, Lisp_Object string, Lisp_Object detail_p)
1811 Lisp_Object prop, tail, gstring;
1812 ptrdiff_t start, end, from, to;
1813 int id;
1815 CHECK_NUMBER_COERCE_MARKER (pos);
1816 if (!NILP (limit))
1818 CHECK_NUMBER_COERCE_MARKER (limit);
1819 to = min (XINT (limit), ZV);
1821 else
1822 to = -1;
1824 if (!NILP (string))
1826 CHECK_STRING (string);
1827 if (XINT (pos) < 0 || XINT (pos) > SCHARS (string))
1828 args_out_of_range (string, pos);
1830 else
1832 if (XINT (pos) < BEGV || XINT (pos) > ZV)
1833 args_out_of_range (Fcurrent_buffer (), pos);
1835 from = XINT (pos);
1837 if (!find_composition (from, to, &start, &end, &prop, string))
1839 if (!NILP (BVAR (current_buffer, enable_multibyte_characters))
1840 && ! NILP (Vauto_composition_mode)
1841 && find_automatic_composition (from, to, &start, &end, &gstring,
1842 string))
1843 return list3 (make_number (start), make_number (end), gstring);
1844 return Qnil;
1846 if ((end <= XINT (pos) || start > XINT (pos)))
1848 ptrdiff_t s, e;
1850 if (find_automatic_composition (from, to, &s, &e, &gstring, string)
1851 && (e <= XINT (pos) ? e > end : s < start))
1852 return list3 (make_number (s), make_number (e), gstring);
1854 if (!composition_valid_p (start, end, prop))
1855 return list3 (make_number (start), make_number (end), Qnil);
1856 if (NILP (detail_p))
1857 return list3 (make_number (start), make_number (end), Qt);
1859 if (composition_registered_p (prop))
1860 id = COMPOSITION_ID (prop);
1861 else
1863 ptrdiff_t start_byte = (NILP (string)
1864 ? CHAR_TO_BYTE (start)
1865 : string_char_to_byte (string, start));
1866 id = get_composition_id (start, start_byte, end - start, prop, string);
1869 if (id >= 0)
1871 Lisp_Object components, relative_p, mod_func;
1872 enum composition_method method = composition_method (prop);
1873 int width = composition_table[id]->width;
1875 components = Fcopy_sequence (COMPOSITION_COMPONENTS (prop));
1876 relative_p = (method == COMPOSITION_WITH_RULE_ALTCHARS
1877 ? Qnil : Qt);
1878 mod_func = COMPOSITION_MODIFICATION_FUNC (prop);
1879 tail = list4 (components, relative_p, mod_func, make_number (width));
1881 else
1882 tail = Qnil;
1884 return Fcons (make_number (start), Fcons (make_number (end), tail));
1888 void
1889 syms_of_composite (void)
1891 int i;
1893 DEFSYM (Qcomposition, "composition");
1895 /* Make a hash table for static composition. */
1896 /* We used to make the hash table weak so that unreferenced
1897 compositions can be garbage-collected. But, usually once
1898 created compositions are repeatedly used in an Emacs session,
1899 and thus it's not worth to save memory in such a way. So, we
1900 make the table not weak. */
1901 Lisp_Object args[] = {QCtest, Qequal, QCsize, make_number (311)};
1902 composition_hash_table = CALLMANY (Fmake_hash_table, args);
1903 staticpro (&composition_hash_table);
1905 /* Make a hash table for glyph-string. */
1906 gstring_hash_table = CALLMANY (Fmake_hash_table, args);
1907 staticpro (&gstring_hash_table);
1909 staticpro (&gstring_work_headers);
1910 gstring_work_headers = make_uninit_vector (8);
1911 for (i = 0; i < 8; i++)
1912 ASET (gstring_work_headers, i, Fmake_vector (make_number (i + 2), Qnil));
1913 staticpro (&gstring_work);
1914 gstring_work = Fmake_vector (make_number (10), Qnil);
1916 /* Text property `composition' should be nonsticky by default. */
1917 Vtext_property_default_nonsticky
1918 = Fcons (Fcons (Qcomposition, Qt), Vtext_property_default_nonsticky);
1920 DEFVAR_LISP ("compose-chars-after-function", Vcompose_chars_after_function,
1921 doc: /* Function to adjust composition of buffer text.
1923 This function is called with three arguments: FROM, TO, and OBJECT.
1924 FROM and TO specify the range of text whose composition should be
1925 adjusted. OBJECT, if non-nil, is a string that contains the text.
1927 This function is called after a text with `composition' property is
1928 inserted or deleted to keep `composition' property of buffer text
1929 valid.
1931 The default value is the function `compose-chars-after'. */);
1932 Vcompose_chars_after_function = intern_c_string ("compose-chars-after");
1934 DEFSYM (Qauto_composed, "auto-composed");
1936 DEFVAR_LISP ("auto-composition-mode", Vauto_composition_mode,
1937 doc: /* Non-nil if Auto-Composition mode is enabled.
1938 Use the command `auto-composition-mode' to change this variable. */);
1939 Vauto_composition_mode = Qt;
1941 DEFVAR_LISP ("auto-composition-function", Vauto_composition_function,
1942 doc: /* Function to call to compose characters automatically.
1943 This function is called from the display routine with four arguments:
1944 FROM, TO, WINDOW, and STRING.
1946 If STRING is nil, the function must compose characters in the region
1947 between FROM and TO in the current buffer.
1949 Otherwise, STRING is a string, and FROM and TO are indices into the
1950 string. In this case, the function must compose characters in the
1951 string. */);
1952 Vauto_composition_function = Qnil;
1954 DEFVAR_LISP ("composition-function-table", Vcomposition_function_table,
1955 doc: /* Char-table of functions for automatic character composition.
1956 For each character that has to be composed automatically with
1957 preceding and/or following characters, this char-table contains
1958 a function to call to compose that character.
1960 The element at index C in the table, if non-nil, is a list of
1961 composition rules of this form: ([PATTERN PREV-CHARS FUNC] ...)
1963 PATTERN is a regular expression which C and the surrounding
1964 characters must match.
1966 PREV-CHARS is a non-negative integer (less than 4) specifying how many
1967 characters before C to check the matching with PATTERN. If it is 0,
1968 PATTERN must match C and the following characters. If it is 1,
1969 PATTERN must match a character before C and the following characters.
1971 If PREV-CHARS is 0, PATTERN can be nil, which means that the
1972 single character C should be composed.
1974 FUNC is a function to return a glyph-string representing a
1975 composition of the characters that match PATTERN. It is
1976 called with one argument GSTRING.
1978 GSTRING is a template of a glyph-string to return. It is already
1979 filled with a proper header for the characters to compose, and
1980 glyphs corresponding to those characters one by one. The
1981 function must return a new glyph-string with the same header as
1982 GSTRING, or modify GSTRING itself and return it.
1984 See also the documentation of `auto-composition-mode'. */);
1985 Vcomposition_function_table = Fmake_char_table (Qnil, Qnil);
1987 defsubr (&Scompose_region_internal);
1988 defsubr (&Scompose_string_internal);
1989 defsubr (&Sfind_composition_internal);
1990 defsubr (&Scomposition_get_gstring);