casefiddle.c 22.4 KB
Newer Older
1
/* -*- coding: utf-8 -*- */
Jim Blandy's avatar
Jim Blandy committed
2
/* GNU Emacs case conversion functions.
3

Paul Eggert's avatar
Paul Eggert committed
4
Copyright (C) 1985, 1994, 1997-1999, 2001-2020 Free Software Foundation,
5
Inc.
Jim Blandy's avatar
Jim Blandy committed
6 7 8

This file is part of GNU Emacs.

9
GNU Emacs is free software: you can redistribute it and/or modify
Jim Blandy's avatar
Jim Blandy committed
10
it under the terms of the GNU General Public License as published by
11 12
the Free Software Foundation, either version 3 of the License, or (at
your option) any later version.
Jim Blandy's avatar
Jim Blandy committed
13 14 15 16 17 18 19

GNU Emacs is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
20
along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.  */
Jim Blandy's avatar
Jim Blandy committed
21 22


23
#include <config.h>
24

Jim Blandy's avatar
Jim Blandy committed
25
#include "lisp.h"
26
#include "character.h"
27
#include "buffer.h"
Jim Blandy's avatar
Jim Blandy committed
28 29
#include "commands.h"
#include "syntax.h"
Kenichi Handa's avatar
Kenichi Handa committed
30
#include "composite.h"
Stefan Monnier's avatar
Stefan Monnier committed
31
#include "keymap.h"
Jim Blandy's avatar
Jim Blandy committed
32 33

enum case_action {CASE_UP, CASE_DOWN, CASE_CAPITALIZE, CASE_CAPITALIZE_UP};
34 35

/* State for casing individual characters.  */
Paul Eggert's avatar
Paul Eggert committed
36 37
struct casing_context
{
38 39 40
  /* A char-table with title-case character mappings or nil.  Non-nil implies
     flag is CASE_CAPITALIZE or CASE_CAPITALIZE_UP.  */
  Lisp_Object titlecase_char_table;
Paul Eggert's avatar
Paul Eggert committed
41

42
  /* The unconditional special-casing Unicode property char tables for upper
Paul Eggert's avatar
Paul Eggert committed
43
     casing, lower casing and title casing respectively.  */
44
  Lisp_Object specialcase_char_tables[3];
Paul Eggert's avatar
Paul Eggert committed
45 46

  /* User-requested action.  */
47
  enum case_action flag;
Paul Eggert's avatar
Paul Eggert committed
48 49 50 51 52

  /* If true, the function operates on a buffer as opposed to a string
     or character.  When run on a buffer, syntax_prefix_flag_p is
     taken into account when determining whether the context is within
     a word.  */
53
  bool inbuffer;
Paul Eggert's avatar
Paul Eggert committed
54 55

  /* Whether the context is within a word.  */
56 57 58
  bool inword;
};

Paul Eggert's avatar
Paul Eggert committed
59
/* Initialize CTX structure for casing characters.  */
60 61 62 63 64 65
static void
prepare_casing_context (struct casing_context *ctx,
			enum case_action flag, bool inbuffer)
{
  ctx->flag = flag;
  ctx->inbuffer = inbuffer;
66
  ctx->inword = false;
Paul Eggert's avatar
Paul Eggert committed
67 68
  ctx->titlecase_char_table
    = (flag < CASE_CAPITALIZE ? Qnil
69
       : uniprop_table (Qtitlecase));
Paul Eggert's avatar
Paul Eggert committed
70 71
  ctx->specialcase_char_tables[CASE_UP]
    = (flag == CASE_DOWN ? Qnil
72
       : uniprop_table (Qspecial_uppercase));
Paul Eggert's avatar
Paul Eggert committed
73 74
  ctx->specialcase_char_tables[CASE_DOWN]
    = (flag == CASE_UP ? Qnil
75
       : uniprop_table (Qspecial_lowercase));
Paul Eggert's avatar
Paul Eggert committed
76 77
  ctx->specialcase_char_tables[CASE_CAPITALIZE]
    = (flag < CASE_CAPITALIZE ? Qnil
78
       : uniprop_table (Qspecial_titlecase));
79 80 81 82 83

  /* If the case table is flagged as modified, rescan it.  */
  if (NILP (XCHAR_TABLE (BVAR (current_buffer, downcase_table))->extras[1]))
    Fset_case_table (BVAR (current_buffer, downcase_table));

Paul Eggert's avatar
Paul Eggert committed
84
  if (inbuffer && flag >= CASE_CAPITALIZE)
85 86 87
    SETUP_BUFFER_SYNTAX_TABLE ();	/* For syntax_prefix_flag_p.  */
}

Paul Eggert's avatar
Paul Eggert committed
88 89 90
struct casing_str_buf
{
  unsigned char data[max (6, MAX_MULTIBYTE_LENGTH)];
91 92 93 94 95 96 97 98 99
  unsigned char len_chars;
  unsigned char len_bytes;
};

/* Based on CTX, case character CH.  If BUF is NULL, return cased character.
   Otherwise, if BUF is non-NULL, save result in it and return whether the
   character has been changed.

   Since meaning of return value depends on arguments, it’s more convenient to
Paul Eggert's avatar
Paul Eggert committed
100
   use case_single_character or case_character instead.  */
101
static int
102 103
case_character_impl (struct casing_str_buf *buf,
		     struct casing_context *ctx, int ch)
104
{
105
  enum case_action flag;
106
  Lisp_Object prop;
107 108 109
  int cased;

  /* Update inword state */
Paul Eggert's avatar
Paul Eggert committed
110
  bool was_inword = ctx->inword;
111 112
  ctx->inword = SYNTAX (ch) == Sword &&
    (!ctx->inbuffer || was_inword || !syntax_prefix_flag_p (ch));
113

Paul Eggert's avatar
Paul Eggert committed
114
  /* Normalize flag so its one of CASE_UP, CASE_DOWN or CASE_CAPITALIZE.  */
115
  if (ctx->flag == CASE_CAPITALIZE)
Paul Eggert's avatar
Paul Eggert committed
116
    flag = ctx->flag - was_inword;
117
  else if (ctx->flag != CASE_CAPITALIZE_UP)
118 119 120
    flag = ctx->flag;
  else if (!was_inword)
    flag = CASE_CAPITALIZE;
121 122 123 124 125 126
  else
    {
      cased = ch;
      goto done;
    }

Paul Eggert's avatar
Paul Eggert committed
127
  /* Look through the special casing entries.  */
Paul Eggert's avatar
Paul Eggert committed
128
  if (buf && !NILP (ctx->specialcase_char_tables[flag]))
129
    {
Paul Eggert's avatar
Paul Eggert committed
130
      prop = CHAR_TABLE_REF (ctx->specialcase_char_tables[flag], ch);
Paul Eggert's avatar
Paul Eggert committed
131
      if (STRINGP (prop))
132
        {
Paul Eggert's avatar
Paul Eggert committed
133 134
          struct Lisp_String *str = XSTRING (prop);
          if (STRING_BYTES (str) <= sizeof buf->data)
135
	    {
136
	      buf->len_chars = str->u.s.size;
Paul Eggert's avatar
Paul Eggert committed
137
	      buf->len_bytes = STRING_BYTES (str);
138
	      memcpy (buf->data, str->u.s.data, buf->len_bytes);
139 140 141 142
	      return 1;
	    }
        }
    }
143

Paul Eggert's avatar
Paul Eggert committed
144
  /* Handle simple, one-to-one case.  */
145 146
  if (flag == CASE_DOWN)
    cased = downcase (ch);
147
  else
Paul Eggert's avatar
Paul Eggert committed
148 149 150 151 152 153 154
    {
      bool cased_is_set = false;
      if (!NILP (ctx->titlecase_char_table))
	{
	  prop = CHAR_TABLE_REF (ctx->titlecase_char_table, ch);
	  if (CHARACTERP (prop))
	    {
Tom Tromey's avatar
Tom Tromey committed
155
	      cased = XFIXNAT (prop);
Paul Eggert's avatar
Paul Eggert committed
156 157 158 159 160 161
	      cased_is_set = true;
	    }
	}
      if (!cased_is_set)
	cased = upcase (ch);
    }
162

Paul Eggert's avatar
Paul Eggert committed
163
  /* And we’re done.  */
164 165 166 167 168 169 170
 done:
  if (!buf)
    return cased;
  buf->len_chars = 1;
  buf->len_bytes = CHAR_STRING (cased, buf->data);
  return cased != ch;
}
171 172 173 174 175 176

/* In Greek, lower case sigma has two forms: one when used in the middle and one
   when used at the end of a word.  Below is to help handle those cases when
   casing.

   The rule does not conflict with any other casing rules so while it is
Paul Eggert's avatar
Paul Eggert committed
177
   a conditional one, it is independent of language.  */
178

Paul Eggert's avatar
Paul Eggert committed
179
enum { GREEK_CAPITAL_LETTER_SIGMA = 0x03A3 }; /* Σ */
Paul Eggert's avatar
Paul Eggert committed
180
enum { GREEK_SMALL_LETTER_FINAL_SIGMA = 0x03C2 }; /* ς */
181

182 183 184 185 186
/* Based on CTX, case character CH accordingly.  Update CTX as necessary.
   Return cased character.

   Special casing rules (such as upcase(fi) = FI) are not handled.  For
   characters whose casing results in multiple code points, the character is
Paul Eggert's avatar
Paul Eggert committed
187
   returned unchanged.  */
188 189 190 191 192 193 194
static inline int
case_single_character (struct casing_context *ctx, int ch)
{
  return case_character_impl (NULL, ctx, ch);
}

/* Save in BUF result of casing character CH.  Return whether casing changed the
195 196 197 198 199 200 201
   character.

   If not-NULL, NEXT points to the next character in the cased string.  If NULL,
   it is assumed current character is the last one being cased.  This is used to
   apply some rules which depend on proceeding state.

   This is like case_single_character but also handles one-to-many casing
Paul Eggert's avatar
Paul Eggert committed
202
   rules.  */
203 204 205
static bool
case_character (struct casing_str_buf *buf, struct casing_context *ctx,
		int ch, const unsigned char *next)
206
{
Paul Eggert's avatar
Paul Eggert committed
207 208
  bool was_inword = ctx->inword;
  bool changed = case_character_impl (buf, ctx, ch);
209 210 211

  /* If we have just down-cased a capital sigma and the next character no longer
     has a word syntax (i.e. current character is end of word), use final
Paul Eggert's avatar
Paul Eggert committed
212 213 214
     sigma.  */
  if (was_inword && ch == GREEK_CAPITAL_LETTER_SIGMA && changed
      && (!next || SYNTAX (STRING_CHAR (next)) != Sword))
215
    {
Paul Eggert's avatar
Paul Eggert committed
216
      buf->len_bytes = CHAR_STRING (GREEK_SMALL_LETTER_FINAL_SIGMA, buf->data);
217 218 219 220
      buf->len_chars = 1;
    }

  return changed;
221
}
Jim Blandy's avatar
Jim Blandy committed
222

223
/* If C is not ASCII, make it unibyte. */
224
static inline int
225 226 227 228 229
make_char_unibyte (int c)
{
  return ASCII_CHAR_P (c) ? c : CHAR_TO_BYTE8 (c);
}

230
static Lisp_Object
231
do_casify_natnum (struct casing_context *ctx, Lisp_Object obj)
Jim Blandy's avatar
Jim Blandy committed
232
{
233 234
  int flagbits = (CHAR_ALT | CHAR_SUPER | CHAR_HYPER
		  | CHAR_SHIFT | CHAR_CTL | CHAR_META);
Tom Tromey's avatar
Tom Tromey committed
235
  int ch = XFIXNAT (obj);
236 237 238

  /* If the character has higher bits set above the flags, return it unchanged.
     It is not a real character.  */
Paul Eggert's avatar
Paul Eggert committed
239
  if (! (0 <= ch && ch <= flagbits))
240 241
    return obj;

Paul Eggert's avatar
Paul Eggert committed
242
  int flags = ch & flagbits;
243 244 245 246 247 248
  ch = ch & ~flagbits;

  /* FIXME: Even if enable-multibyte-characters is nil, we may manipulate
     multibyte chars.  This means we have a bug for latin-1 chars since when we
     receive an int 128-255 we can't tell whether it's an eight-bit byte or
     a latin-1 char.  */
Paul Eggert's avatar
Paul Eggert committed
249 250 251
  bool multibyte = (ch >= 256
		    || !NILP (BVAR (current_buffer,
				    enable_multibyte_characters)));
252
  if (! multibyte)
253
    ch = make_char_multibyte (ch);
Paul Eggert's avatar
Paul Eggert committed
254
  int cased = case_single_character (ctx, ch);
255 256 257 258
  if (cased == ch)
    return obj;

  if (! multibyte)
259
    cased = make_char_unibyte (cased);
260
  return make_fixed_natnum (cased | flags);
261 262 263
}

static Lisp_Object
264
do_casify_multibyte_string (struct casing_context *ctx, Lisp_Object obj)
265
{
Paul Eggert's avatar
Paul Eggert committed
266 267 268 269 270 271
  /* Verify that ‘data’ is the first member of struct casing_str_buf
     so that when casting char * to struct casing_str_buf *, the
     representation of the character is at the beginning of the
     buffer.  This is why we don’t need a separate struct
     casing_str_buf object, and can write directly to the destination.  */
  verify (offsetof (struct casing_str_buf, data) == 0);
272 273

  ptrdiff_t size = SCHARS (obj), n;
274
  USE_SAFE_ALLOCA;
Paul Eggert's avatar
Paul Eggert committed
275
  if (INT_MULTIPLY_WRAPV (size, MAX_MULTIBYTE_LENGTH, &n)
276
      || INT_ADD_WRAPV (n, sizeof (struct casing_str_buf), &n))
277
    n = PTRDIFF_MAX;
Paul Eggert's avatar
Paul Eggert committed
278 279
  unsigned char *dst = SAFE_ALLOCA (n);
  unsigned char *dst_end = dst + n;
280 281
  unsigned char *o = dst;

282 283 284
  const unsigned char *src = SDATA (obj);

  for (n = 0; size; --size)
285
    {
Paul Eggert's avatar
Paul Eggert committed
286
      if (dst_end - o < sizeof (struct casing_str_buf))
287
	string_overflow ();
288
      int ch = string_char_advance (&src);
Paul Eggert's avatar
Paul Eggert committed
289 290 291 292
      case_character ((struct casing_str_buf *) o, ctx, ch,
		      size > 1 ? src : NULL);
      n += ((struct casing_str_buf *) o)->len_chars;
      o += ((struct casing_str_buf *) o)->len_bytes;
293
    }
294 295
  eassert (o <= dst_end);
  obj = make_multibyte_string ((char *) dst, n, o - dst);
296 297 298 299 300
  SAFE_FREE ();
  return obj;
}

static Lisp_Object
301
do_casify_unibyte_string (struct casing_context *ctx, Lisp_Object obj)
302 303 304 305 306 307 308
{
  ptrdiff_t i, size = SCHARS (obj);
  int ch, cased;

  obj = Fcopy_sequence (obj);
  for (i = 0; i < size; i++)
    {
309
      ch = make_char_multibyte (SREF (obj, i));
310
      cased = case_single_character (ctx, ch);
311 312
      if (ch == cased)
	continue;
313
      cased = make_char_unibyte (cased);
Paul Eggert's avatar
Paul Eggert committed
314 315
      /* If the char can't be converted to a valid byte, just don't
	 change it.  */
316
      if (SINGLE_BYTE_CHAR_P (cased))
317
	SSET (obj, i, cased);
318 319 320
    }
  return obj;
}
Jim Blandy's avatar
Jim Blandy committed
321

322 323 324
static Lisp_Object
casify_object (enum case_action flag, Lisp_Object obj)
{
325 326
  struct casing_context ctx;
  prepare_casing_context (&ctx, flag, false);
327

328
  if (FIXNATP (obj))
329
    return do_casify_natnum (&ctx, obj);
330
  else if (!STRINGP (obj))
331
    wrong_type_argument (Qchar_or_string_p, obj);
332 333 334
  else if (!SCHARS (obj))
    return obj;
  else if (STRING_MULTIBYTE (obj))
335
    return do_casify_multibyte_string (&ctx, obj);
336
  else
337
    return do_casify_unibyte_string (&ctx, obj);
Jim Blandy's avatar
Jim Blandy committed
338 339
}

Paul Eggert's avatar
Paul Eggert committed
340
DEFUN ("upcase", Fupcase, Supcase, 1, 1, 0,
341 342
       doc: /* Convert argument to upper case and return that.
The argument may be a character or string.  The result has the same type.
343 344 345
The argument object is not altered--the value is a copy.  If argument
is a character, characters which map to multiple code points when
cased, e.g. fi, are returned unchanged.
346
See also `capitalize', `downcase' and `upcase-initials'.  */)
Dan Nicolaescu's avatar
Dan Nicolaescu committed
347
  (Lisp_Object obj)
Jim Blandy's avatar
Jim Blandy committed
348 349 350 351
{
  return casify_object (CASE_UP, obj);
}

Paul Eggert's avatar
Paul Eggert committed
352
DEFUN ("downcase", Fdowncase, Sdowncase, 1, 1, 0,
353 354 355
       doc: /* Convert argument to lower case and return that.
The argument may be a character or string.  The result has the same type.
The argument object is not altered--the value is a copy.  */)
Dan Nicolaescu's avatar
Dan Nicolaescu committed
356
  (Lisp_Object obj)
Jim Blandy's avatar
Jim Blandy committed
357 358 359 360 361
{
  return casify_object (CASE_DOWN, obj);
}

DEFUN ("capitalize", Fcapitalize, Scapitalize, 1, 1, 0,
362
       doc: /* Convert argument to capitalized form and return that.
363 364
This means that each word's first character is converted to either
title case or upper case, and the rest to lower case.
365
The argument may be a character or string.  The result has the same type.
366 367 368
The argument object is not altered--the value is a copy.  If argument
is a character, characters which map to multiple code points when
cased, e.g. fi, are returned unchanged.  */)
Dan Nicolaescu's avatar
Dan Nicolaescu committed
369
  (Lisp_Object obj)
Jim Blandy's avatar
Jim Blandy committed
370 371 372
{
  return casify_object (CASE_CAPITALIZE, obj);
}
373

374 375
/* Like Fcapitalize but change only the initials.  */

Paul Eggert's avatar
Paul Eggert committed
376
DEFUN ("upcase-initials", Fupcase_initials, Supcase_initials, 1, 1, 0,
377
       doc: /* Convert the initial of each word in the argument to upper case.
378 379
This means that each word's first character is converted to either
title case or upper case, and the rest are left unchanged.
380
The argument may be a character or string.  The result has the same type.
381 382 383
The argument object is not altered--the value is a copy.  If argument
is a character, characters which map to multiple code points when
cased, e.g. fi, are returned unchanged.  */)
Dan Nicolaescu's avatar
Dan Nicolaescu committed
384
  (Lisp_Object obj)
385 386 387
{
  return casify_object (CASE_CAPITALIZE_UP, obj);
}
Jim Blandy's avatar
Jim Blandy committed
388

389 390 391 392 393 394 395
/* Based on CTX, case region in a unibyte buffer from *STARTP to *ENDP.

   Save first and last positions that has changed in *STARTP and *ENDP
   respectively.  If no characters were changed, save -1 to *STARTP and leave
   *ENDP unspecified.

   Always return 0.  This is so that interface of this function is the same as
Paul Eggert's avatar
Paul Eggert committed
396
   do_casify_multibyte_region.  */
397 398
static ptrdiff_t
do_casify_unibyte_region (struct casing_context *ctx,
399
			  ptrdiff_t *startp, ptrdiff_t *endp)
Jim Blandy's avatar
Jim Blandy committed
400
{
Paul Eggert's avatar
Paul Eggert committed
401 402
  ptrdiff_t first = -1, last = -1;  /* Position of first and last changes.  */
  ptrdiff_t end = *endp;
403

Paul Eggert's avatar
Paul Eggert committed
404
  for (ptrdiff_t pos = *startp; pos < end; ++pos)
405
    {
406
      int ch = make_char_multibyte (FETCH_BYTE (pos));
Paul Eggert's avatar
Paul Eggert committed
407
      int cased = case_single_character (ctx, ch);
408 409
      if (cased == ch)
	continue;
Jim Blandy's avatar
Jim Blandy committed
410

411
      last = pos + 1;
412 413
      if (first < 0)
	first = pos;
414

415
      FETCH_BYTE (pos) = make_char_unibyte (cased);
416
    }
Jim Blandy's avatar
Jim Blandy committed
417

418 419 420
  *startp = first;
  *endp = last;
  return 0;
421
}
Jim Blandy's avatar
Jim Blandy committed
422

423 424 425 426 427
/* Based on CTX, case region in a multibyte buffer from *STARTP to *ENDP.

   Return number of added characters (may be negative if more characters were
   deleted then inserted), save first and last positions that has changed in
   *STARTP and *ENDP respectively.  If no characters were changed, return 0,
Paul Eggert's avatar
Paul Eggert committed
428
   save -1 to *STARTP and leave *ENDP unspecified.  */
429 430
static ptrdiff_t
do_casify_multibyte_region (struct casing_context *ctx,
431
			    ptrdiff_t *startp, ptrdiff_t *endp)
432
{
Paul Eggert's avatar
Paul Eggert committed
433
  ptrdiff_t first = -1, last = -1;  /* Position of first and last changes.  */
434 435
  ptrdiff_t pos = *startp, pos_byte = CHAR_TO_BYTE (pos), size = *endp - pos;
  ptrdiff_t opoint = PT, added = 0;
436

437
  for (; size; --size)
Karl Heuer's avatar
Karl Heuer committed
438
    {
439
      int len, ch = string_char_and_length (BYTE_POS_ADDR (pos_byte), &len);
Paul Eggert's avatar
Paul Eggert committed
440 441 442
      struct casing_str_buf buf;
      if (!case_character (&buf, ctx, ch,
			   size > 1 ? BYTE_POS_ADDR (pos_byte + len) : NULL))
Karl Heuer's avatar
Karl Heuer committed
443
	{
444 445 446 447
	  pos_byte += len;
	  ++pos;
	  continue;
	}
448

449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
      last = pos + buf.len_chars;
      if (first < 0)
	first = pos;

      if (buf.len_chars == 1 && buf.len_bytes == len)
	memcpy (BYTE_POS_ADDR (pos_byte), buf.data, len);
      else
	{
	  /* Replace one character with the other(s), keeping text
	     properties the same.  */
	  replace_range_2 (pos, pos_byte, pos + 1, pos_byte + len,
			   (const char *) buf.data, buf.len_chars,
			   buf.len_bytes,
			   0);
	  added += (ptrdiff_t) buf.len_chars - 1;
	  if (opoint > pos)
	    opoint += (ptrdiff_t) buf.len_chars - 1;
Karl Heuer's avatar
Karl Heuer committed
466
	}
467 468 469

      pos_byte += buf.len_bytes;
      pos += buf.len_chars;
Jim Blandy's avatar
Jim Blandy committed
470 471
    }

Kenichi Handa's avatar
Kenichi Handa committed
472
  if (PT != opoint)
473 474
    TEMP_SET_PT_BOTH (opoint, CHAR_TO_BYTE (opoint));

475
  *startp = first;
476
  *endp = last;
477
  return added;
478 479
}

480 481 482 483
/* flag is CASE_UP, CASE_DOWN or CASE_CAPITALIZE or CASE_CAPITALIZE_UP.  b and
   e specify range of buffer to operate on.  Return character position of the
   end of the region after changes.  */
static ptrdiff_t
484 485
casify_region (enum case_action flag, Lisp_Object b, Lisp_Object e)
{
Paul Eggert's avatar
Paul Eggert committed
486
  ptrdiff_t added;
487 488 489
  struct casing_context ctx;

  validate_region (&b, &e);
Tom Tromey's avatar
Tom Tromey committed
490 491
  ptrdiff_t start = XFIXNAT (b);
  ptrdiff_t end = XFIXNAT (e);
492
  if (start == end)
Paul Eggert's avatar
Paul Eggert committed
493
    /* Not modifying because nothing marked.  */
494
    return end;
495 496 497
  modify_text (start, end);
  prepare_casing_context (&ctx, flag, true);

Paul Eggert's avatar
Paul Eggert committed
498
  ptrdiff_t orig_end = end;
499
  record_delete (start, make_buffer_string (start, end, true), false);
500
  if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
501 502 503 504
    {
      record_insert (start, end - start);
      added = do_casify_unibyte_region (&ctx, &start, &end);
    }
505
  else
506 507 508 509 510
    {
      ptrdiff_t len = end - start, ostart = start;
      added = do_casify_multibyte_region (&ctx, &start, &end);
      record_insert (ostart, len + added);
    }
Kenichi Handa's avatar
Kenichi Handa committed
511

512
  if (start >= 0)
Kenichi Handa's avatar
Kenichi Handa committed
513
    {
514 515
      signal_after_change (start, end - start - added, end - start);
      update_compositions (start, end, CHECK_ALL);
Kenichi Handa's avatar
Kenichi Handa committed
516
    }
517 518

  return orig_end + added;
Jim Blandy's avatar
Jim Blandy committed
519 520
}

521 522 523 524
/* Casify a possibly noncontiguous region according to FLAG.  BEG and
   END specify the bounds, except that if REGION_NONCONTIGUOUS_P is
   non-nil, the region's bounds are specified by (funcall
   region-extract-function 'bounds) instead.  */
525

526 527 528 529
static Lisp_Object
casify_pnc_region (enum case_action flag, Lisp_Object beg, Lisp_Object end,
		   Lisp_Object region_noncontiguous_p)
{
530 531
  if (!NILP (region_noncontiguous_p))
    {
532 533
      Lisp_Object bounds = call1 (Vregion_extract_function, Qbounds);
      FOR_EACH_TAIL (bounds)
534
	{
535 536
	  CHECK_CONS (XCAR (bounds));
	  casify_region (flag, XCAR (XCAR (bounds)), XCDR (XCAR (bounds)));
537
	}
538
      CHECK_LIST_END (bounds, bounds);
539 540
    }
  else
541
    casify_region (flag, beg, end);
542

Jim Blandy's avatar
Jim Blandy committed
543 544 545
  return Qnil;
}

546 547 548 549 550 551 552 553 554 555 556 557
DEFUN ("upcase-region", Fupcase_region, Supcase_region, 2, 3,
       "(list (region-beginning) (region-end) (region-noncontiguous-p))",
       doc: /* Convert the region to upper case.  In programs, wants two arguments.
These arguments specify the starting and ending character numbers of
the region to operate on.  When used as a command, the text between
point and the mark is operated on.
See also `capitalize-region'.  */)
  (Lisp_Object beg, Lisp_Object end, Lisp_Object region_noncontiguous_p)
{
  return casify_pnc_region (CASE_UP, beg, end, region_noncontiguous_p);
}

558 559
DEFUN ("downcase-region", Fdowncase_region, Sdowncase_region, 2, 3,
       "(list (region-beginning) (region-end) (region-noncontiguous-p))",
560 561 562 563
       doc: /* Convert the region to lower case.  In programs, wants two arguments.
These arguments specify the starting and ending character numbers of
the region to operate on.  When used as a command, the text between
point and the mark is operated on.  */)
564
  (Lisp_Object beg, Lisp_Object end, Lisp_Object region_noncontiguous_p)
Jim Blandy's avatar
Jim Blandy committed
565
{
566
  return casify_pnc_region (CASE_DOWN, beg, end, region_noncontiguous_p);
Jim Blandy's avatar
Jim Blandy committed
567 568
}

569 570
DEFUN ("capitalize-region", Fcapitalize_region, Scapitalize_region, 2, 3,
       "(list (region-beginning) (region-end) (region-noncontiguous-p))",
571
       doc: /* Convert the region to capitalized form.
572 573
This means that each word's first character is converted to either
title case or upper case, and the rest to lower case.
574 575
In programs, give two arguments, the starting and ending
character positions to operate on.  */)
576
  (Lisp_Object beg, Lisp_Object end, Lisp_Object region_noncontiguous_p)
Jim Blandy's avatar
Jim Blandy committed
577
{
578
  return casify_pnc_region (CASE_CAPITALIZE, beg, end, region_noncontiguous_p);
Jim Blandy's avatar
Jim Blandy committed
579 580
}

581 582
/* Like Fcapitalize_region but change only the initials.  */

Paul Eggert's avatar
Paul Eggert committed
583
DEFUN ("upcase-initials-region", Fupcase_initials_region,
584 585
       Supcase_initials_region, 2, 3,
       "(list (region-beginning) (region-end) (region-noncontiguous-p))",
586
       doc: /* Upcase the initial of each word in the region.
587 588
This means that each word's first character is converted to either
title case or upper case, and the rest are left unchanged.
589 590
In programs, give two arguments, the starting and ending
character positions to operate on.  */)
591
     (Lisp_Object beg, Lisp_Object end, Lisp_Object region_noncontiguous_p)
592
{
593 594
  return casify_pnc_region (CASE_CAPITALIZE_UP, beg, end,
			    region_noncontiguous_p);
595
}
Jim Blandy's avatar
Jim Blandy committed
596

597
static Lisp_Object
598
casify_word (enum case_action flag, Lisp_Object arg)
Jim Blandy's avatar
Jim Blandy committed
599
{
600
  CHECK_FIXNUM (arg);
Tom Tromey's avatar
Tom Tromey committed
601
  ptrdiff_t farend = scan_words (PT, XFIXNUM (arg));
602
  if (!farend)
Tom Tromey's avatar
Tom Tromey committed
603
    farend = XFIXNUM (arg) <= 0 ? BEGV : ZV;
604
  SET_PT (casify_region (flag, make_fixnum (PT), make_fixnum (farend)));
605
  return Qnil;
Jim Blandy's avatar
Jim Blandy committed
606 607 608
}

DEFUN ("upcase-word", Fupcase_word, Supcase_word, 1, 1, "p",
609 610 611 612 613
       doc: /* Convert to upper case from point to end of word, moving over.

If point is in the middle of a word, the part of that word before point
is ignored when moving forward.

614 615
With negative argument, convert previous words but do not move.
See also `capitalize-word'.  */)
Dan Nicolaescu's avatar
Dan Nicolaescu committed
616
  (Lisp_Object arg)
Jim Blandy's avatar
Jim Blandy committed
617
{
618
  return casify_word (CASE_UP, arg);
Jim Blandy's avatar
Jim Blandy committed
619 620 621
}

DEFUN ("downcase-word", Fdowncase_word, Sdowncase_word, 1, 1, "p",
622 623 624 625 626
       doc: /* Convert to lower case from point to end of word, moving over.

If point is in the middle of a word, the part of that word before point
is ignored when moving forward.

627
With negative argument, convert previous words but do not move.  */)
Dan Nicolaescu's avatar
Dan Nicolaescu committed
628
  (Lisp_Object arg)
Jim Blandy's avatar
Jim Blandy committed
629
{
630
  return casify_word (CASE_DOWN, arg);
Jim Blandy's avatar
Jim Blandy committed
631 632 633
}

DEFUN ("capitalize-word", Fcapitalize_word, Scapitalize_word, 1, 1, "p",
634 635
       doc: /* Capitalize from point to the end of word, moving over.
With numerical argument ARG, capitalize the next ARG-1 words as well.
636 637
This gives the word(s) a first character in upper case
and the rest lower case.
638 639 640 641

If point is in the middle of a word, the part of that word before point
is ignored when moving forward.

642
With negative argument, capitalize previous words but do not move.  */)
Dan Nicolaescu's avatar
Dan Nicolaescu committed
643
  (Lisp_Object arg)
Jim Blandy's avatar
Jim Blandy committed
644
{
645
  return casify_word (CASE_CAPITALIZE, arg);
Jim Blandy's avatar
Jim Blandy committed
646 647
}

Andreas Schwab's avatar
Andreas Schwab committed
648
void
649
syms_of_casefiddle (void)
Jim Blandy's avatar
Jim Blandy committed
650
{
651
  DEFSYM (Qbounds, "bounds");
652
  DEFSYM (Qidentity, "identity");
653 654 655 656 657
  DEFSYM (Qtitlecase, "titlecase");
  DEFSYM (Qspecial_uppercase, "special-uppercase");
  DEFSYM (Qspecial_lowercase, "special-lowercase");
  DEFSYM (Qspecial_titlecase, "special-titlecase");

658 659 660 661 662 663 664 665 666 667 668 669 670 671 672
  DEFVAR_LISP ("region-extract-function", Vregion_extract_function,
	       doc: /* Function to get the region's content.
Called with one argument METHOD which can be:
- nil: return the content as a string (list of strings for
  non-contiguous regions).
- `delete-only': delete the region; the return value is undefined.
- `bounds': return the boundaries of the region as a list of one
  or more cons cells of the form (START . END).
- anything else: delete the region and return its content
  as a string (or list of strings for non-contiguous regions),
  after filtering it with `filter-buffer-substring', which
  is called, for each contiguous sub-region, with METHOD as its
  3rd argument.  */);
  Vregion_extract_function = Qnil; /* simple.el sets this.  */

Jim Blandy's avatar
Jim Blandy committed
673 674 675
  defsubr (&Supcase);
  defsubr (&Sdowncase);
  defsubr (&Scapitalize);
676
  defsubr (&Supcase_initials);
Jim Blandy's avatar
Jim Blandy committed
677 678 679
  defsubr (&Supcase_region);
  defsubr (&Sdowncase_region);
  defsubr (&Scapitalize_region);
680
  defsubr (&Supcase_initials_region);
Jim Blandy's avatar
Jim Blandy committed
681 682 683 684 685
  defsubr (&Supcase_word);
  defsubr (&Sdowncase_word);
  defsubr (&Scapitalize_word);
}

Andreas Schwab's avatar
Andreas Schwab committed
686
void
687
keys_of_casefiddle (void)
Jim Blandy's avatar
Jim Blandy committed
688
{
Juanma Barranquero's avatar
Juanma Barranquero committed
689
  initial_define_key (control_x_map, Ctl ('U'), "upcase-region");
Jim Blandy's avatar
Jim Blandy committed
690
  Fput (intern ("upcase-region"), Qdisabled, Qt);
Juanma Barranquero's avatar
Juanma Barranquero committed
691
  initial_define_key (control_x_map, Ctl ('L'), "downcase-region");
Jim Blandy's avatar
Jim Blandy committed
692 693
  Fput (intern ("downcase-region"), Qdisabled, Qt);

Jim Blandy's avatar
Jim Blandy committed
694 695 696 697
  initial_define_key (meta_map, 'u', "upcase-word");
  initial_define_key (meta_map, 'l', "downcase-word");
  initial_define_key (meta_map, 'c', "capitalize-word");
}