Tk Source Code

Check-in [2f3be9a6]
Login

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:[0819cc4018]: Patch from Paul Obermeier to make the branch build
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | revised_text_ober | tip-466
Files: files | file ages | folders
SHA1: 2f3be9a6f26f2581d76453bfc84f166fea725a3e
User & Date: fvogel 2017-02-22 23:08:19
Context
2017-02-24
10:58
Forgot to add generic/mystdint.h when committing Paul's patch (my bad, sorry). Closed-Leaf check-in: 6e28cd8d user: fvogel tags: revised_text_ober, tip-466
2017-02-22
23:08
[0819cc4018]: Patch from Paul Obermeier to make the branch build check-in: 2f3be9a6 user: fvogel tags: revised_text_ober, tip-466
2017-02-21
22:53
Silence compiler warning check-in: 96115bb3 user: fvogel tags: revised_text, tip-466
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Deleted generic/tkAlloc.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/*
 * tkAlloc.h --
 *
 *	This module provides an interface to memory allocation functions, this
 *	is: malloc(), realloc(), free(). This has the following advantages:
 *
 *	1. The whole features of the very valuable tool Valgrind can be used,
 *	   this requires to bypass the Tcl allocation functions.
 *
 *	2. Backport to version 8.5, this is important because the Mac version
 *	   of wish8.6 has event loop issues.
 *
 * Copyright (c) 2015-2017 Gregor Cramer
 *
 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#ifndef _TK_ALLOC
#define _TK_ALLOC

#include "tcl.h"

#if TK_VALGRIND

# include <stdlib.h>

/* enables compiler check that these functions will not be used */
# undef ckalloc
# undef ckrealloc
# undef ckfree

#else /* if !TK_VALGRIND */

/* the main reason for these definitions is portability to 8.5 */
# define malloc(size)		((void *) (ckalloc(size)))
# define realloc(ptr, size)	((void *) (ckrealloc((char *) (ptr), size)))
# define free(ptr)		ckfree((char *) (ptr))

#endif /* TK_VALGRIND */

#endif /* _TK_ALLOC */
/* vi:set ts=8 sw=4: */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






















































































Changes to generic/tkBitField.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/*
 * tkBitField.c --
 *
 *	This module implements bit field operations.
 *
 * Copyright (c) 2015-2017 Gregor Cramer
 *
 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "tkBitField.h"
#include "tkIntSet.h"
#include "tkAlloc.h"
#include <string.h>
#include <assert.h>

#if !(__STDC_VERSION__ >= 199901L || (defined(_MSC_VER) && _MSC_VER >= 1900))
# define _TK_NEED_IMPLEMENTATION
# include "tkBitFieldPriv.h"
#endif













<







1
2
3
4
5
6
7
8
9
10
11
12
13

14
15
16
17
18
19
20
/*
 * tkBitField.c --
 *
 *	This module implements bit field operations.
 *
 * Copyright (c) 2015-2017 Gregor Cramer
 *
 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "tkBitField.h"
#include "tkIntSet.h"

#include <string.h>
#include <assert.h>

#if !(__STDC_VERSION__ >= 199901L || (defined(_MSC_VER) && _MSC_VER >= 1900))
# define _TK_NEED_IMPLEMENTATION
# include "tkBitFieldPriv.h"
#endif
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
LsbIndex(uint32_t x)
{
    /* Source: http://graphics.stanford.edu/~seander/bithacks.html#ZerosOnRightLinear */
    static const unsigned MultiplyDeBruijnBitPosition[32] = {
	 0,  1, 28,  2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17,  4, 8,
	31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18,  6, 11,  5, 10, 9
    };
    return MultiplyDeBruijnBitPosition[((uint32_t) ((x & -((int32_t) x))*0x077cb531)) >> 27];
}
#  else
/* The "classical" method, but about 20% slower than the DeBruijn method on my system. */
static unsigned
LsbIndex(uint32_t x)
{
    unsigned ctz = 32;







|







122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
LsbIndex(uint32_t x)
{
    /* Source: http://graphics.stanford.edu/~seander/bithacks.html#ZerosOnRightLinear */
    static const unsigned MultiplyDeBruijnBitPosition[32] = {
	 0,  1, 28,  2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17,  4, 8,
	31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18,  6, 11,  5, 10, 9
    };
    return MultiplyDeBruijnBitPosition[((uint32_t) ((x & -x)*0x077cb531)) >> 27];
}
#  else
/* The "classical" method, but about 20% slower than the DeBruijn method on my system. */
static unsigned
LsbIndex(uint32_t x)
{
    unsigned ctz = 32;
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
TkBitDestroy(
    TkBitField **bfPtr)
{
    assert(bfPtr);

    if (*bfPtr) {
	DEBUG_ALLOC(Free(*bfPtr));
	free(*bfPtr);
	*bfPtr = NULL;
	DEBUG_ALLOC(tkBitCountDestroy++);
    }
}


TkBitField *
TkBitResize(
    TkBitField *bf,
    unsigned newSize)
{
    if (!bf) {
	bf = malloc(BF_SIZE(newSize));
	DEBUG_ALLOC(Use(bf));
	bf->size = newSize;
	bf->refCount = 1;
	bf->isSetFlag = false;
	memset(bf->bits, 0, BYTE_SIZE(newSize));
	DEBUG_ALLOC(tkBitCountNew++);
    } else {







|












|







259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
TkBitDestroy(
    TkBitField **bfPtr)
{
    assert(bfPtr);

    if (*bfPtr) {
	DEBUG_ALLOC(Free(*bfPtr));
	ckfree(*bfPtr);
	*bfPtr = NULL;
	DEBUG_ALLOC(tkBitCountDestroy++);
    }
}


TkBitField *
TkBitResize(
    TkBitField *bf,
    unsigned newSize)
{
    if (!bf) {
	bf = ckalloc(BF_SIZE(newSize));
	DEBUG_ALLOC(Use(bf));
	bf->size = newSize;
	bf->refCount = 1;
	bf->isSetFlag = false;
	memset(bf->bits, 0, BYTE_SIZE(newSize));
	DEBUG_ALLOC(tkBitCountNew++);
    } else {
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
	    bf->size = newSize;
	    ResetUnused(bf);
	    return bf;
	}

	if (bf->refCount <= 1) {
	    DEBUG_ALLOC(Free(bf));
	    bf = realloc((char *) bf, BF_SIZE(newSize));
	    DEBUG_ALLOC(Use(bf));
	} else {
	    TkBitField *newBF = malloc(BF_SIZE(newSize));
	    DEBUG_ALLOC(Use(newBF));
	    memcpy(newBF->bits, bf->bits, NBYTES(MIN(oldWords, newWords)));
	    newBF->refCount = 1;
	    newBF->isSetFlag = false;
	    bf->refCount -= 1;
	    bf = newBF;
	    DEBUG_ALLOC(tkBitCountNew++);







|


|







294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
	    bf->size = newSize;
	    ResetUnused(bf);
	    return bf;
	}

	if (bf->refCount <= 1) {
	    DEBUG_ALLOC(Free(bf));
	    bf = ckrealloc((char *) bf, BF_SIZE(newSize));
	    DEBUG_ALLOC(Use(bf));
	} else {
	    TkBitField *newBF = ckalloc(BF_SIZE(newSize));
	    DEBUG_ALLOC(Use(newBF));
	    memcpy(newBF->bits, bf->bits, NBYTES(MIN(oldWords, newWords)));
	    newBF->refCount = 1;
	    newBF->isSetFlag = false;
	    bf->refCount -= 1;
	    bf = newBF;
	    DEBUG_ALLOC(tkBitCountNew++);
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390

    assert(bf);

    if (size < 0) {
	size = bf->size;
    }

    copy = malloc(BF_SIZE(size));
    DEBUG_ALLOC(Use(copy));
    oldWords = NWORDS(bf->size);
    newWords = NWORDS(size);
    memcpy(copy->bits, bf->bits, NBYTES(MIN(oldWords, newWords)));
    if (newWords > oldWords) {
	memset(copy->bits + oldWords, 0, NBYTES(newWords - oldWords));
    }







|







375
376
377
378
379
380
381
382
383
384
385
386
387
388
389

    assert(bf);

    if (size < 0) {
	size = bf->size;
    }

    copy = ckalloc(BF_SIZE(size));
    DEBUG_ALLOC(Use(copy));
    oldWords = NWORDS(bf->size);
    newWords = NWORDS(size);
    memcpy(copy->bits, bf->bits, NBYTES(MIN(oldWords, newWords)));
    if (newWords > oldWords) {
	memset(copy->bits + oldWords, 0, NBYTES(newWords - oldWords));
    }

Changes to generic/tkBitField.h.

13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#define _TKBITFIELD

#ifndef _TK
#include "tk.h"
#endif

#include "tkBool.h"
#include <stdint.h>

#ifdef _MSC_VER
# if _MSC_VER >= 1900
#  define inline __inline
# else
#  define inline
# endif







|







13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#define _TKBITFIELD

#ifndef _TK
#include "tk.h"
#endif

#include "tkBool.h"
#include "mystdint.h"

#ifdef _MSC_VER
# if _MSC_VER >= 1900
#  define inline __inline
# else
#  define inline
# endif

Changes to generic/tkIntSet.c.

10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
 *
 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "tkIntSet.h"
#include "tkBitField.h"
#include "tkAlloc.h"

#if !(__STDC_VERSION__ >= 199901L || (defined(_MSC_VER) && _MSC_VER >= 1900))
# define _TK_NEED_IMPLEMENTATION
# include "tkIntSetPriv.h"
#endif

#include <string.h>







<







10
11
12
13
14
15
16

17
18
19
20
21
22
23
 *
 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "tkIntSet.h"
#include "tkBitField.h"


#if !(__STDC_VERSION__ >= 199901L || (defined(_MSC_VER) && _MSC_VER >= 1900))
# define _TK_NEED_IMPLEMENTATION
# include "tkIntSetPriv.h"
#endif

#include <string.h>
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
    return first;
}


TkIntSet *
TkIntSetNew()
{
    TkIntSet *set = malloc(SET_SIZE(0));
    set->end = set->buf;
    set->refCount = 0;
    set->isSetFlag = true;
    DEBUG_ALLOC(tkIntSetCountNew++);
    return set;
}


#if !TK_TEXT_DONT_USE_BITFIELDS

TkIntSet *
TkIntSetFromBits(
    const TkBitField *bf)
{
    unsigned size;
    TkIntSet *set;
    unsigned index = 0, i;

    size = TkBitCount(bf);
    set = malloc(SET_SIZE(NextPowerOf2(size)));
    set->end = set->buf + size;
    set->refCount = 1;
    set->isSetFlag = true;
    DEBUG_ALLOC(tkIntSetCountNew++);

    for (i = TkBitFindFirst(bf); i != TK_BIT_NPOS; i = TkBitFindNext(bf, i)) {
	set->buf[index++] = i;







|



















|







135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
    return first;
}


TkIntSet *
TkIntSetNew()
{
    TkIntSet *set = ckalloc(SET_SIZE(0));
    set->end = set->buf;
    set->refCount = 0;
    set->isSetFlag = true;
    DEBUG_ALLOC(tkIntSetCountNew++);
    return set;
}


#if !TK_TEXT_DONT_USE_BITFIELDS

TkIntSet *
TkIntSetFromBits(
    const TkBitField *bf)
{
    unsigned size;
    TkIntSet *set;
    unsigned index = 0, i;

    size = TkBitCount(bf);
    set = ckalloc(SET_SIZE(NextPowerOf2(size)));
    set->end = set->buf + size;
    set->refCount = 1;
    set->isSetFlag = true;
    DEBUG_ALLOC(tkIntSetCountNew++);

    for (i = TkBitFindFirst(bf); i != TK_BIT_NPOS; i = TkBitFindNext(bf, i)) {
	set->buf[index++] = i;
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
void
TkIntSetDestroy(
    TkIntSet **setPtr)
{
    assert(setPtr);

    if (*setPtr) {
	free(*setPtr);
	*setPtr = NULL;
	DEBUG_ALLOC(tkIntSetCountDestroy++);
    }
}


TkIntSet *
TkIntSetCopy(
    const TkIntSet *set)
{
    TkIntSet *newSet;
    unsigned size;

    assert(set);

    size = TkIntSetSize(set);
    newSet = malloc(SET_SIZE(NextPowerOf2(size)));
    newSet->end = newSet->buf + size;
    newSet->refCount = 1;
    newSet->isSetFlag = true;
    memcpy(newSet->buf, set->buf, size*sizeof(TkIntSetType));
    DEBUG_ALLOC(tkIntSetCountNew++);
    return newSet;
}







|
















|







178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
void
TkIntSetDestroy(
    TkIntSet **setPtr)
{
    assert(setPtr);

    if (*setPtr) {
	ckfree(*setPtr);
	*setPtr = NULL;
	DEBUG_ALLOC(tkIntSetCountDestroy++);
    }
}


TkIntSet *
TkIntSetCopy(
    const TkIntSet *set)
{
    TkIntSet *newSet;
    unsigned size;

    assert(set);

    size = TkIntSetSize(set);
    newSet = ckalloc(SET_SIZE(NextPowerOf2(size)));
    newSet->end = newSet->buf + size;
    newSet->refCount = 1;
    newSet->isSetFlag = true;
    memcpy(newSet->buf, set->buf, size*sizeof(TkIntSetType));
    DEBUG_ALLOC(tkIntSetCountNew++);
    return newSet;
}
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
    unsigned size;

    assert(src);
    assert(dst);
    assert(TkIntSetRefCount(dst) > 0);

    capacity1 = NextPowerOf2(TkIntSetSize(dst) + TkIntSetSize(src));
    set = malloc(SET_SIZE(capacity1));
    set->end = Join(set->buf, dst->buf, dst->end, src->buf, src->end);
    size = set->end - set->buf;
    capacity2 = NextPowerOf2(size);
    assert(capacity2 <= capacity1);
    DEBUG_ALLOC(tkIntSetCountNew++);

    if (capacity2 < capacity1) {
	set = realloc(set, SET_SIZE(capacity2));
	set->end = set->buf + size;
    }

    if (--dst->refCount == 0) {
	free(dst);
	DEBUG_ALLOC(tkIntSetCountDestroy++);
    }

    set->refCount = 1;
    set->isSetFlag = true;
    return set;
}







|







|




|







250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
    unsigned size;

    assert(src);
    assert(dst);
    assert(TkIntSetRefCount(dst) > 0);

    capacity1 = NextPowerOf2(TkIntSetSize(dst) + TkIntSetSize(src));
    set = ckalloc(SET_SIZE(capacity1));
    set->end = Join(set->buf, dst->buf, dst->end, src->buf, src->end);
    size = set->end - set->buf;
    capacity2 = NextPowerOf2(size);
    assert(capacity2 <= capacity1);
    DEBUG_ALLOC(tkIntSetCountNew++);

    if (capacity2 < capacity1) {
	set = ckrealloc(set, SET_SIZE(capacity2));
	set->end = set->buf + size;
    }

    if (--dst->refCount == 0) {
	ckfree(dst);
	DEBUG_ALLOC(tkIntSetCountDestroy++);
    }

    set->refCount = 1;
    set->isSetFlag = true;
    return set;
}
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356

    if (dst->buf == dst->end) {
	set = TkIntSetNew();
    } else {
	unsigned capacity1, capacity2, size;

	capacity1 = NextPowerOf2(TkIntSetSize(dst) + TkBitSize(src));
	set = malloc(SET_SIZE(capacity1));
	set->end = JoinBits(set->buf, dst->buf, dst->end, src);
	size = set->end - set->buf;
	capacity2 = NextPowerOf2(size);
	assert(capacity2 <= capacity1);
	DEBUG_ALLOC(tkIntSetCountNew++);

	if (capacity2 < capacity1) {
	    set = realloc(set, SET_SIZE(capacity2));
	    set->end = set->buf + size;
	}
    }

    if (--dst->refCount == 0) {
	free(dst);
	DEBUG_ALLOC(tkIntSetCountDestroy++);
    }

    set->refCount = 1;
    set->isSetFlag = true;
    return set;
}







|







|





|







327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355

    if (dst->buf == dst->end) {
	set = TkIntSetNew();
    } else {
	unsigned capacity1, capacity2, size;

	capacity1 = NextPowerOf2(TkIntSetSize(dst) + TkBitSize(src));
	set = ckalloc(SET_SIZE(capacity1));
	set->end = JoinBits(set->buf, dst->buf, dst->end, src);
	size = set->end - set->buf;
	capacity2 = NextPowerOf2(size);
	assert(capacity2 <= capacity1);
	DEBUG_ALLOC(tkIntSetCountNew++);

	if (capacity2 < capacity1) {
	    set = ckrealloc(set, SET_SIZE(capacity2));
	    set->end = set->buf + size;
	}
    }

    if (--dst->refCount == 0) {
	ckfree(dst);
	DEBUG_ALLOC(tkIntSetCountDestroy++);
    }

    set->refCount = 1;
    set->isSetFlag = true;
    return set;
}
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445

    assert(dst);
    assert(set1);
    assert(set2);
    assert(TkIntSetRefCount(dst) > 0);

    capacity1 = NextPowerOf2(TkIntSetSize(dst) + TkIntSetSize(set1) + TkIntSetSize(set2));
    set = malloc(SET_SIZE(capacity1));
    set->end = Join2(set->buf, dst->buf, dst->end, set1->buf, set1->end, set2->buf, set2->end);
    size = set->end - set->buf;
    capacity2 = NextPowerOf2(size);
    assert(capacity2 <= capacity1);
    DEBUG_ALLOC(tkIntSetCountNew++);

    if (capacity2 < capacity1) {
	set = realloc(set, SET_SIZE(capacity2));
	set->end = set->buf + size;
    }

    if (--dst->refCount == 0) {
	free(dst);
	DEBUG_ALLOC(tkIntSetCountDestroy++);
    }

    set->refCount = 1;
    set->isSetFlag = true;
    return set;
}







|







|




|







417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444

    assert(dst);
    assert(set1);
    assert(set2);
    assert(TkIntSetRefCount(dst) > 0);

    capacity1 = NextPowerOf2(TkIntSetSize(dst) + TkIntSetSize(set1) + TkIntSetSize(set2));
    set = ckalloc(SET_SIZE(capacity1));
    set->end = Join2(set->buf, dst->buf, dst->end, set1->buf, set1->end, set2->buf, set2->end);
    size = set->end - set->buf;
    capacity2 = NextPowerOf2(size);
    assert(capacity2 <= capacity1);
    DEBUG_ALLOC(tkIntSetCountNew++);

    if (capacity2 < capacity1) {
	set = ckrealloc(set, SET_SIZE(capacity2));
	set->end = set->buf + size;
    }

    if (--dst->refCount == 0) {
	ckfree(dst);
	DEBUG_ALLOC(tkIntSetCountDestroy++);
    }

    set->refCount = 1;
    set->isSetFlag = true;
    return set;
}
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504

    assert(src);
    assert(dst);
    assert(TkIntSetRefCount(dst) > 0);

    size = MIN(TkIntSetSize(src), TkIntSetSize(dst));
    capacity1 = NextPowerOf2(size);
    set = malloc(SET_SIZE(capacity1));
    set->end = Intersect(set->buf, dst->buf, dst->end, src->buf, src->end);
    size = set->end - set->buf;
    capacity2 = NextPowerOf2(size);
    assert(capacity2 <= capacity1);
    DEBUG_ALLOC(tkIntSetCountNew++);

    if (capacity2 < capacity1) {
	set = realloc(set, SET_SIZE(capacity2));
	set->end = set->buf + size;
    }

    if (--dst->refCount == 0) {
	free(dst);
	DEBUG_ALLOC(tkIntSetCountDestroy++);
    }

    set->refCount = 1;
    set->isSetFlag = true;
    return set;
}







|







|




|







476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503

    assert(src);
    assert(dst);
    assert(TkIntSetRefCount(dst) > 0);

    size = MIN(TkIntSetSize(src), TkIntSetSize(dst));
    capacity1 = NextPowerOf2(size);
    set = ckalloc(SET_SIZE(capacity1));
    set->end = Intersect(set->buf, dst->buf, dst->end, src->buf, src->end);
    size = set->end - set->buf;
    capacity2 = NextPowerOf2(size);
    assert(capacity2 <= capacity1);
    DEBUG_ALLOC(tkIntSetCountNew++);

    if (capacity2 < capacity1) {
	set = ckrealloc(set, SET_SIZE(capacity2));
	set->end = set->buf + size;
    }

    if (--dst->refCount == 0) {
	ckfree(dst);
	DEBUG_ALLOC(tkIntSetCountDestroy++);
    }

    set->refCount = 1;
    set->isSetFlag = true;
    return set;
}
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
    assert(dst);
    assert(TkIntSetRefCount(dst) > 0);

    size = TkBitCount(src);

    size = MIN(TkIntSetSize(dst), TkBitCount(src));
    capacity1 = NextPowerOf2(size);
    set = malloc(SET_SIZE(capacity1));
    set->end = IntersectBits(set->buf, dst->buf, dst->end, src);
    size = set->end - set->buf;
    capacity2 = NextPowerOf2(size);
    assert(capacity2 <= capacity1);
    DEBUG_ALLOC(tkIntSetCountNew++);

    if (capacity2 < capacity1) {
	set = realloc(set, SET_SIZE(capacity2));
	set->end = set->buf + size;
    }

    if (--dst->refCount == 0) {
	free(dst);
	DEBUG_ALLOC(tkIntSetCountDestroy++);
    }

    set->refCount = 1;
    set->isSetFlag = true;
    return set;
}







|







|




|







539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
    assert(dst);
    assert(TkIntSetRefCount(dst) > 0);

    size = TkBitCount(src);

    size = MIN(TkIntSetSize(dst), TkBitCount(src));
    capacity1 = NextPowerOf2(size);
    set = ckalloc(SET_SIZE(capacity1));
    set->end = IntersectBits(set->buf, dst->buf, dst->end, src);
    size = set->end - set->buf;
    capacity2 = NextPowerOf2(size);
    assert(capacity2 <= capacity1);
    DEBUG_ALLOC(tkIntSetCountNew++);

    if (capacity2 < capacity1) {
	set = ckrealloc(set, SET_SIZE(capacity2));
	set->end = set->buf + size;
    }

    if (--dst->refCount == 0) {
	ckfree(dst);
	DEBUG_ALLOC(tkIntSetCountDestroy++);
    }

    set->refCount = 1;
    set->isSetFlag = true;
    return set;
}
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
    unsigned size;

    assert(src);
    assert(dst);
    assert(TkIntSetRefCount(dst) > 0);

    capacity1 = NextPowerOf2(TkIntSetSize(dst));
    set = malloc(SET_SIZE(capacity1));
    set->end = Remove(set->buf, dst->buf, dst->end, src->buf, src->end);
    size = set->end - set->buf;
    capacity2 = NextPowerOf2(size);
    assert(capacity2 <= capacity1);
    DEBUG_ALLOC(tkIntSetCountNew++);

    if (capacity2 < capacity1) {
	set = realloc(set, SET_SIZE(capacity2));
	set->end = set->buf + size;
    }

    if (--dst->refCount == 0) {
	free(dst);
	DEBUG_ALLOC(tkIntSetCountDestroy++);
    }

    set->refCount = 1;
    set->isSetFlag = true;
    return set;
}







|







|




|







605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
    unsigned size;

    assert(src);
    assert(dst);
    assert(TkIntSetRefCount(dst) > 0);

    capacity1 = NextPowerOf2(TkIntSetSize(dst));
    set = ckalloc(SET_SIZE(capacity1));
    set->end = Remove(set->buf, dst->buf, dst->end, src->buf, src->end);
    size = set->end - set->buf;
    capacity2 = NextPowerOf2(size);
    assert(capacity2 <= capacity1);
    DEBUG_ALLOC(tkIntSetCountNew++);

    if (capacity2 < capacity1) {
	set = ckrealloc(set, SET_SIZE(capacity2));
	set->end = set->buf + size;
    }

    if (--dst->refCount == 0) {
	ckfree(dst);
	DEBUG_ALLOC(tkIntSetCountDestroy++);
    }

    set->refCount = 1;
    set->isSetFlag = true;
    return set;
}
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
    unsigned size;

    assert(src);
    assert(dst);
    assert(TkIntSetRefCount(dst) > 0);

    capacity1 = NextPowerOf2(TkIntSetSize(dst));
    set = malloc(SET_SIZE(capacity1));
    set->end = RemoveBits(set->buf, dst->buf, dst->end, src);
    size = set->end - set->buf;
    capacity2 = NextPowerOf2(size);
    assert(capacity2 <= capacity1);
    DEBUG_ALLOC(tkIntSetCountNew++);

    if (capacity2 < capacity1) {
	set = realloc(set, SET_SIZE(capacity2));
	set->end = set->buf + size;
    }

    if (--dst->refCount == 0) {
	free(dst);
	DEBUG_ALLOC(tkIntSetCountDestroy++);
    }

    set->refCount = 1;
    set->isSetFlag = true;
    return set;
}







|







|




|







670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
    unsigned size;

    assert(src);
    assert(dst);
    assert(TkIntSetRefCount(dst) > 0);

    capacity1 = NextPowerOf2(TkIntSetSize(dst));
    set = ckalloc(SET_SIZE(capacity1));
    set->end = RemoveBits(set->buf, dst->buf, dst->end, src);
    size = set->end - set->buf;
    capacity2 = NextPowerOf2(size);
    assert(capacity2 <= capacity1);
    DEBUG_ALLOC(tkIntSetCountNew++);

    if (capacity2 < capacity1) {
	set = ckrealloc(set, SET_SIZE(capacity2));
	set->end = set->buf + size;
    }

    if (--dst->refCount == 0) {
	ckfree(dst);
	DEBUG_ALLOC(tkIntSetCountDestroy++);
    }

    set->refCount = 1;
    set->isSetFlag = true;
    return set;
}
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
    unsigned size;

    assert(src);
    assert(dst);
    assert(TkIntSetRefCount(dst) > 0);

    capacity1 = NextPowerOf2(TkIntSetSize(src));
    set = malloc(SET_SIZE(capacity1));
    set->end = ComplementTo(set->buf, dst->buf, dst->end, src->buf, src->end);
    size = set->end - set->buf;
    capacity2 = NextPowerOf2(size);
    assert(capacity2 <= capacity1);
    DEBUG_ALLOC(tkIntSetCountNew++);

    if (capacity2 < capacity1) {
	set = realloc(set, SET_SIZE(capacity2));
	set->end = set->buf + size;
    }

    if (--dst->refCount == 0) {
	free(dst);
	DEBUG_ALLOC(tkIntSetCountDestroy++);
    }

    set->refCount = 1;
    set->isSetFlag = true;
    return set;
}







|







|




|







719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
    unsigned size;

    assert(src);
    assert(dst);
    assert(TkIntSetRefCount(dst) > 0);

    capacity1 = NextPowerOf2(TkIntSetSize(src));
    set = ckalloc(SET_SIZE(capacity1));
    set->end = ComplementTo(set->buf, dst->buf, dst->end, src->buf, src->end);
    size = set->end - set->buf;
    capacity2 = NextPowerOf2(size);
    assert(capacity2 <= capacity1);
    DEBUG_ALLOC(tkIntSetCountNew++);

    if (capacity2 < capacity1) {
	set = ckrealloc(set, SET_SIZE(capacity2));
	set->end = set->buf + size;
    }

    if (--dst->refCount == 0) {
	ckfree(dst);
	DEBUG_ALLOC(tkIntSetCountDestroy++);
    }

    set->refCount = 1;
    set->isSetFlag = true;
    return set;
}
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
    unsigned size;

    assert(src);
    assert(dst);
    assert(TkIntSetRefCount(dst) > 0);

    capacity1 = NextPowerOf2(TkBitSize(src));
    set = malloc(SET_SIZE(capacity1));
    set->end = ComplementToBits(set->buf, dst->buf, dst->end, src);
    size = set->end - set->buf;
    capacity2 = NextPowerOf2(size);
    assert(capacity2 <= capacity1);
    DEBUG_ALLOC(tkIntSetCountNew++);

    if (capacity2 < capacity1) {
	set = realloc(set, SET_SIZE(capacity2));
	set->end = set->buf + size;
    }

    if (--dst->refCount == 0) {
	free(dst);
	DEBUG_ALLOC(tkIntSetCountDestroy++);
    }

    set->refCount = 1;
    set->isSetFlag = true;
    return set;
}







|







|




|







788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
    unsigned size;

    assert(src);
    assert(dst);
    assert(TkIntSetRefCount(dst) > 0);

    capacity1 = NextPowerOf2(TkBitSize(src));
    set = ckalloc(SET_SIZE(capacity1));
    set->end = ComplementToBits(set->buf, dst->buf, dst->end, src);
    size = set->end - set->buf;
    capacity2 = NextPowerOf2(size);
    assert(capacity2 <= capacity1);
    DEBUG_ALLOC(tkIntSetCountNew++);

    if (capacity2 < capacity1) {
	set = ckrealloc(set, SET_SIZE(capacity2));
	set->end = set->buf + size;
    }

    if (--dst->refCount == 0) {
	ckfree(dst);
	DEBUG_ALLOC(tkIntSetCountDestroy++);
    }

    set->refCount = 1;
    set->isSetFlag = true;
    return set;
}
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907

    assert(dst);
    assert(set1);
    assert(set2);
    assert(TkIntSetRefCount(dst) > 0);

    capacity1 = NextPowerOf2(TkIntSetSize(dst) + TkIntSetSize(set1));
    set = malloc(SET_SIZE(capacity1));
    set->end = JoinComplementTo(
	    set->buf, dst->buf, dst->end, set1->buf, set1->end, set2->buf, set2->end);
    size = set->end - set->buf;
    capacity2 = NextPowerOf2(size);
    assert(capacity2 <= capacity1);
    DEBUG_ALLOC(tkIntSetCountNew++);

    if (capacity2 < capacity1) {
	set = realloc(set, SET_SIZE(capacity2));
	set->end = set->buf + size;
    }

    if (--dst->refCount == 0) {
	free(dst);
	DEBUG_ALLOC(tkIntSetCountDestroy++);
    }

    set->refCount = 1;
    set->isSetFlag = true;
    return set;
}







|








|




|







878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906

    assert(dst);
    assert(set1);
    assert(set2);
    assert(TkIntSetRefCount(dst) > 0);

    capacity1 = NextPowerOf2(TkIntSetSize(dst) + TkIntSetSize(set1));
    set = ckalloc(SET_SIZE(capacity1));
    set->end = JoinComplementTo(
	    set->buf, dst->buf, dst->end, set1->buf, set1->end, set2->buf, set2->end);
    size = set->end - set->buf;
    capacity2 = NextPowerOf2(size);
    assert(capacity2 <= capacity1);
    DEBUG_ALLOC(tkIntSetCountNew++);

    if (capacity2 < capacity1) {
	set = ckrealloc(set, SET_SIZE(capacity2));
	set->end = set->buf + size;
    }

    if (--dst->refCount == 0) {
	ckfree(dst);
	DEBUG_ALLOC(tkIntSetCountDestroy++);
    }

    set->refCount = 1;
    set->isSetFlag = true;
    return set;
}
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024

    assert(dst);
    assert(set1);
    assert(set2);
    assert(TkIntSetRefCount(dst) > 0);

    capacity1 = NextPowerOf2(TkIntSetSize(dst) + TkIntSetSize(set1) + TkIntSetSize(set2));
    set = malloc(SET_SIZE(capacity1));
    set->end = JoinNonIntersection(
	    set->buf, dst->buf, dst->end, set1->buf, set1->end, set2->buf, set2->end);
    size = set->end - set->buf;
    capacity2 = NextPowerOf2(size);
    assert(capacity2 <= capacity1);
    DEBUG_ALLOC(tkIntSetCountNew++);

    if (capacity2 < capacity1) {
	set = realloc(set, SET_SIZE(capacity2));
	set->end = set->buf + size;
    }

    if (--dst->refCount == 0) {
	free(dst);
	DEBUG_ALLOC(tkIntSetCountDestroy++);
    }

    set->refCount = 1;
    set->isSetFlag = true;
    return set;
}







|








|




|







995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023

    assert(dst);
    assert(set1);
    assert(set2);
    assert(TkIntSetRefCount(dst) > 0);

    capacity1 = NextPowerOf2(TkIntSetSize(dst) + TkIntSetSize(set1) + TkIntSetSize(set2));
    set = ckalloc(SET_SIZE(capacity1));
    set->end = JoinNonIntersection(
	    set->buf, dst->buf, dst->end, set1->buf, set1->end, set2->buf, set2->end);
    size = set->end - set->buf;
    capacity2 = NextPowerOf2(size);
    assert(capacity2 <= capacity1);
    DEBUG_ALLOC(tkIntSetCountNew++);

    if (capacity2 < capacity1) {
	set = ckrealloc(set, SET_SIZE(capacity2));
	set->end = set->buf + size;
    }

    if (--dst->refCount == 0) {
	ckfree(dst);
	DEBUG_ALLOC(tkIntSetCountDestroy++);
    }

    set->refCount = 1;
    set->isSetFlag = true;
    return set;
}
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
    set2P = set2->buf;
    set1End = set1->end;
    set2End = set2->end;

    size1 = TkIntSetSize(set1) + TkIntSetSize(set2);
    size2 = MIN(TkIntSetSize(set1), TkIntSetSize(set2));
    size = size1 + 2*size2;
    res1 = size <= sizeof(buffer)/sizeof(buffer[0]) ? buffer : malloc(size*sizeof(TkIntSetType));
    res2 = res1 + size1;
    res3 = res2 + size2;

    res1End = Join(res1, set1P, set1End, set2P, set2End);
    res2End = Intersect(res2, set1P, set1End, set2P, set2End);
    res3End = ComplementTo(res3, res1, res1End, res2, res2End);

    capacity1 = NextPowerOf2(TkIntSetSize(dst) + TkIntSetSize(add) + (res3End - res3));
    set = malloc(SET_SIZE(capacity1));
    set->end = Join2(set->buf, dst->buf, dst->end, add->buf, add->end, res3, res3End);
    size = set->end - set->buf;
    capacity2 = NextPowerOf2(size);
    assert(capacity2 <= capacity1);
    DEBUG_ALLOC(tkIntSetCountNew++);

    if (capacity2 < capacity1) {
	set = realloc(set, SET_SIZE(capacity2));
	set->end = set->buf + size;
    }

    if (--dst->refCount == 0) {
	free(dst);
	DEBUG_ALLOC(tkIntSetCountDestroy++);
    }

    if (res1 != buffer) {
	free(res1);
    }
    set->refCount = 1;
    set->isSetFlag = true;
    return set;
}









|








|







|




|




|







1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
    set2P = set2->buf;
    set1End = set1->end;
    set2End = set2->end;

    size1 = TkIntSetSize(set1) + TkIntSetSize(set2);
    size2 = MIN(TkIntSetSize(set1), TkIntSetSize(set2));
    size = size1 + 2*size2;
    res1 = size <= sizeof(buffer)/sizeof(buffer[0]) ? buffer : ckalloc(size*sizeof(TkIntSetType));
    res2 = res1 + size1;
    res3 = res2 + size2;

    res1End = Join(res1, set1P, set1End, set2P, set2End);
    res2End = Intersect(res2, set1P, set1End, set2P, set2End);
    res3End = ComplementTo(res3, res1, res1End, res2, res2End);

    capacity1 = NextPowerOf2(TkIntSetSize(dst) + TkIntSetSize(add) + (res3End - res3));
    set = ckalloc(SET_SIZE(capacity1));
    set->end = Join2(set->buf, dst->buf, dst->end, add->buf, add->end, res3, res3End);
    size = set->end - set->buf;
    capacity2 = NextPowerOf2(size);
    assert(capacity2 <= capacity1);
    DEBUG_ALLOC(tkIntSetCountNew++);

    if (capacity2 < capacity1) {
	set = ckrealloc(set, SET_SIZE(capacity2));
	set->end = set->buf + size;
    }

    if (--dst->refCount == 0) {
	ckfree(dst);
	DEBUG_ALLOC(tkIntSetCountDestroy++);
    }

    if (res1 != buffer) {
	ckfree(res1);
    }
    set->refCount = 1;
    set->isSetFlag = true;
    return set;
}


1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
    assert(dst);
    assert(set1);
    assert(set2);
    assert(TkIntSetRefCount(dst) > 0);

    capacity2 = TkIntSetSize(dst) + TkIntSetSize(set1);
    capacity1 = NextPowerOf2(2*capacity2);
    set = malloc(SET_SIZE(capacity1));
    buf1 = set->buf + capacity2;
    buf2 = buf1 + TkIntSetSize(dst);
    end1 = Remove(buf1, dst->buf, dst->end, set1->buf, set1->end);
    end2 = Remove(buf2, set1->buf, set1->end, set2->buf, set2->end);
    set->end = Join(set->buf, buf1, end1, buf2, end2);
    size = set->end - set->buf;
    capacity2 = NextPowerOf2(size);
    assert(capacity2 <= capacity1);
    DEBUG_ALLOC(tkIntSetCountNew++);

    if (capacity2 < capacity1) {
	set = realloc(set, SET_SIZE(capacity2));
	set->end = set->buf + size;
    }

    if (--dst->refCount == 0) {
	free(dst);
	DEBUG_ALLOC(tkIntSetCountDestroy++);
    }

    set->refCount = 1;
    set->isSetFlag = true;
    return set;
}







|











|




|







1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
    assert(dst);
    assert(set1);
    assert(set2);
    assert(TkIntSetRefCount(dst) > 0);

    capacity2 = TkIntSetSize(dst) + TkIntSetSize(set1);
    capacity1 = NextPowerOf2(2*capacity2);
    set = ckalloc(SET_SIZE(capacity1));
    buf1 = set->buf + capacity2;
    buf2 = buf1 + TkIntSetSize(dst);
    end1 = Remove(buf1, dst->buf, dst->end, set1->buf, set1->end);
    end2 = Remove(buf2, set1->buf, set1->end, set2->buf, set2->end);
    set->end = Join(set->buf, buf1, end1, buf2, end2);
    size = set->end - set->buf;
    capacity2 = NextPowerOf2(size);
    assert(capacity2 <= capacity1);
    DEBUG_ALLOC(tkIntSetCountNew++);

    if (capacity2 < capacity1) {
	set = ckrealloc(set, SET_SIZE(capacity2));
	set->end = set->buf + size;
    }

    if (--dst->refCount == 0) {
	ckfree(dst);
	DEBUG_ALLOC(tkIntSetCountDestroy++);
    }

    set->refCount = 1;
    set->isSetFlag = true;
    return set;
}
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
    TkIntSet *set,
    TkIntSetType *pos,
    unsigned n)
{
    unsigned size = set->end - set->buf;

    if (IsPowerOf2(size)) {
	TkIntSet *newSet = malloc(SET_SIZE(MAX(2*size, 1)));
	unsigned offs = pos - set->buf;

	assert(offs <= size);
	memcpy(newSet->buf, set->buf, offs*sizeof(TkIntSetType));
	memcpy(newSet->buf + offs + 1, pos, (size - offs)*sizeof(TkIntSetType));
	newSet->end = newSet->buf + size + 1;
	newSet->refCount = 1;
	newSet->isSetFlag = true;
	DEBUG_ALLOC(tkIntSetCountNew++);

	if (--set->refCount == 0) {
	    free(set);
	    DEBUG_ALLOC(tkIntSetCountDestroy++);
	}

	set = newSet;
	pos = set->buf + offs;
    } else {
	memmove(pos + 1, pos, (set->end - pos)*sizeof(TkIntSetType));







|











|







1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
    TkIntSet *set,
    TkIntSetType *pos,
    unsigned n)
{
    unsigned size = set->end - set->buf;

    if (IsPowerOf2(size)) {
	TkIntSet *newSet = ckalloc(SET_SIZE(MAX(2*size, 1)));
	unsigned offs = pos - set->buf;

	assert(offs <= size);
	memcpy(newSet->buf, set->buf, offs*sizeof(TkIntSetType));
	memcpy(newSet->buf + offs + 1, pos, (size - offs)*sizeof(TkIntSetType));
	newSet->end = newSet->buf + size + 1;
	newSet->refCount = 1;
	newSet->isSetFlag = true;
	DEBUG_ALLOC(tkIntSetCountNew++);

	if (--set->refCount == 0) {
	    ckfree(set);
	    DEBUG_ALLOC(tkIntSetCountDestroy++);
	}

	set = newSet;
	pos = set->buf + offs;
    } else {
	memmove(pos + 1, pos, (set->end - pos)*sizeof(TkIntSetType));
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
    TkIntSet *set,
    TkIntSetType *pos,
    unsigned n)
{
    unsigned size = set->end - set->buf - 1;

    if (IsPowerOf2(size)) {
	TkIntSet *newSet = malloc(SET_SIZE(size));
	unsigned offs = pos - set->buf;

	memcpy(newSet->buf, set->buf, offs*sizeof(TkIntSetType));
	memcpy(newSet->buf + offs, pos + 1, (size - offs)*sizeof(TkIntSetType));
	newSet->end = newSet->buf + size;
	newSet->refCount = 1;
	newSet->isSetFlag = true;
	DEBUG_ALLOC(tkIntSetCountNew++);

	if (--set->refCount == 0) {
	    free(set);
	    DEBUG_ALLOC(tkIntSetCountDestroy++);
	}

	set = newSet;
    } else {
	memmove(pos, pos + 1, (set->end - pos - 1)*sizeof(TkIntSetType));
	set->end -= 1;







|










|







1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
    TkIntSet *set,
    TkIntSetType *pos,
    unsigned n)
{
    unsigned size = set->end - set->buf - 1;

    if (IsPowerOf2(size)) {
	TkIntSet *newSet = ckalloc(SET_SIZE(size));
	unsigned offs = pos - set->buf;

	memcpy(newSet->buf, set->buf, offs*sizeof(TkIntSetType));
	memcpy(newSet->buf + offs, pos + 1, (size - offs)*sizeof(TkIntSetType));
	newSet->end = newSet->buf + size;
	newSet->refCount = 1;
	newSet->isSetFlag = true;
	DEBUG_ALLOC(tkIntSetCountNew++);

	if (--set->refCount == 0) {
	    ckfree(set);
	    DEBUG_ALLOC(tkIntSetCountDestroy++);
	}

	set = newSet;
    } else {
	memmove(pos, pos + 1, (set->end - pos - 1)*sizeof(TkIntSetType));
	set->end -= 1;
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
    assert(set);
    assert(TkIntSetRefCount(set) > 0);

    if (set->buf == set->end) {
	return set;
    }

    newSet = malloc(SET_SIZE(0));
    newSet->end = newSet->buf;
    newSet->refCount = 1;
    newSet->isSetFlag = true;
    DEBUG_ALLOC(tkIntSetCountNew++);

    if (--set->refCount == 0) {
	free(set);
	DEBUG_ALLOC(tkIntSetCountDestroy++);
    }

    return newSet;
}









|






|







1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
    assert(set);
    assert(TkIntSetRefCount(set) > 0);

    if (set->buf == set->end) {
	return set;
    }

    newSet = ckalloc(SET_SIZE(0));
    newSet->end = newSet->buf;
    newSet->refCount = 1;
    newSet->isSetFlag = true;
    DEBUG_ALLOC(tkIntSetCountNew++);

    if (--set->refCount == 0) {
	ckfree(set);
	DEBUG_ALLOC(tkIntSetCountDestroy++);
    }

    return newSet;
}


1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676

    assert(dst);
    assert(add);
    assert(sub);
    assert(TkIntSetRefCount(dst) > 0);

    capacity1 = NextPowerOf2(TkIntSetSize(dst) + TkIntSetSize(add));
    set = malloc(SET_SIZE(capacity1));
    set->end = InnerJoinDifference(set->buf, dst->buf, dst->end, add->buf, add->end, sub->buf, sub->end);
    size = set->end - set->buf;
    capacity2 = NextPowerOf2(size);
    assert(capacity2 <= capacity1);
    DEBUG_ALLOC(tkIntSetCountNew++);

    if (capacity2 < capacity1) {
	set = realloc(set, SET_SIZE(capacity2));
	set->end = set->buf + size;
    }

    if (--dst->refCount == 0) {
	free(dst);
	DEBUG_ALLOC(tkIntSetCountDestroy++);
    }

    set->refCount = 1;
    set->isSetFlag = true;
    return set;
}







|







|




|







1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675

    assert(dst);
    assert(add);
    assert(sub);
    assert(TkIntSetRefCount(dst) > 0);

    capacity1 = NextPowerOf2(TkIntSetSize(dst) + TkIntSetSize(add));
    set = ckalloc(SET_SIZE(capacity1));
    set->end = InnerJoinDifference(set->buf, dst->buf, dst->end, add->buf, add->end, sub->buf, sub->end);
    size = set->end - set->buf;
    capacity2 = NextPowerOf2(size);
    assert(capacity2 <= capacity1);
    DEBUG_ALLOC(tkIntSetCountNew++);

    if (capacity2 < capacity1) {
	set = ckrealloc(set, SET_SIZE(capacity2));
	set->end = set->buf + size;
    }

    if (--dst->refCount == 0) {
	ckfree(dst);
	DEBUG_ALLOC(tkIntSetCountDestroy++);
    }

    set->refCount = 1;
    set->isSetFlag = true;
    return set;
}
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
	/* (set2 & add2) + (add2 - sub2) == nil */
	return TkIntSetDisjunctive(set2, add2)
		&& DifferenceIsEmpty(add2->buf, add2->end, sub2->buf, sub2->end);
    }

    diffSize = TkIntSetSize(add2);
    inscSize = MIN(TkIntSetSize(set2), diffSize);
    inscBuf = inscSize <= sizeof(buf1)/sizeof(buf1[0]) ? buf1 : malloc(inscSize*sizeof(buf1[0]));
    inscEnd = Intersect(inscP = inscBuf, set2->buf, set2->end, add2->buf, add2->end);

    if (inscP == inscEnd) {
	/* set1 == (add2 - sub2) */
	isEqual = TkIntSetIsEqualToDifference(set1, add2, sub2);
    } else {
	diffBuf = diffSize <= sizeof(buf2)/sizeof(buf2[0]) ? buf2 : malloc(diffSize*sizeof(buf2[0]));
	diffEnd = Remove(diffP = diffBuf, add2->buf, add2->end, sub2->buf, sub2->end);

	if (diffP == diffEnd) {
	    /* set1 == inscP */
	    isEqual = TestIfEqual(set1->buf, set1->end, inscP, inscEnd);
	} else {
	    /* set1 == inscP + diffP */
	    isEqual = EqualToJoin(set1->buf, set1->end, inscP, inscEnd, diffP, diffEnd);
	}

	if (diffBuf != buf2) { free(diffBuf); }
    }

    if (inscBuf != buf1) { free(inscBuf); }

    return isEqual;
}


static bool
InnerJoinDifferenceIsEqual(







|






|










|


|







1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
	/* (set2 & add2) + (add2 - sub2) == nil */
	return TkIntSetDisjunctive(set2, add2)
		&& DifferenceIsEmpty(add2->buf, add2->end, sub2->buf, sub2->end);
    }

    diffSize = TkIntSetSize(add2);
    inscSize = MIN(TkIntSetSize(set2), diffSize);
    inscBuf = inscSize <= sizeof(buf1)/sizeof(buf1[0]) ? buf1 : ckalloc(inscSize*sizeof(buf1[0]));
    inscEnd = Intersect(inscP = inscBuf, set2->buf, set2->end, add2->buf, add2->end);

    if (inscP == inscEnd) {
	/* set1 == (add2 - sub2) */
	isEqual = TkIntSetIsEqualToDifference(set1, add2, sub2);
    } else {
	diffBuf = diffSize <= sizeof(buf2)/sizeof(buf2[0]) ? buf2 : ckalloc(diffSize*sizeof(buf2[0]));
	diffEnd = Remove(diffP = diffBuf, add2->buf, add2->end, sub2->buf, sub2->end);

	if (diffP == diffEnd) {
	    /* set1 == inscP */
	    isEqual = TestIfEqual(set1->buf, set1->end, inscP, inscEnd);
	} else {
	    /* set1 == inscP + diffP */
	    isEqual = EqualToJoin(set1->buf, set1->end, inscP, inscEnd, diffP, diffEnd);
	}

	if (diffBuf != buf2) { ckfree(diffBuf); }
    }

    if (inscBuf != buf1) { ckfree(inscBuf); }

    return isEqual;
}


static bool
InnerJoinDifferenceIsEqual(

Changes to generic/tkIntSet.h.

13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#define _TKINTSET

#ifndef _TK
#include "tk.h"
#endif

#include "tkBool.h"
#include <stdint.h>

#if defined(__GNUC__) || defined(__clang__)
# define __warn_unused__ __attribute__((warn_unused_result))
#else
# define __warn_unused__
#endif








|







13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#define _TKINTSET

#ifndef _TK
#include "tk.h"
#endif

#include "tkBool.h"
#include "mystdint.h"

#if defined(__GNUC__) || defined(__clang__)
# define __warn_unused__ __attribute__((warn_unused_result))
#else
# define __warn_unused__
#endif

Changes to generic/tkQTree.c.

42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
 * Copyright (c) 2015-2017 Gregor Cramer
 *
 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "tkQTree.h"
#include "tkAlloc.h"

#if !(__STDC_VERSION__ >= 199901L || (defined(_MSC_VER) && _MSC_VER >= 1900))
# define _TK_NEED_IMPLEMENTATION
# include "tkQTreePriv.h"
#endif

#include <tcl.h>







<







42
43
44
45
46
47
48

49
50
51
52
53
54
55
 * Copyright (c) 2015-2017 Gregor Cramer
 *
 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "tkQTree.h"


#if !(__STDC_VERSION__ >= 199901L || (defined(_MSC_VER) && _MSC_VER >= 1900))
# define _TK_NEED_IMPLEMENTATION
# include "tkQTreePriv.h"
#endif

#include <tcl.h>
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
{
    Element *elem;

    assert(tree);
    assert(rect);

    DEBUG_ALLOC(tkQTreeCountNewElement++);
    elem = malloc(sizeof(Element));
    elem->prev = NULL;
    if ((elem->next = tree->elem)) {
	elem->next->prev = elem;
    }
    tree->elem = elem;
    elem->bbox = *rect;
    elem->uid = uid;
    elem->state = initialState;
    elem->epoch = 0;
    return elem;
}


static Node *
NewNode(int initialPartialCount)
{
    Node *n;

    DEBUG_ALLOC(tkQTreeCountNewNode++);
    n = memset(malloc(sizeof(Node)), 0, sizeof(Node));
    n->countPartial = initialPartialCount;
    return n;
}


static void
FreeItems(
    Item *item)
{
    while (item) {
	Item *next = item->next;
	free(item);
	item = next;
	DEBUG_ALLOC(tkQTreeCountDestroyItem++);
    }
}


static void
FreeNode(
    Node *node)
{
    if (node) {
	if (node->countPartial >= 0) {
	    FreeItems(node->partialItem);
	} else {
	    FreeNode(node->ne);
	    FreeNode(node->nw);
	    FreeNode(node->se);
	    FreeNode(node->sw);
	}
	FreeItems(node->spanningItem);
	free(node);
	DEBUG_ALLOC(tkQTreeCountDestroyNode++);
    }
}


static void
FreeElements(
    Element *elem)
{
    while (elem) {
	Element *next = elem->next;
	free(elem);
	elem = next;
	DEBUG_ALLOC(tkQTreeCountDestroyElement++);
    }
}


static void
AddItem(
    Item **itemPtr,
    Element *elem)
{
    Item *newItem;

    assert(itemPtr);
    assert(elem);

    DEBUG_ALLOC(tkQTreeCountNewItem++);
    newItem = malloc(sizeof(Item));
    newItem->elem = elem;
    newItem->next = *itemPtr;
    *itemPtr = newItem;
}


/* Helper for function Split. */







|



















|











|




















|











|

















|







124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
{
    Element *elem;

    assert(tree);
    assert(rect);

    DEBUG_ALLOC(tkQTreeCountNewElement++);
    elem = ckalloc(sizeof(Element));
    elem->prev = NULL;
    if ((elem->next = tree->elem)) {
	elem->next->prev = elem;
    }
    tree->elem = elem;
    elem->bbox = *rect;
    elem->uid = uid;
    elem->state = initialState;
    elem->epoch = 0;
    return elem;
}


static Node *
NewNode(int initialPartialCount)
{
    Node *n;

    DEBUG_ALLOC(tkQTreeCountNewNode++);
    n = memset(ckalloc(sizeof(Node)), 0, sizeof(Node));
    n->countPartial = initialPartialCount;
    return n;
}


static void
FreeItems(
    Item *item)
{
    while (item) {
	Item *next = item->next;
	ckfree(item);
	item = next;
	DEBUG_ALLOC(tkQTreeCountDestroyItem++);
    }
}


static void
FreeNode(
    Node *node)
{
    if (node) {
	if (node->countPartial >= 0) {
	    FreeItems(node->partialItem);
	} else {
	    FreeNode(node->ne);
	    FreeNode(node->nw);
	    FreeNode(node->se);
	    FreeNode(node->sw);
	}
	FreeItems(node->spanningItem);
	ckfree(node);
	DEBUG_ALLOC(tkQTreeCountDestroyNode++);
    }
}


static void
FreeElements(
    Element *elem)
{
    while (elem) {
	Element *next = elem->next;
	ckfree(elem);
	elem = next;
	DEBUG_ALLOC(tkQTreeCountDestroyElement++);
    }
}


static void
AddItem(
    Item **itemPtr,
    Element *elem)
{
    Item *newItem;

    assert(itemPtr);
    assert(elem);

    DEBUG_ALLOC(tkQTreeCountNewItem++);
    newItem = ckalloc(sizeof(Item));
    newItem->elem = elem;
    newItem->next = *itemPtr;
    *itemPtr = newItem;
}


/* Helper for function Split. */
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
	if (item->elem->uid == uid) {
	    *elem = item->elem;
	    if (prevItem) {
		prevItem->next = item->next;
	    } else {
		*itemPtr = item->next;
	    }
	    free(item);
	    *count -= 1;
	    DEBUG_ALLOC(tkQTreeCountDestroyItem++);
	    return;
	}
    }
}








|







514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
	if (item->elem->uid == uid) {
	    *elem = item->elem;
	    if (prevItem) {
		prevItem->next = item->next;
	    } else {
		*itemPtr = item->next;
	    }
	    ckfree(item);
	    *count -= 1;
	    DEBUG_ALLOC(tkQTreeCountDestroyItem++);
	    return;
	}
    }
}

725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
	elem->prev->next = elem->next;
    } else {
	tree->elem = elem->next;
    }
    if (elem->next) {
	elem->next->prev = elem->prev;
    }
    free(elem);
    DEBUG_ALLOC(tkQTreeCountDestroyElement++);
}


void
TkQTreeTraverse(
    TkQTree tree,







|







724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
	elem->prev->next = elem->next;
    } else {
	tree->elem = elem->next;
    }
    if (elem->next) {
	elem->next->prev = elem->prev;
    }
    ckfree(elem);
    DEBUG_ALLOC(tkQTreeCountDestroyElement++);
}


void
TkQTreeTraverse(
    TkQTree tree,
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
    TkQTree *treePtr)
{
    assert(treePtr);

    if (*treePtr) {
	FreeNode((*treePtr)->root);
	FreeElements((*treePtr)->elem);
	free(*treePtr);
	DEBUG_ALLOC(tkQTreeCountDestroyTree++);
	*treePtr = NULL;
    }
}


bool







|







965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
    TkQTree *treePtr)
{
    assert(treePtr);

    if (*treePtr) {
	FreeNode((*treePtr)->root);
	FreeElements((*treePtr)->elem);
	ckfree(*treePtr);
	DEBUG_ALLOC(tkQTreeCountDestroyTree++);
	*treePtr = NULL;
    }
}


bool
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
    if ((tree = *treePtr)) {
	if (TkQTreeRectIsEqual(&tree->bbox, rect)) {
	    return true;
	}
	FreeNode(tree->root);
    } else {
	DEBUG_ALLOC(tkQTreeCountNewTree++);
	*treePtr = tree = malloc(sizeof(struct TkQTree));
	tree->elem = NULL;
	tree->epoch = 0;
    }

    tree->root = NewNode(0);
    tree->bbox = *rect;








|







995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
    if ((tree = *treePtr)) {
	if (TkQTreeRectIsEqual(&tree->bbox, rect)) {
	    return true;
	}
	FreeNode(tree->root);
    } else {
	DEBUG_ALLOC(tkQTreeCountNewTree++);
	*treePtr = tree = ckalloc(sizeof(struct TkQTree));
	tree->elem = NULL;
	tree->epoch = 0;
    }

    tree->root = NewNode(0);
    tree->bbox = *rect;

Changes to generic/tkQTree.h.

13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#define _TKQTREE

#ifndef _TKINT
#include "tkInt.h"
#endif

#include "tkBool.h"
#include <stdint.h>

#ifdef _MSC_VER
# if _MSC_VER >= 1900
#  define inline __inline
# else
#  define inline
# endif







|







13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#define _TKQTREE

#ifndef _TKINT
#include "tkInt.h"
#endif

#include "tkBool.h"
#include "mystdint.h"

#ifdef _MSC_VER
# if _MSC_VER >= 1900
#  define inline __inline
# else
#  define inline
# endif

Changes to generic/tkRangeList.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/*
 * tkRangeList.c --
 *
 *	This module implements operations on a list of integer ranges.
 *
 * Copyright (c) 2015-2017 Gregor Cramer
 *
 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "tkRangeList.h"
#include "tkAlloc.h"

#include <tk.h>
#include <string.h>
#include <assert.h>

#if !(__STDC_VERSION__ >= 199901L || (defined(_MSC_VER) && _MSC_VER >= 1900))
# define _TK_NEED_IMPLEMENTATION












<







1
2
3
4
5
6
7
8
9
10
11
12

13
14
15
16
17
18
19
/*
 * tkRangeList.c --
 *
 *	This module implements operations on a list of integer ranges.
 *
 * Copyright (c) 2015-2017 Gregor Cramer
 *
 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "tkRangeList.h"


#include <tk.h>
#include <string.h>
#include <assert.h>

#if !(__STDC_VERSION__ >= 199901L || (defined(_MSC_VER) && _MSC_VER >= 1900))
# define _TK_NEED_IMPLEMENTATION
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
Increase(
    TkRangeList **rangesPtr)
{
    TkRangeList *ranges = *rangesPtr;

    if (ranges->size == ranges->capacity) {
	ranges->capacity = MAX(1, 2*ranges->capacity);
	ranges = realloc(ranges, MEM_SIZE(ranges->capacity));
	*rangesPtr = ranges;
    }

    return ranges->items + ranges->size++;
}


static TkRange *
Insert(
    TkRangeList **rangesPtr,
    TkRange *entry)
{
    TkRangeList *ranges = *rangesPtr;
    unsigned pos = entry - ranges->items;

    if (ranges->size == ranges->capacity) {
	TkRangeList *newRanges;
	TkRange *newEntry;

	ranges->capacity = MAX(1, 2*ranges->capacity);
	newRanges = malloc(MEM_SIZE(ranges->capacity));
	newRanges->capacity = ranges->capacity;
	newRanges->size = ranges->size + 1;
	newRanges->count = ranges->count;
	newEntry = newRanges->items + pos;
	memcpy(newRanges->items, ranges->items, pos*sizeof(TkRange));
	memcpy(newEntry + 1, entry, (ranges->size - pos)*sizeof(TkRange));
	free(ranges);
	*rangesPtr = ranges = newRanges;
	entry = newEntry;
    } else {
	memmove(entry + 1, entry, (ranges->size - pos)*sizeof(TkRange));
	ranges->size += 1;
    }








|




















|






|







101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
Increase(
    TkRangeList **rangesPtr)
{
    TkRangeList *ranges = *rangesPtr;

    if (ranges->size == ranges->capacity) {
	ranges->capacity = MAX(1, 2*ranges->capacity);
	ranges = ckrealloc(ranges, MEM_SIZE(ranges->capacity));
	*rangesPtr = ranges;
    }

    return ranges->items + ranges->size++;
}


static TkRange *
Insert(
    TkRangeList **rangesPtr,
    TkRange *entry)
{
    TkRangeList *ranges = *rangesPtr;
    unsigned pos = entry - ranges->items;

    if (ranges->size == ranges->capacity) {
	TkRangeList *newRanges;
	TkRange *newEntry;

	ranges->capacity = MAX(1, 2*ranges->capacity);
	newRanges = ckalloc(MEM_SIZE(ranges->capacity));
	newRanges->capacity = ranges->capacity;
	newRanges->size = ranges->size + 1;
	newRanges->count = ranges->count;
	newEntry = newRanges->items + pos;
	memcpy(newRanges->items, ranges->items, pos*sizeof(TkRange));
	memcpy(newEntry + 1, entry, (ranges->size - pos)*sizeof(TkRange));
	ckfree(ranges);
	*rangesPtr = ranges = newRanges;
	entry = newEntry;
    } else {
	memmove(entry + 1, entry, (ranges->size - pos)*sizeof(TkRange));
	ranges->size += 1;
    }

174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220


TkRangeList *
TkRangeListCreate(unsigned capacity)
{
    TkRangeList *ranges;

    ranges = malloc(MEM_SIZE(capacity));
    ranges->size = 0;
    ranges->capacity = capacity;
    ranges->count = 0;
    DEBUG_ALLOC(tkRangeListCountNew++);
    return ranges;
}


TkRangeList *
TkRangeListCopy(
    const TkRangeList *ranges)
{
    TkRangeList *copy;
    unsigned memSize;

    assert(ranges);

    copy = malloc(memSize = MEM_SIZE(ranges->size));
    memcpy(copy, ranges, memSize);
    DEBUG_ALLOC(tkRangeListCountNew++);
    return copy;
}


void
TkRangeListDestroy(
    TkRangeList **rangesPtr)
{
    assert(rangesPtr);

    if (*rangesPtr) {
	free(*rangesPtr);
	*rangesPtr = NULL;
	DEBUG_ALLOC(tkRangeListCountDestroy++);
    }
}


void







|

















|













|







173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219


TkRangeList *
TkRangeListCreate(unsigned capacity)
{
    TkRangeList *ranges;

    ranges = ckalloc(MEM_SIZE(capacity));
    ranges->size = 0;
    ranges->capacity = capacity;
    ranges->count = 0;
    DEBUG_ALLOC(tkRangeListCountNew++);
    return ranges;
}


TkRangeList *
TkRangeListCopy(
    const TkRangeList *ranges)
{
    TkRangeList *copy;
    unsigned memSize;

    assert(ranges);

    copy = ckalloc(memSize = MEM_SIZE(ranges->size));
    memcpy(copy, ranges, memSize);
    DEBUG_ALLOC(tkRangeListCountNew++);
    return copy;
}


void
TkRangeListDestroy(
    TkRangeList **rangesPtr)
{
    assert(rangesPtr);

    if (*rangesPtr) {
	ckfree(*rangesPtr);
	*rangesPtr = NULL;
	DEBUG_ALLOC(tkRangeListCountDestroy++);
    }
}


void

Changes to generic/tkText.c.

959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
     */

    if (!(newWin = Tk_CreateWindowFromPath(interp, tkwin, Tcl_GetString(objv[1]), NULL))) {
	return TCL_ERROR;
    }

    if (!sharedTextPtr) {
	sharedTextPtr = memset(malloc(sizeof(TkSharedText)), 0, sizeof(TkSharedText));

	Tcl_InitHashTable(&sharedTextPtr->tagTable, TCL_STRING_KEYS);
	Tcl_InitHashTable(&sharedTextPtr->markTable, TCL_STRING_KEYS);
	Tcl_InitHashTable(&sharedTextPtr->windowTable, TCL_STRING_KEYS);
	Tcl_InitHashTable(&sharedTextPtr->imageTable, TCL_STRING_KEYS);
	sharedTextPtr->usedTags = TkBitResize(NULL, 256);
	sharedTextPtr->elisionTags = TkBitResize(NULL, 256);
	sharedTextPtr->selectionTags = TkBitResize(NULL, 256);
	sharedTextPtr->dontUndoTags = TkBitResize(NULL, 256);
	sharedTextPtr->affectDisplayTags = TkBitResize(NULL, 256);
	sharedTextPtr->notAffectDisplayTags = TkBitResize(NULL, 256);
	sharedTextPtr->affectDisplayNonSelTags = TkBitResize(NULL, 256);
	sharedTextPtr->affectGeometryTags = TkBitResize(NULL, 256);
	sharedTextPtr->affectGeometryNonSelTags = TkBitResize(NULL, 256);
	sharedTextPtr->affectLineHeightTags = TkBitResize(NULL, 256);
	sharedTextPtr->tagLookup = malloc(256*sizeof(TkTextTag *));
	sharedTextPtr->emptyTagInfoPtr = TkTextTagSetResize(NULL, 0);
	sharedTextPtr->maxRedoDepth = -1;
	sharedTextPtr->autoSeparators = true;
	sharedTextPtr->lastEditMode = TK_TEXT_EDIT_OTHER;
	sharedTextPtr->lastUndoTokenType = -1;
	sharedTextPtr->startMarker = TkTextMakeStartEndMark(NULL, &tkTextLeftMarkType);
	sharedTextPtr->endMarker = TkTextMakeStartEndMark(NULL, &tkTextRightMarkType);
	sharedTextPtr->protectionMark[0] = TkTextMakeMark(NULL, NULL);
	sharedTextPtr->protectionMark[1] = TkTextMakeMark(NULL, NULL);
	sharedTextPtr->protectionMark[0]->typePtr = &tkTextProtectionMarkType;
	sharedTextPtr->protectionMark[1]->typePtr = &tkTextProtectionMarkType;

	DEBUG(memset(sharedTextPtr->tagLookup, 0, 256*sizeof(TkTextTag *)));

	sharedTextPtr->mainPeer = memset(malloc(sizeof(TkText)), 0, sizeof(TkText));
	sharedTextPtr->mainPeer->startMarker = sharedTextPtr->startMarker;
	sharedTextPtr->mainPeer->endMarker = sharedTextPtr->endMarker;
	sharedTextPtr->mainPeer->sharedTextPtr = sharedTextPtr;
	DEBUG_ALLOC(tkTextCountNewPeer++);

#if TK_CHECK_ALLOCS
	if (tkTextCountNewShared++ == 0) {
	    atexit(AllocStatistic);
	}
	/*
	 * Add this shared resource to global list.
	 */
	{
	    WatchShared *wShared = malloc(sizeof(WatchShared));
	    wShared->sharedTextPtr = sharedTextPtr;
	    wShared->nextPtr = watchShared;
	    watchShared = wShared;
	}
#endif

	/*







|















|














|













|







959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
     */

    if (!(newWin = Tk_CreateWindowFromPath(interp, tkwin, Tcl_GetString(objv[1]), NULL))) {
	return TCL_ERROR;
    }

    if (!sharedTextPtr) {
	sharedTextPtr = memset(ckalloc(sizeof(TkSharedText)), 0, sizeof(TkSharedText));

	Tcl_InitHashTable(&sharedTextPtr->tagTable, TCL_STRING_KEYS);
	Tcl_InitHashTable(&sharedTextPtr->markTable, TCL_STRING_KEYS);
	Tcl_InitHashTable(&sharedTextPtr->windowTable, TCL_STRING_KEYS);
	Tcl_InitHashTable(&sharedTextPtr->imageTable, TCL_STRING_KEYS);
	sharedTextPtr->usedTags = TkBitResize(NULL, 256);
	sharedTextPtr->elisionTags = TkBitResize(NULL, 256);
	sharedTextPtr->selectionTags = TkBitResize(NULL, 256);
	sharedTextPtr->dontUndoTags = TkBitResize(NULL, 256);
	sharedTextPtr->affectDisplayTags = TkBitResize(NULL, 256);
	sharedTextPtr->notAffectDisplayTags = TkBitResize(NULL, 256);
	sharedTextPtr->affectDisplayNonSelTags = TkBitResize(NULL, 256);
	sharedTextPtr->affectGeometryTags = TkBitResize(NULL, 256);
	sharedTextPtr->affectGeometryNonSelTags = TkBitResize(NULL, 256);
	sharedTextPtr->affectLineHeightTags = TkBitResize(NULL, 256);
	sharedTextPtr->tagLookup = ckalloc(256*sizeof(TkTextTag *));
	sharedTextPtr->emptyTagInfoPtr = TkTextTagSetResize(NULL, 0);
	sharedTextPtr->maxRedoDepth = -1;
	sharedTextPtr->autoSeparators = true;
	sharedTextPtr->lastEditMode = TK_TEXT_EDIT_OTHER;
	sharedTextPtr->lastUndoTokenType = -1;
	sharedTextPtr->startMarker = TkTextMakeStartEndMark(NULL, &tkTextLeftMarkType);
	sharedTextPtr->endMarker = TkTextMakeStartEndMark(NULL, &tkTextRightMarkType);
	sharedTextPtr->protectionMark[0] = TkTextMakeMark(NULL, NULL);
	sharedTextPtr->protectionMark[1] = TkTextMakeMark(NULL, NULL);
	sharedTextPtr->protectionMark[0]->typePtr = &tkTextProtectionMarkType;
	sharedTextPtr->protectionMark[1]->typePtr = &tkTextProtectionMarkType;

	DEBUG(memset(sharedTextPtr->tagLookup, 0, 256*sizeof(TkTextTag *)));

	sharedTextPtr->mainPeer = memset(ckalloc(sizeof(TkText)), 0, sizeof(TkText));
	sharedTextPtr->mainPeer->startMarker = sharedTextPtr->startMarker;
	sharedTextPtr->mainPeer->endMarker = sharedTextPtr->endMarker;
	sharedTextPtr->mainPeer->sharedTextPtr = sharedTextPtr;
	DEBUG_ALLOC(tkTextCountNewPeer++);

#if TK_CHECK_ALLOCS
	if (tkTextCountNewShared++ == 0) {
	    atexit(AllocStatistic);
	}
	/*
	 * Add this shared resource to global list.
	 */
	{
	    WatchShared *wShared = ckalloc(sizeof(WatchShared));
	    wShared->sharedTextPtr = sharedTextPtr;
	    wShared->nextPtr = watchShared;
	    watchShared = wShared;
	}
#endif

	/*
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040

    /*
     * Create the text widget and initialize everything to zero, then set the
     * necessary initial (non-NULL) values. It is important that the 'set' tag
     * and 'insert', 'current' mark pointers are all NULL to start.
     */

    textPtr = memset(malloc(sizeof(TkText)), 0, sizeof(TkText));
    textPtr->tkwin = newWin;
    textPtr->display = Tk_Display(newWin);
    textPtr->interp = interp;
    textPtr->widgetCmd = Tcl_CreateObjCommand(interp, Tk_PathName(textPtr->tkwin),
	    TextWidgetObjCmd, textPtr, TextCmdDeletedProc);
    DEBUG_ALLOC(textPtr->widgetNumber = ++widgetNumber);








|







1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040

    /*
     * Create the text widget and initialize everything to zero, then set the
     * necessary initial (non-NULL) values. It is important that the 'set' tag
     * and 'insert', 'current' mark pointers are all NULL to start.
     */

    textPtr = memset(ckalloc(sizeof(TkText)), 0, sizeof(TkText));
    textPtr->tkwin = newWin;
    textPtr->display = Tk_Display(newWin);
    textPtr->interp = interp;
    textPtr->widgetCmd = Tcl_CreateObjCommand(interp, Tk_PathName(textPtr->tkwin),
	    TextWidgetObjCmd, textPtr, TextCmdDeletedProc);
    DEBUG_ALLOC(textPtr->widgetNumber = ++widgetNumber);

1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
    /*
     * Create the "sel" tag and the "current" and "insert" marks.
     * Note: it is important that textPtr->selTagPtr is NULL before this
     * initial call.
     */

    textPtr->selTagPtr = TkTextCreateTag(textPtr, "sel", NULL);
    textPtr->selTagPtr->reliefString = malloc(sizeof(DEF_TEXT_SELECT_RELIEF));
    strcpy(textPtr->selTagPtr->reliefString, DEF_TEXT_SELECT_RELIEF);
    Tk_GetRelief(interp, DEF_TEXT_SELECT_RELIEF, &textPtr->selTagPtr->relief);
    textPtr->insertMarkPtr = TkTextSetMark(textPtr, "insert", &startIndex);
    textPtr->currentMarkPtr = TkTextSetMark(textPtr, "current", &startIndex);
    textPtr->currentMarkIndex = startIndex;

    sharedTextPtr->numPeers += 1;







|







1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
    /*
     * Create the "sel" tag and the "current" and "insert" marks.
     * Note: it is important that textPtr->selTagPtr is NULL before this
     * initial call.
     */

    textPtr->selTagPtr = TkTextCreateTag(textPtr, "sel", NULL);
    textPtr->selTagPtr->reliefString = ckalloc(sizeof(DEF_TEXT_SELECT_RELIEF));
    strcpy(textPtr->selTagPtr->reliefString, DEF_TEXT_SELECT_RELIEF);
    Tk_GetRelief(interp, DEF_TEXT_SELECT_RELIEF, &textPtr->selTagPtr->relief);
    textPtr->insertMarkPtr = TkTextSetMark(textPtr, "insert", &startIndex);
    textPtr->currentMarkPtr = TkTextSetMark(textPtr, "current", &startIndex);
    textPtr->currentMarkIndex = startIndex;

    sharedTextPtr->numPeers += 1;
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
AppendScript(
    const char *oldScript,
    const char *script)
{
    int lenOfNew = strlen(script);
    int lenOfOld = strlen(oldScript);
    int totalLen = lenOfOld + lenOfNew + 1;
    char *newScript = malloc(totalLen + 1);

    memcpy(newScript, oldScript, lenOfOld);
    newScript[lenOfOld] = '\n';
    memcpy(newScript + lenOfOld + 1, script, lenOfNew + 1);
    return Tcl_NewStringObj(newScript, totalLen);
}








|







1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
AppendScript(
    const char *oldScript,
    const char *script)
{
    int lenOfNew = strlen(script);
    int lenOfOld = strlen(oldScript);
    int totalLen = lenOfOld + lenOfNew + 1;
    char *newScript = ckalloc(totalLen + 1);

    memcpy(newScript, oldScript, lenOfOld);
    newScript[lenOfOld] = '\n';
    memcpy(newScript + lenOfOld + 1, script, lenOfNew + 1);
    return Tcl_NewStringObj(newScript, totalLen);
}

1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401

	if (objc != 3) {
	    Tcl_WrongNumArgs(interp, 2, objv, "varname");
	    result = TCL_ERROR;
	    goto done;
	}

	listPtr = malloc(sizeof(TkTextStringList));
	Tcl_IncrRefCount(listPtr->strObjPtr = objv[2]);
	listPtr->nextPtr = textPtr->varBindingList;
	textPtr->varBindingList = listPtr;
	break;
    }
    case TEXT_BBOX: {
	int x, y, width, height;







|







1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401

	if (objc != 3) {
	    Tcl_WrongNumArgs(interp, 2, objv, "varname");
	    result = TCL_ERROR;
	    goto done;
	}

	listPtr = ckalloc(sizeof(TkTextStringList));
	Tcl_IncrRefCount(listPtr->strObjPtr = objv[2]);
	listPtr->nextPtr = textPtr->varBindingList;
	textPtr->varBindingList = listPtr;
	break;
    }
    case TEXT_BBOX: {
	int x, y, width, height;
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
		result = TCL_ERROR;
		goto done;
	    }
	    lang = Tcl_GetString(objv[3]);
	}
	if ((length = GetByteLength(objv[2])) < textPtr->brksBufferSize) {
	    textPtr->brksBufferSize = MAX(length, textPtr->brksBufferSize + 512);
	    textPtr->brksBuffer = realloc(textPtr->brksBuffer, textPtr->brksBufferSize);
	}
	TkTextComputeBreakLocations(interp, Tcl_GetString(objv[2]), length, lang, textPtr->brksBuffer);
	arrPtr = Tcl_NewObj();

	for (i = 0; i < length; ++i) {
	    int value;








|







1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
		result = TCL_ERROR;
		goto done;
	    }
	    lang = Tcl_GetString(objv[3]);
	}
	if ((length = GetByteLength(objv[2])) < textPtr->brksBufferSize) {
	    textPtr->brksBufferSize = MAX(length, textPtr->brksBufferSize + 512);
	    textPtr->brksBuffer = ckrealloc(textPtr->brksBuffer, textPtr->brksBufferSize);
	}
	TkTextComputeBreakLocations(interp, Tcl_GetString(objv[2]), length, lang, textPtr->brksBuffer);
	arrPtr = Tcl_NewObj();

	for (i = 0; i < length; ++i) {
	    int value;

1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874

	    TkTextIndex *indices, *ixStart, *ixEnd, *lastStart;
	    char *useIdx;
	    int lastUsed, i;

	    objc -= 2;
	    objv += 2;
	    indices = malloc((objc + 1)*sizeof(TkTextIndex));

	    /*
	     * First pass verifies that all indices are valid.
	     */

	    for (i = 0; i < objc; i++) {
		if (!TkTextGetIndexFromObj(interp, textPtr, objv[i], &indices[i])) {
		    result = TCL_ERROR;
		    free(indices);
		    goto done;
		}
	    }

	    /*
	     * Pad out the pairs evenly to make later code easier.
	     */

	    if (objc & 1) {
		indices[i] = indices[i - 1];
		TkTextIndexForwChars(textPtr, &indices[i], 1, &indices[i], COUNT_INDICES);
		objc += 1;
	    }
	    useIdx = malloc(objc);
	    memset(useIdx, 0, (unsigned) objc);

	    /*
	     * Do a decreasing order sort so that we delete the end ranges
	     * first to maintain index consistency.
	     */








|








|













|







1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874

	    TkTextIndex *indices, *ixStart, *ixEnd, *lastStart;
	    char *useIdx;
	    int lastUsed, i;

	    objc -= 2;
	    objv += 2;
	    indices = ckalloc((objc + 1)*sizeof(TkTextIndex));

	    /*
	     * First pass verifies that all indices are valid.
	     */

	    for (i = 0; i < objc; i++) {
		if (!TkTextGetIndexFromObj(interp, textPtr, objv[i], &indices[i])) {
		    result = TCL_ERROR;
		    ckfree(indices);
		    goto done;
		}
	    }

	    /*
	     * Pad out the pairs evenly to make later code easier.
	     */

	    if (objc & 1) {
		indices[i] = indices[i - 1];
		TkTextIndexForwChars(textPtr, &indices[i], 1, &indices[i], COUNT_INDICES);
		objc += 1;
	    }
	    useIdx = ckalloc(objc);
	    memset(useIdx, 0, (unsigned) objc);

	    /*
	     * Do a decreasing order sort so that we delete the end ranges
	     * first to maintain index consistency.
	     */

1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
		     * indices are preparsed above.
		     */

		    ok = DeleteIndexRange(NULL, textPtr, &indices[i], &indices[i + 1],
			    flags, true, triggerWatch, triggerWatch, triggerUserMod, i == lastUsed);
		}
	    }
	    free(indices);
	}

	if (!ok) {
	    return TCL_OK; /* widget has been destroyed */
	}
	break;
    }







|







1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
		     * indices are preparsed above.
		     */

		    ok = DeleteIndexRange(NULL, textPtr, &indices[i], &indices[i + 1],
			    flags, true, triggerWatch, triggerWatch, triggerUserMod, i == lastUsed);
		}
	    }
	    ckfree(indices);
	}

	if (!ok) {
	    return TCL_OK; /* widget has been destroyed */
	}
	break;
    }
2046
2047
2048
2049
2050
2051
2052

2053
2054
2055
2056
2057
2058
2059
		result = TCL_ERROR;
		goto done;
	    }
	}

	for (; i < objc; i += 2) {
	    TkTextIndex index1, index2;


	    if (!TkTextGetIndexFromObj(interp, textPtr, objv[i], &index1)) {
		if (objPtr) {
		    Tcl_DecrRefCount(objPtr);
		}
		result = TCL_ERROR;
		goto done;







>







2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
		result = TCL_ERROR;
		goto done;
	    }
	}

	for (; i < objc; i += 2) {
	    TkTextIndex index1, index2;
	    Tcl_Obj *get;

	    if (!TkTextGetIndexFromObj(interp, textPtr, objv[i], &index1)) {
		if (objPtr) {
		    Tcl_DecrRefCount(objPtr);
		}
		result = TCL_ERROR;
		goto done;
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090

	    /*
	     * We want to move the text we get from the window into the
	     * result, but since this could in principle be a megabyte or
	     * more, we want to do it efficiently!
	     */

	    Tcl_Obj *get = TextGetText(textPtr, &index1, &index2, NULL, NULL, UINT_MAX,
		    visibleOnly, includeHyphens);

	    if (++found == 1) {
		Tcl_SetObjResult(interp, get);
	    } else {
		if (found == 2) {
		    /*







|







2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091

	    /*
	     * We want to move the text we get from the window into the
	     * result, but since this could in principle be a megabyte or
	     * more, we want to do it efficiently!
	     */

	    get = TextGetText(textPtr, &index1, &index2, NULL, NULL, UINT_MAX,
		    visibleOnly, includeHyphens);

	    if (++found == 1) {
		Tcl_SetObjResult(interp, get);
	    } else {
		if (found == 2) {
		    /*
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
	break;
    }

  done:
    if (--textPtr->refCount == 0) {
	bool sharedIsReleased = textPtr->sharedIsReleased;

	free(textPtr);
	if (sharedIsReleased) {
	    return result;
	}
	textPtr = NULL;
    } else if (textPtr->watchCmd) {
	TkTextTriggerWatchCursor(textPtr);
    }







|







2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
	break;
    }

  done:
    if (--textPtr->refCount == 0) {
	bool sharedIsReleased = textPtr->sharedIsReleased;

	ckfree(textPtr);
	if (sharedIsReleased) {
	    return result;
	}
	textPtr = NULL;
    } else if (textPtr->watchCmd) {
	TkTextTriggerWatchCursor(textPtr);
    }
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319

    listPtr = textPtr->varBindingList;
    while (listPtr) {
	TkTextStringList *nextPtr = listPtr->nextPtr;

	Tcl_UnsetVar2(textPtr->interp, Tcl_GetString(listPtr->strObjPtr), NULL, TCL_GLOBAL_ONLY);
	Tcl_DecrRefCount(listPtr->strObjPtr);
	free(listPtr);
	listPtr = nextPtr;
    }

    /*
     * Unset the watch command.
     */








|







3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320

    listPtr = textPtr->varBindingList;
    while (listPtr) {
	TkTextStringList *nextPtr = listPtr->nextPtr;

	Tcl_UnsetVar2(textPtr->interp, Tcl_GetString(listPtr->strObjPtr), NULL, TCL_GLOBAL_ONLY);
	Tcl_DecrRefCount(listPtr->strObjPtr);
	ckfree(listPtr);
	listPtr = nextPtr;
    }

    /*
     * Unset the watch command.
     */

3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
	}
    } else {
	/* Prevent that this resource will be released too early. */
	textPtr->refCount += 1;

	ClearRetainedUndoTokens(sharedTextPtr);
	TkTextUndoDestroyStack(&sharedTextPtr->undoStack);
	free(sharedTextPtr->undoTagList);
	free(sharedTextPtr->undoMarkList);
	TkBTreeDestroy(sharedTextPtr->tree);
	assert(sharedTextPtr->startMarker->refCount == 1);
	FREE_SEGMENT(sharedTextPtr->startMarker);
	DEBUG_ALLOC(tkTextCountDestroySegment++);
	assert(sharedTextPtr->endMarker->refCount == 1);
	FREE_SEGMENT(sharedTextPtr->endMarker);
	DEBUG_ALLOC(tkTextCountDestroySegment++);







|
|







3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
	}
    } else {
	/* Prevent that this resource will be released too early. */
	textPtr->refCount += 1;

	ClearRetainedUndoTokens(sharedTextPtr);
	TkTextUndoDestroyStack(&sharedTextPtr->undoStack);
	ckfree(sharedTextPtr->undoTagList);
	ckfree(sharedTextPtr->undoMarkList);
	TkBTreeDestroy(sharedTextPtr->tree);
	assert(sharedTextPtr->startMarker->refCount == 1);
	FREE_SEGMENT(sharedTextPtr->startMarker);
	DEBUG_ALLOC(tkTextCountDestroySegment++);
	assert(sharedTextPtr->endMarker->refCount == 1);
	FREE_SEGMENT(sharedTextPtr->endMarker);
	DEBUG_ALLOC(tkTextCountDestroySegment++);
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
	TkBitDestroy(&sharedTextPtr->affectGeometryNonSelTags);
	TkBitDestroy(&sharedTextPtr->affectLineHeightTags);
	TkTextTagSetDestroy(&sharedTextPtr->emptyTagInfoPtr);
	Tcl_DeleteHashTable(&sharedTextPtr->windowTable);
	Tcl_DeleteHashTable(&sharedTextPtr->imageTable);
	TkTextDeleteBreakInfoTableEntries(&sharedTextPtr->breakInfoTable);
	Tcl_DeleteHashTable(&sharedTextPtr->breakInfoTable);
	free(sharedTextPtr->mainPeer);
	DEBUG_ALLOC(tkTextCountDestroyPeer++);

	if (sharedTextPtr->tagBindingTable) {
	    Tk_DeleteBindingTable(sharedTextPtr->tagBindingTable);
	}
	if (sharedTextPtr->imageBindingTable) {
	    Tk_DeleteBindingTable(sharedTextPtr->imageBindingTable);
	}
	if (sharedTextPtr->stillExisting) {
	    *sharedTextPtr->stillExisting = false;
	}
	free(sharedTextPtr);
	DEBUG_ALLOC(tkTextCountDestroyShared++);

	textPtr->sharedIsReleased = true;
	textPtr->refCount -= 1;

#if TK_CHECK_ALLOCS
	/*







|











|







3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
	TkBitDestroy(&sharedTextPtr->affectGeometryNonSelTags);
	TkBitDestroy(&sharedTextPtr->affectLineHeightTags);
	TkTextTagSetDestroy(&sharedTextPtr->emptyTagInfoPtr);
	Tcl_DeleteHashTable(&sharedTextPtr->windowTable);
	Tcl_DeleteHashTable(&sharedTextPtr->imageTable);
	TkTextDeleteBreakInfoTableEntries(&sharedTextPtr->breakInfoTable);
	Tcl_DeleteHashTable(&sharedTextPtr->breakInfoTable);
	ckfree(sharedTextPtr->mainPeer);
	DEBUG_ALLOC(tkTextCountDestroyPeer++);

	if (sharedTextPtr->tagBindingTable) {
	    Tk_DeleteBindingTable(sharedTextPtr->tagBindingTable);
	}
	if (sharedTextPtr->imageBindingTable) {
	    Tk_DeleteBindingTable(sharedTextPtr->imageBindingTable);
	}
	if (sharedTextPtr->stillExisting) {
	    *sharedTextPtr->stillExisting = false;
	}
	ckfree(sharedTextPtr);
	DEBUG_ALLOC(tkTextCountDestroyShared++);

	textPtr->sharedIsReleased = true;
	textPtr->refCount -= 1;

#if TK_CHECK_ALLOCS
	/*
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493

	    if (prevPtr) {
		prevPtr->nextPtr = thisPtr->nextPtr;
	    } else {
		watchShared = thisPtr->nextPtr;
	    }

	    free(thisPtr);
	}
#endif
    }

    if (textPtr->tabArrayPtr) {
	free(textPtr->tabArrayPtr);
    }
    if (textPtr->insertBlinkHandler) {
	Tcl_DeleteTimerHandler(textPtr->insertBlinkHandler);
    }

    textPtr->tkwin = NULL;
    Tcl_DeleteCommandFromToken(textPtr->interp, textPtr->widgetCmd);
    if (--textPtr->refCount == 0) {
	free(textPtr);
    }

    tkBTreeDebug = debug;
    DEBUG_ALLOC(tkTextCountDestroyPeer++);
}

/*







|





|








|







3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494

	    if (prevPtr) {
		prevPtr->nextPtr = thisPtr->nextPtr;
	    } else {
		watchShared = thisPtr->nextPtr;
	    }

	    ckfree(thisPtr);
	}
#endif
    }

    if (textPtr->tabArrayPtr) {
	ckfree(textPtr->tabArrayPtr);
    }
    if (textPtr->insertBlinkHandler) {
	Tcl_DeleteTimerHandler(textPtr->insertBlinkHandler);
    }

    textPtr->tkwin = NULL;
    Tcl_DeleteCommandFromToken(textPtr->interp, textPtr->widgetCmd);
    if (--textPtr->refCount == 0) {
	ckfree(textPtr);
    }

    tkBTreeDebug = debug;
    DEBUG_ALLOC(tkTextCountDestroyPeer++);
}

/*
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524

bool
TkTextDecrRefCountAndTestIfDestroyed(
    TkText *textPtr)
{
    if (--textPtr->refCount == 0) {
	assert(textPtr->flags & DESTROYED);
	free(textPtr);
	return true;
    }
    return !!(textPtr->flags & DESTROYED);
}

/*
 *----------------------------------------------------------------------







|







3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525

bool
TkTextDecrRefCountAndTestIfDestroyed(
    TkText *textPtr)
{
    if (--textPtr->refCount == 0) {
	assert(textPtr->flags & DESTROYED);
	ckfree(textPtr);
	return true;
    }
    return !!(textPtr->flags & DESTROYED);
}

/*
 *----------------------------------------------------------------------
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
TkTextReleaseIfDestroyed(
    TkText *textPtr)
{
    if (!(textPtr->flags & DESTROYED)) {
	return false;
    }
    if (--textPtr->refCount == 0) {
	free(textPtr);
    }
    return true;
}

/*
 *----------------------------------------------------------------------
 *







|







3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
TkTextReleaseIfDestroyed(
    TkText *textPtr)
{
    if (!(textPtr->flags & DESTROYED)) {
	return false;
    }
    if (--textPtr->refCount == 0) {
	ckfree(textPtr);
    }
    return true;
}

/*
 *----------------------------------------------------------------------
 *
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
	Tcl_Obj **myObjv;
	Tcl_Obj *startLineObj = NULL;
	Tcl_Obj *endLineObj = NULL;
	Tcl_Obj *startIndexObj = NULL;
	Tcl_Obj *endIndexObj = NULL;
	int i, rc;

	myObjv = malloc(objc * sizeof(Tcl_Obj *));

	for (i = 0; i < objc; ++i) {
	    Tcl_Obj *obj = objv[i];

	    if (!(i & 1)) {
		if (strcmp(Tcl_GetString(objv[i]), "-start") == 0) {
		    if (i + 1 < objc && IsNumberOrEmpty(Tcl_GetString(objv[i + 1]))) {







|







3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
	Tcl_Obj **myObjv;
	Tcl_Obj *startLineObj = NULL;
	Tcl_Obj *endLineObj = NULL;
	Tcl_Obj *startIndexObj = NULL;
	Tcl_Obj *endIndexObj = NULL;
	int i, rc;

	myObjv = ckalloc(objc * sizeof(Tcl_Obj *));

	for (i = 0; i < objc; ++i) {
	    Tcl_Obj *obj = objv[i];

	    if (!(i & 1)) {
		if (strcmp(Tcl_GetString(objv[i]), "-start") == 0) {
		    if (i + 1 < objc && IsNumberOrEmpty(Tcl_GetString(objv[i + 1]))) {
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
	}

	if (startLineObj)  { Tcl_DecrRefCount(startLineObj); }
	if (endLineObj)    { Tcl_DecrRefCount(endLineObj); }
	if (startIndexObj) { Tcl_DecrRefCount(startIndexObj); }
	if (endIndexObj)   { Tcl_DecrRefCount(endIndexObj); }

	free(myObjv);

	if (rc != TCL_OK) {
	    tkTextDebug = oldTextDebug;
	    return rc;
	}
    }








|







3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
	}

	if (startLineObj)  { Tcl_DecrRefCount(startLineObj); }
	if (endLineObj)    { Tcl_DecrRefCount(endLineObj); }
	if (startIndexObj) { Tcl_DecrRefCount(startIndexObj); }
	if (endIndexObj)   { Tcl_DecrRefCount(endIndexObj); }

	ckfree(myObjv);

	if (rc != TCL_OK) {
	    tkTextDebug = oldTextDebug;
	    return rc;
	}
    }

3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
    }

    /*
     * Parse tab stops.
     */

    if (textPtr->tabArrayPtr) {
	free(textPtr->tabArrayPtr);
	textPtr->tabArrayPtr = NULL;
    }
    if (textPtr->tabOptionPtr) {
	textPtr->tabArrayPtr = TkTextGetTabs(interp, textPtr, textPtr->tabOptionPtr);
	if (!textPtr->tabArrayPtr) {
	    Tcl_AddErrorInfo(interp, "\n    (while processing -tabs option)");
	    Tk_RestoreSavedOptions(&savedOptions);







|







3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
    }

    /*
     * Parse tab stops.
     */

    if (textPtr->tabArrayPtr) {
	ckfree(textPtr->tabArrayPtr);
	textPtr->tabArrayPtr = NULL;
    }
    if (textPtr->tabOptionPtr) {
	textPtr->tabArrayPtr = TkTextGetTabs(interp, textPtr, textPtr->tabOptionPtr);
	if (!textPtr->tabArrayPtr) {
	    Tcl_AddErrorInfo(interp, "\n    (while processing -tabs option)");
	    Tk_RestoreSavedOptions(&savedOptions);
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
     * Notify the display module that lines are about to change, then do the
     * insertion. If the insertion occurs on the top line of the widget
     * (textPtr->topIndex), then we have to recompute topIndex after the
     * insertion, since the insertion could invalidate it.
     */

    if (sharedTextPtr->numPeers > sizeof(textPosition)/sizeof(textPosition[0])) {
	textPosition = malloc(sizeof(textPosition[0])*sharedTextPtr->numPeers);
    } else {
	textPosition = textPosBuf;
    }
    InitPosition(sharedTextPtr, textPosition);
    FindNewTopPosition(sharedTextPtr, textPosition, index1Ptr, NULL, length);

    TkTextChanged(sharedTextPtr, NULL, index1Ptr, index1Ptr);
    undoInfoPtr = TkTextUndoStackIsFull(sharedTextPtr->undoStack) ? NULL : &undoInfo;
    startIndex = *index1Ptr;
    TkTextIndexToByteIndex(&startIndex); /* we need the byte position after insertion */

    if (parseHyphens) {
	text = (length >= sizeof(textBuf)) ? malloc(length + 1) : textBuf;
	ParseHyphens(string, string + length, (char *) text);
    }

    TkBTreeInsertChars(sharedTextPtr->tree, index1Ptr, text, tagInfoPtr, hyphenTagPtr, undoInfoPtr);

    /*
     * Push the insertion on the undo stack, and update the modified status of the widget.







|












|







4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
     * Notify the display module that lines are about to change, then do the
     * insertion. If the insertion occurs on the top line of the widget
     * (textPtr->topIndex), then we have to recompute topIndex after the
     * insertion, since the insertion could invalidate it.
     */

    if (sharedTextPtr->numPeers > sizeof(textPosition)/sizeof(textPosition[0])) {
	textPosition = ckalloc(sizeof(textPosition[0])*sharedTextPtr->numPeers);
    } else {
	textPosition = textPosBuf;
    }
    InitPosition(sharedTextPtr, textPosition);
    FindNewTopPosition(sharedTextPtr, textPosition, index1Ptr, NULL, length);

    TkTextChanged(sharedTextPtr, NULL, index1Ptr, index1Ptr);
    undoInfoPtr = TkTextUndoStackIsFull(sharedTextPtr->undoStack) ? NULL : &undoInfo;
    startIndex = *index1Ptr;
    TkTextIndexToByteIndex(&startIndex); /* we need the byte position after insertion */

    if (parseHyphens) {
	text = (length >= sizeof(textBuf)) ? ckalloc(length + 1) : textBuf;
	ParseHyphens(string, string + length, (char *) text);
    }

    TkBTreeInsertChars(sharedTextPtr->tree, index1Ptr, text, tagInfoPtr, hyphenTagPtr, undoInfoPtr);

    /*
     * Push the insertion on the undo stack, and update the modified status of the widget.
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
	if (sharedTextPtr->lastUndoTokenType != TK_TEXT_UNDO_INSERT
		|| !((subAtom = TkTextUndoGetLastUndoSubAtom(sharedTextPtr->undoStack))
			&& (triggerStackEvent = TkBTreeJoinUndoInsert(
				subAtom->item, subAtom->size, undoInfo.token, undoInfo.byteSize)))) {
	    TkTextPushUndoToken(sharedTextPtr, undoInfo.token, undoInfo.byteSize);
	} else {
	    assert(!undoInfo.token->undoType->destroyProc);
	    free(undoInfo.token);
	    DEBUG_ALLOC(tkTextCountDestroyUndoToken++);
	}
	if (triggerStackEvent) {
	    sharedTextPtr->undoStackEvent = true; /* TkBTreeJoinUndoInsert didn't trigger */
	}
	assert(undoInfo.token->undoType->rangeProc);
	sharedTextPtr->prevUndoStartIndex = ((TkTextUndoTokenRange *) undoInfo.token)->startIndex;
	sharedTextPtr->prevUndoEndIndex = ((TkTextUndoTokenRange *) undoInfo.token)->endIndex;
	sharedTextPtr->lastUndoTokenType = TK_TEXT_UNDO_INSERT;
	sharedTextPtr->lastEditMode = TK_TEXT_EDIT_INSERT;
    }

    *index2Ptr = *index1Ptr;
    *index1Ptr = startIndex;
    UpdateModifiedFlag(sharedTextPtr, true);
    TkTextUpdateAlteredFlag(sharedTextPtr);
    SetNewTopPosition(sharedTextPtr, textPtr, textPosition, viewUpdate);
    if (textPosition != textPosBuf) {
	free(textPosition);
    }

    /*
     * Invalidate any selection retrievals in progress.
     */

    for (tPtr = sharedTextPtr->peers; tPtr; tPtr = tPtr->next) {
	tPtr->abortSelections = true;
    }

    if (parseHyphens && text != textBuf) {
	free((char *) text);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TextUndoRedoCallback --







|


















|











|







4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
	if (sharedTextPtr->lastUndoTokenType != TK_TEXT_UNDO_INSERT
		|| !((subAtom = TkTextUndoGetLastUndoSubAtom(sharedTextPtr->undoStack))
			&& (triggerStackEvent = TkBTreeJoinUndoInsert(
				subAtom->item, subAtom->size, undoInfo.token, undoInfo.byteSize)))) {
	    TkTextPushUndoToken(sharedTextPtr, undoInfo.token, undoInfo.byteSize);
	} else {
	    assert(!undoInfo.token->undoType->destroyProc);
	    ckfree(undoInfo.token);
	    DEBUG_ALLOC(tkTextCountDestroyUndoToken++);
	}
	if (triggerStackEvent) {
	    sharedTextPtr->undoStackEvent = true; /* TkBTreeJoinUndoInsert didn't trigger */
	}
	assert(undoInfo.token->undoType->rangeProc);
	sharedTextPtr->prevUndoStartIndex = ((TkTextUndoTokenRange *) undoInfo.token)->startIndex;
	sharedTextPtr->prevUndoEndIndex = ((TkTextUndoTokenRange *) undoInfo.token)->endIndex;
	sharedTextPtr->lastUndoTokenType = TK_TEXT_UNDO_INSERT;
	sharedTextPtr->lastEditMode = TK_TEXT_EDIT_INSERT;
    }

    *index2Ptr = *index1Ptr;
    *index1Ptr = startIndex;
    UpdateModifiedFlag(sharedTextPtr, true);
    TkTextUpdateAlteredFlag(sharedTextPtr);
    SetNewTopPosition(sharedTextPtr, textPtr, textPosition, viewUpdate);
    if (textPosition != textPosBuf) {
	ckfree(textPosition);
    }

    /*
     * Invalidate any selection retrievals in progress.
     */

    for (tPtr = sharedTextPtr->peers; tPtr; tPtr = tPtr->next) {
	tPtr->abortSelections = true;
    }

    if (parseHyphens && text != textBuf) {
	ckfree((char *) text);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TextUndoRedoCallback --
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
    TkText *tPtr;
    int i, k, countPeers = 0;

    assert(stack);

    if (sharedTextPtr->triggerWatchCmd) {
	if (sharedTextPtr->numPeers > sizeof(peerArr) / sizeof(peerArr[0])) {
	    peers = malloc(sharedTextPtr->numPeers * sizeof(peerArr[0]));
	}
	for (tPtr = sharedTextPtr->peers; tPtr; tPtr = tPtr->next) {
	    if (tPtr->watchCmd) {
		TkTextSaveCursorIndex(tPtr);
		peers[countPeers++] = tPtr;
		tPtr->refCount += 1;
	    }







|







5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
    TkText *tPtr;
    int i, k, countPeers = 0;

    assert(stack);

    if (sharedTextPtr->triggerWatchCmd) {
	if (sharedTextPtr->numPeers > sizeof(peerArr) / sizeof(peerArr[0])) {
	    peers = ckalloc(sharedTextPtr->numPeers * sizeof(peerArr[0]));
	}
	for (tPtr = sharedTextPtr->peers; tPtr; tPtr = tPtr->next) {
	    if (tPtr->watchCmd) {
		TkTextSaveCursorIndex(tPtr);
		peers[countPeers++] = tPtr;
		tPtr->refCount += 1;
	    }
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
	    const TkTextUndoTokenRange *range = (const TkTextUndoTokenRange *) token;

	    if (isDelete && sharedTextPtr->triggerWatchCmd) {
		TriggerWatchUndoRedo(sharedTextPtr, token, subAtom->redo, i == 0, peers, countPeers);
	    }
	    if (!textPosition) {
		if (sharedTextPtr->numPeers > sizeof(textPosBuf)/sizeof(textPosBuf[0])) {
		    textPosition = malloc(sizeof(textPosition[0])*sharedTextPtr->numPeers);
		} else {
		    textPosition = textPosBuf;
		}
		InitPosition(sharedTextPtr, textPosition);
	    }
	    if (isInsert) {
		TkBTreeUndoIndexToIndex(sharedTextPtr, &range->startIndex, &index1);







|







5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
	    const TkTextUndoTokenRange *range = (const TkTextUndoTokenRange *) token;

	    if (isDelete && sharedTextPtr->triggerWatchCmd) {
		TriggerWatchUndoRedo(sharedTextPtr, token, subAtom->redo, i == 0, peers, countPeers);
	    }
	    if (!textPosition) {
		if (sharedTextPtr->numPeers > sizeof(textPosBuf)/sizeof(textPosBuf[0])) {
		    textPosition = ckalloc(sizeof(textPosition[0])*sharedTextPtr->numPeers);
		} else {
		    textPosition = textPosBuf;
		}
		InitPosition(sharedTextPtr, textPosition);
	    }
	    if (isInsert) {
		TkBTreeUndoIndexToIndex(sharedTextPtr, &range->startIndex, &index1);
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
    sharedTextPtr->lastUndoTokenType = -1;
    UpdateModifiedFlag(sharedTextPtr, false);
    TkTextUpdateAlteredFlag(sharedTextPtr);

    if (textPosition) {
	SetNewTopPosition(sharedTextPtr, NULL, textPosition, true);
	if (textPosition != textPosBuf) {
	    free(textPosition);
	}
    }

    if (sharedTextPtr->triggerWatchCmd) {
	for (i = 0; i < countPeers; ++i) {
	    TkText *tPtr = peers[i];

	    if (!(tPtr->flags & DESTROYED)) {
		TkTextIndexClear(&tPtr->insertIndex, tPtr);
		TkTextTriggerWatchCursor(tPtr);
	    }
	    if (--tPtr->refCount == 0) {
		free(tPtr);
	    }
	}
    }

    /*
     * Freeing the peer array has to be done even if sharedTextPtr->triggerWatchCmd
     * is false, possibly the user has cleared the watch command inside the trigger
     * callback.
     */

    if (peers != peerArr) {
	free(peers);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TextUndoStackContentChangedCallback --







|












|











|







5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
    sharedTextPtr->lastUndoTokenType = -1;
    UpdateModifiedFlag(sharedTextPtr, false);
    TkTextUpdateAlteredFlag(sharedTextPtr);

    if (textPosition) {
	SetNewTopPosition(sharedTextPtr, NULL, textPosition, true);
	if (textPosition != textPosBuf) {
	    ckfree(textPosition);
	}
    }

    if (sharedTextPtr->triggerWatchCmd) {
	for (i = 0; i < countPeers; ++i) {
	    TkText *tPtr = peers[i];

	    if (!(tPtr->flags & DESTROYED)) {
		TkTextIndexClear(&tPtr->insertIndex, tPtr);
		TkTextTriggerWatchCursor(tPtr);
	    }
	    if (--tPtr->refCount == 0) {
		ckfree(tPtr);
	    }
	}
    }

    /*
     * Freeing the peer array has to be done even if sharedTextPtr->triggerWatchCmd
     * is false, possibly the user has cleared the watch command inside the trigger
     * callback.
     */

    if (peers != peerArr) {
	ckfree(peers);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TextUndoStackContentChangedCallback --
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
	    TkSharedText *sharedTextPtr = (TkSharedText *) TkTextUndoGetContext(stack);
	    assert(sharedTextPtr->insertDeleteUndoTokenCount > 0);
	    sharedTextPtr->insertDeleteUndoTokenCount -= 1;
	}
	if (token->undoType->destroyProc) {
	    token->undoType->destroyProc(TkTextUndoGetContext(stack), subAtom->item, false);
	}
	free(subAtom->item);
	DEBUG_ALLOC(tkTextCountDestroyUndoToken++);
    }
}

/*
 *----------------------------------------------------------------------
 *







|







5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
	    TkSharedText *sharedTextPtr = (TkSharedText *) TkTextUndoGetContext(stack);
	    assert(sharedTextPtr->insertDeleteUndoTokenCount > 0);
	    sharedTextPtr->insertDeleteUndoTokenCount -= 1;
	}
	if (token->undoType->destroyProc) {
	    token->undoType->destroyProc(TkTextUndoGetContext(stack), subAtom->item, false);
	}
	ckfree(subAtom->item);
	DEBUG_ALLOC(tkTextCountDestroyUndoToken++);
    }
}

/*
 *----------------------------------------------------------------------
 *
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
	 * (the deletion will invalidate textPtr->topIndex). Compute what the new
	 * first character will be, then do the deletion, then reset the view.
	 */

	TkTextChanged(sharedTextPtr, NULL, &index1, &index3);

	if (sharedTextPtr->numPeers > sizeof(textPosBuf)/sizeof(textPosBuf[0])) {
	    textPosition = malloc(sizeof(textPosition[0])*sharedTextPtr->numPeers);
	} else {
	    textPosition = textPosBuf;
	}
	InitPosition(sharedTextPtr, textPosition);
	FindNewTopPosition(sharedTextPtr, textPosition, &index1, &index2, 0);

	undoInfoPtr = TkTextUndoStackIsFull(sharedTextPtr->undoStack) ? NULL : &undoInfo;







|







5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
	 * (the deletion will invalidate textPtr->topIndex). Compute what the new
	 * first character will be, then do the deletion, then reset the view.
	 */

	TkTextChanged(sharedTextPtr, NULL, &index1, &index3);

	if (sharedTextPtr->numPeers > sizeof(textPosBuf)/sizeof(textPosBuf[0])) {
	    textPosition = ckalloc(sizeof(textPosition[0])*sharedTextPtr->numPeers);
	} else {
	    textPosition = textPosBuf;
	}
	InitPosition(sharedTextPtr, textPosition);
	FindNewTopPosition(sharedTextPtr, textPosition, &index1, &index2, 0);

	undoInfoPtr = TkTextUndoStackIsFull(sharedTextPtr->undoStack) ? NULL : &undoInfo;
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
			((TkTextUndoTokenRange *) undoInfo.token)->startIndex;
		sharedTextPtr->prevUndoEndIndex = ((TkTextUndoTokenRange *) undoInfo.token)->endIndex;
		/* stack has changed anyway, but TkBTreeJoinUndoDelete didn't trigger */
		sharedTextPtr->undoStackEvent = true;
	    } else {
		assert(undoInfo.token->undoType->destroyProc);
		undoInfo.token->undoType->destroyProc(sharedTextPtr, undoInfo.token, false);
		free(undoInfo.token);
		DEBUG_ALLOC(tkTextCountDestroyUndoToken++);
	    }

	    sharedTextPtr->lastEditMode = TK_TEXT_EDIT_DELETE;
	}

	UpdateModifiedFlag(sharedTextPtr, true);

	SetNewTopPosition(sharedTextPtr, textPtr, textPosition, viewUpdate);
	if (textPosition != textPosBuf) {
	    free(textPosition);
	}
    }

    if (altered) {
	TkTextUpdateAlteredFlag(sharedTextPtr);
    }








|










|







5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
			((TkTextUndoTokenRange *) undoInfo.token)->startIndex;
		sharedTextPtr->prevUndoEndIndex = ((TkTextUndoTokenRange *) undoInfo.token)->endIndex;
		/* stack has changed anyway, but TkBTreeJoinUndoDelete didn't trigger */
		sharedTextPtr->undoStackEvent = true;
	    } else {
		assert(undoInfo.token->undoType->destroyProc);
		undoInfo.token->undoType->destroyProc(sharedTextPtr, undoInfo.token, false);
		ckfree(undoInfo.token);
		DEBUG_ALLOC(tkTextCountDestroyUndoToken++);
	    }

	    sharedTextPtr->lastEditMode = TK_TEXT_EDIT_DELETE;
	}

	UpdateModifiedFlag(sharedTextPtr, true);

	SetNewTopPosition(sharedTextPtr, textPtr, textPosition, viewUpdate);
	if (textPosition != textPosBuf) {
	    ckfree(textPosition);
	}
    }

    if (altered) {
	TkTextUpdateAlteredFlag(sharedTextPtr);
    }

6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
	}
    }

    /*
     * Parse the elements of the list one at a time to fill in the array.
     */

    tabArrayPtr = malloc(sizeof(TkTextTabArray) + (count - 1)*sizeof(TkTextTab));
    tabArrayPtr->numTabs = 0;
    prevStop = 0.0;
    lastStop = 0.0;
    for (i = 0, tabPtr = &tabArrayPtr->tabs[0]; i < objc; i++, tabPtr++) {
	int index;

	/*







|







6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
	}
    }

    /*
     * Parse the elements of the list one at a time to fill in the array.
     */

    tabArrayPtr = ckalloc(sizeof(TkTextTabArray) + (count - 1)*sizeof(TkTextTab));
    tabArrayPtr->numTabs = 0;
    prevStop = 0.0;
    lastStop = 0.0;
    for (i = 0, tabPtr = &tabArrayPtr->tabs[0]; i < objc; i++, tabPtr++) {
	int index;

	/*
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050

    tabArrayPtr->lastTab = lastStop;
    tabArrayPtr->tabIncrement = lastStop - prevStop;

    return tabArrayPtr;

  error:
    free(tabArrayPtr);
    return NULL;
}

/*
 *----------------------------------------------------------------------
 *
 * TextDumpCmd --







|







7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051

    tabArrayPtr->lastTab = lastStop;
    tabArrayPtr->tabIncrement = lastStop - prevStop;

    return tabArrayPtr;

  error:
    ckfree(tabArrayPtr);
    return NULL;
}

/*
 *----------------------------------------------------------------------
 *
 * TextDumpCmd --
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
			 * text, we could not confidently revert the modification here.
			 */

			int length = last - first;

			if (length >= bufSize) {
			    bufSize = MAX(length + 1, 2*length);
			    buffer = realloc(buffer, bufSize);
			}

			memcpy(buffer, segPtr->body.chars + first, length);
			buffer[length] = '\0';

			TkTextMakeByteIndex(sharedTextPtr->tree, textPtr, lineno,
				offset + first, &index);







|







7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
			 * text, we could not confidently revert the modification here.
			 */

			int length = last - first;

			if (length >= bufSize) {
			    bufSize = MAX(length + 1, 2*length);
			    buffer = ckrealloc(buffer, bufSize);
			}

			memcpy(buffer, segPtr->body.chars + first, length);
			buffer[length] = '\0';

			TkTextMakeByteIndex(sharedTextPtr->tree, textPtr, lineno,
				offset + first, &index);
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
	if (sPtr != segPtr) {
	    segPtr = newSegPtr;
	} else if (offset >= segPtr->size) {
	    segPtr = segPtr->nextPtr;
	}
    }

    free(buffer);
    return !textChanged;
}

/*
 *----------------------------------------------------------------------
 *
 * TextChecksumCmd --







|







7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
	if (sPtr != segPtr) {
	    segPtr = newSegPtr;
	} else if (offset >= segPtr->size) {
	    segPtr = segPtr->nextPtr;
	}
    }

    ckfree(buffer);
    return !textChanged;
}

/*
 *----------------------------------------------------------------------
 *
 * TextChecksumCmd --
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
    linePtr = segPtr->sectionPtr->linePtr;
    if (endPtr->sectionPtr->linePtr != linePtr) {
	endPtr = NULL;
    }
    crc = 0;

    if ((what & SEG_GROUP_TAG)) {
	tagArrPtr = malloc(sizeof(tagArrPtr[0])*sharedTextPtr->numTags);
    }

    /*
     * Note that 0xff cannot occur in UTF-8 strings, so we can use this value as a separator.
     */

    while (segPtr != endPtr) {







|







7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
    linePtr = segPtr->sectionPtr->linePtr;
    if (endPtr->sectionPtr->linePtr != linePtr) {
	endPtr = NULL;
    }
    crc = 0;

    if ((what & SEG_GROUP_TAG)) {
	tagArrPtr = ckalloc(sizeof(tagArrPtr[0])*sharedTextPtr->numTags);
    }

    /*
     * Note that 0xff cannot occur in UTF-8 strings, so we can use this value as a separator.
     */

    while (segPtr != endPtr) {
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
	if (!(segPtr = segPtr->nextPtr)) {
	    linePtr = linePtr->nextPtr;
	    segPtr = linePtr->segPtr;
	}
    }

    if ((what & SEG_GROUP_TAG)) {
	free(tagArrPtr);
    }
    Tcl_SetObjResult(interp, Tcl_NewWideIntObj(crc));
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------







|







7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
	if (!(segPtr = segPtr->nextPtr)) {
	    linePtr = linePtr->nextPtr;
	    segPtr = linePtr->segPtr;
	}
    }

    if ((what & SEG_GROUP_TAG)) {
	ckfree(tagArrPtr);
    }
    Tcl_SetObjResult(interp, Tcl_NewWideIntObj(crc));
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
    epoch = sharedTextPtr->inspectEpoch;
    tagPtr = textPtr->selTagPtr; /* any non-null value */
    nextPtr = textPtr->startMarker;
    closeSubList = false;
    prevTagPtr = NULL;
    prevPtr = NULL;
    tagArrSize = 128;
    tagArray = malloc(tagArrSize * sizeof(tagArray[0]));

    assert(textPtr->selTagPtr->textPtr == textPtr);
    if (what & TK_DUMP_DISCARD_SEL) {
	/* this little trick is discarding the "sel" tag */
	textPtr->selTagPtr->textPtr = (TkText *) textPtr->selTagPtr;
    }








|







8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
    epoch = sharedTextPtr->inspectEpoch;
    tagPtr = textPtr->selTagPtr; /* any non-null value */
    nextPtr = textPtr->startMarker;
    closeSubList = false;
    prevTagPtr = NULL;
    prevPtr = NULL;
    tagArrSize = 128;
    tagArray = ckalloc(tagArrSize * sizeof(tagArray[0]));

    assert(textPtr->selTagPtr->textPtr == textPtr);
    if (what & TK_DUMP_DISCARD_SEL) {
	/* this little trick is discarding the "sel" tag */
	textPtr->selTagPtr->textPtr = (TkText *) textPtr->selTagPtr;
    }

8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
		    }
		}

		for ( ; prevTagPtr; prevTagPtr = prevTagPtr->succPtr) {
		    if (prevTagPtr->flag == epoch) { /* should be closed? */
			if (numTags == tagArrSize) {
			    tagArrSize *= 2;
			    tagArray = realloc(tagArray, tagArrSize * sizeof(tagArray[0]));
			}
			tagArray[numTags++] = prevTagPtr;
			prevTagPtr->flag = 0; /* mark as closed */
		    }
		}

		Tcl_DStringStartSublist(str);







|







8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
		    }
		}

		for ( ; prevTagPtr; prevTagPtr = prevTagPtr->succPtr) {
		    if (prevTagPtr->flag == epoch) { /* should be closed? */
			if (numTags == tagArrSize) {
			    tagArrSize *= 2;
			    tagArray = ckrealloc(tagArray, tagArrSize * sizeof(tagArray[0]));
			}
			tagArray[numTags++] = prevTagPtr;
			prevTagPtr->flag = 0; /* mark as closed */
		    }
		}

		Tcl_DStringStartSublist(str);
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
		if (what & TK_DUMP_NESTED) {
		    epoch += 1;

		    for (tPtr = tagPtr; tPtr; tPtr = tPtr->nextPtr) {
			if (tPtr->flag != epoch) { /* should be opened? */
			    if (numTags == tagArrSize) {
				tagArrSize *= 2;
				tagArray = realloc(tagArray, tagArrSize * sizeof(tagArray[0]));
			    }
			    tagArray[numTags++] = tPtr;
			    tPtr->flag = epoch; /* mark as open */
			}
			tPtr->succPtr = tPtr->nextPtr;
		    }
		} else {
		    for (tPtr = tagPtr; tPtr; tPtr = tPtr->nextPtr) {
			if (numTags == tagArrSize) {
			    tagArrSize *= 2;
			    tagArray = realloc(tagArray, tagArrSize * sizeof(tagArray[0]));
			}
			tagArray[numTags++] = tPtr;
		    }
		}

		Tcl_DStringStartSublist(str);
		TkTextSortTags(numTags, tagArray);







|










|







8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
		if (what & TK_DUMP_NESTED) {
		    epoch += 1;

		    for (tPtr = tagPtr; tPtr; tPtr = tPtr->nextPtr) {
			if (tPtr->flag != epoch) { /* should be opened? */
			    if (numTags == tagArrSize) {
				tagArrSize *= 2;
				tagArray = ckrealloc(tagArray, tagArrSize * sizeof(tagArray[0]));
			    }
			    tagArray[numTags++] = tPtr;
			    tPtr->flag = epoch; /* mark as open */
			}
			tPtr->succPtr = tPtr->nextPtr;
		    }
		} else {
		    for (tPtr = tagPtr; tPtr; tPtr = tPtr->nextPtr) {
			if (numTags == tagArrSize) {
			    tagArrSize *= 2;
			    tagArray = ckrealloc(tagArray, tagArrSize * sizeof(tagArray[0]));
			}
			tagArray[numTags++] = tPtr;
		    }
		}

		Tcl_DStringStartSublist(str);
		TkTextSortTags(numTags, tagArray);
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
    assert(!indexPtr1 == !indexPtr2);
    assert(strcmp(operation, "insert") == 0 || strcmp(operation, "delete") == 0);

    sharedTextPtr = textPtr->sharedTextPtr;
    sharedTextPtr->triggerWatchCmd = false;

    if (sharedTextPtr->numPeers > sizeof(peerArr) / sizeof(peerArr[0])) {
	peers = malloc(sharedTextPtr->numPeers * sizeof(peerArr[0]));
    }

    /*
     * Firstly save all peers, we have to take into account that the list of
     * peers is changing when executing the "watch" command.
     */








|







9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
    assert(!indexPtr1 == !indexPtr2);
    assert(strcmp(operation, "insert") == 0 || strcmp(operation, "delete") == 0);

    sharedTextPtr = textPtr->sharedTextPtr;
    sharedTextPtr->triggerWatchCmd = false;

    if (sharedTextPtr->numPeers > sizeof(peerArr) / sizeof(peerArr[0])) {
	peers = ckalloc(sharedTextPtr->numPeers * sizeof(peerArr[0]));
    }

    /*
     * Firstly save all peers, we have to take into account that the list of
     * peers is changing when executing the "watch" command.
     */

9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
			&& tPtr == textPtr) {
		    rc = false; /* this widget has been destroyed */
		}
	    }
	}

	if (--tPtr->refCount == 0) {
	    free(tPtr);
	}
    }

    if (peers != peerArr) {
	free(peers);
    }

    sharedTextPtr->triggerWatchCmd = true;
    return rc;
}

/*







|




|







9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
			&& tPtr == textPtr) {
		    rc = false; /* this widget has been destroyed */
		}
	    }
	}

	if (--tPtr->refCount == 0) {
	    ckfree(tPtr);
	}
    }

    if (peers != peerArr) {
	ckfree(peers);
    }

    sharedTextPtr->triggerWatchCmd = true;
    return rc;
}

/*
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
			    /*
			     * We've run out of space in our normal store, so
			     * we must allocate space for these backwards
			     * matches on the heap.
			     */

			    int matchNumSize = matchNum * sizeof(int32_t);
			    int32_t *newArray = malloc(4*matchNumSize);
			    memcpy(newArray, storeMatch, matchNumSize);
			    memcpy(newArray + 2*matchNum, storeLength, matchNumSize);
			    if (storeMatch != smArray) {
				free((char *) storeMatch);
			    }
			    matchNum *= 2;
			    storeMatch = newArray;
			    storeLength = newArray + matchNum;
			}
			storeMatch[matches] = matchOffset;
			storeLength[matches] = matchLength;







|



|







10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
			    /*
			     * We've run out of space in our normal store, so
			     * we must allocate space for these backwards
			     * matches on the heap.
			     */

			    int matchNumSize = matchNum * sizeof(int32_t);
			    int32_t *newArray = ckalloc(4*matchNumSize);
			    memcpy(newArray, storeMatch, matchNumSize);
			    memcpy(newArray + 2*matchNum, storeLength, matchNumSize);
			    if (storeMatch != smArray) {
				ckfree((char *) storeMatch);
			    }
			    matchNum *= 2;
			    storeMatch = newArray;
			    storeLength = newArray + matchNum;
			}
			storeMatch[matches] = matchOffset;
			storeLength[matches] = matchLength;
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
    Tcl_DecrRefCount(patObj);

    /*
     * Free up any extra space we allocated.
     */

    if (storeMatch != smArray) {
	free((char *) storeMatch);
    }

    return code;
}

/*
 *----------------------------------------------------------------------







|







10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
    Tcl_DecrRefCount(patObj);

    /*
     * Free up any extra space we allocated.
     */

    if (storeMatch != smArray) {
	ckfree((char *) storeMatch);
    }

    return code;
}

/*
 *----------------------------------------------------------------------

Changes to generic/tkText.h.

21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44





45
46
47
48
49
50
51
#ifndef _TKINT
# include "tkInt.h"
#endif

#include "tkTextUndo.h"
#include "tkQTree.h"
#include "tkBool.h"
#include "tkAlloc.h"
#include <stdint.h>

#ifdef MAC_OSX_TK
/* required for TK_LAYOUT_WITH_BASE_CHUNKS */
# include "tkMacOSXInt.h"
#endif

#ifdef _MSC_VER
# if _MSC_VER >= 1900
#  define inline __inline
# else
#  define inline
# endif
#elif __STDC_VERSION__ < 199901L
# define inline /* we are not C99 conform */
#endif






#ifdef BUILD_tk
# undef TCL_STORAGE_CLASS
# define TCL_STORAGE_CLASS DLLEXPORT
#endif

#if TK_CHECK_ALLOCS







|
<















>
>
>
>
>







21
22
23
24
25
26
27
28

29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#ifndef _TKINT
# include "tkInt.h"
#endif

#include "tkTextUndo.h"
#include "tkQTree.h"
#include "tkBool.h"
#include "mystdint.h"


#ifdef MAC_OSX_TK
/* required for TK_LAYOUT_WITH_BASE_CHUNKS */
# include "tkMacOSXInt.h"
#endif

#ifdef _MSC_VER
# if _MSC_VER >= 1900
#  define inline __inline
# else
#  define inline
# endif
#elif __STDC_VERSION__ < 199901L
# define inline /* we are not C99 conform */
#endif

/* ISO hack for dumb VC++ */
#ifdef _MSC_VER
#define   snprintf	_snprintf
#endif

#ifdef BUILD_tk
# undef TCL_STORAGE_CLASS
# define TCL_STORAGE_CLASS DLLEXPORT
#endif

#if TK_CHECK_ALLOCS
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
/*
 * Helper for guarded deallocation.
 */

#define FREE_SEGMENT(ptr) { \
    assert(ptr->typePtr); \
    assert(!(ptr->typePtr = NULL)); \
    free(ptr); }

/*
 * We need a callback function for tag changes. The return value informs whether
 * this operation is undoable.
 */

typedef bool TkTextTagChangedProc(







|







1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
/*
 * Helper for guarded deallocation.
 */

#define FREE_SEGMENT(ptr) { \
    assert(ptr->typePtr); \
    assert(!(ptr->typePtr = NULL)); \
    ckfree(ptr); }

/*
 * We need a callback function for tag changes. The return value informs whether
 * this operation is undoable.
 */

typedef bool TkTextTagChangedProc(

Changes to generic/tkTextBTree.c.

550
551
552
553
554
555
556

557
558
559
560
561
562
563
564
565
566
    return !segPtr->nextPtr;
}

static TkTextSegment *
GetPrevTagInfoSegment(
    TkTextSegment *segPtr)
{

    assert(segPtr);

    TkTextLine *linePtr = segPtr->sectionPtr->linePtr;

    for (segPtr = segPtr->prevPtr; segPtr; segPtr = segPtr->prevPtr) {
	if (segPtr->tagInfoPtr) {
	    return segPtr;
	}
    }








>


|







550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
    return !segPtr->nextPtr;
}

static TkTextSegment *
GetPrevTagInfoSegment(
    TkTextSegment *segPtr)
{
    TkTextLine *linePtr;
    assert(segPtr);

    linePtr = segPtr->sectionPtr->linePtr;

    for (segPtr = segPtr->prevPtr; segPtr; segPtr = segPtr->prevPtr) {
	if (segPtr->tagInfoPtr) {
	    return segPtr;
	}
    }

1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
    unsigned contentSize,
    const Tk_SegType *segType)
{
    TkTextSegment *segPtr;

    assert(segType != &tkTextCharType);

    segPtr = memset(malloc(segByteSize), 0, segByteSize);
    segPtr->typePtr = segType;
    segPtr->size = contentSize;
    segPtr->refCount = 1;
    DEBUG_ALLOC(tkTextCountNewSegment++);
    return segPtr;
}








|







1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
    unsigned contentSize,
    const Tk_SegType *segType)
{
    TkTextSegment *segPtr;

    assert(segType != &tkTextCharType);

    segPtr = memset(ckalloc(segByteSize), 0, segByteSize);
    segPtr->typePtr = segType;
    segPtr->size = contentSize;
    segPtr->refCount = 1;
    DEBUG_ALLOC(tkTextCountNewSegment++);
    return segPtr;
}

1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
    CleanupSplitPoint(lastPtr, sharedTextPtr);

    /*
     * Prevent that the destroy function will delete these segments.
     * This also makes the token reusable.
     */

    free(undoToken->segments);
    undoToken->segments = NULL;
    undoToken->numSegments = 0;

    /*
     * Update the redo information.
     */








|







1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
    CleanupSplitPoint(lastPtr, sharedTextPtr);

    /*
     * Prevent that the destroy function will delete these segments.
     * This also makes the token reusable.
     */

    ckfree(undoToken->segments);
    undoToken->segments = NULL;
    undoToken->numSegments = 0;

    /*
     * Update the redo information.
     */

1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
	for (segPtr = *segments++; numSegments > 0; segPtr = *segments++, --numSegments) {
	    UNMARK_POINTER(segPtr);
	    assert(segPtr->typePtr);
	    assert(segPtr->typePtr->deleteProc);
	    segPtr->typePtr->deleteProc(sharedTextPtr->tree, segPtr, DELETE_BRANCHES | DELETE_MARKS);
	}

	free(((UndoTokenDelete *) token)->segments);
    }
}

static Tcl_Obj *
RedoDeleteInspect(
    const TkSharedText *sharedTextPtr,
    const TkTextUndoToken *item)







|







1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
	for (segPtr = *segments++; numSegments > 0; segPtr = *segments++, --numSegments) {
	    UNMARK_POINTER(segPtr);
	    assert(segPtr->typePtr);
	    assert(segPtr->typePtr->deleteProc);
	    segPtr->typePtr->deleteProc(sharedTextPtr->tree, segPtr, DELETE_BRANCHES | DELETE_MARKS);
	}

	ckfree(((UndoTokenDelete *) token)->segments);
    }
}

static Tcl_Obj *
RedoDeleteInspect(
    const TkSharedText *sharedTextPtr,
    const TkTextUndoToken *item)
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
    bool reused)
{
    if (!reused) {
	UndoTokenTagChange *token = (UndoTokenTagChange *) item;

	UNMARK_POINTER(token->tagPtr);
	TkTextReleaseTag(sharedTextPtr, token->tagPtr, NULL);
	free(token->lengths);
	token->lengths = NULL;
    }
}

/* TAG CLEAR *****************************************************************/

static Tcl_Obj *







|







1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
    bool reused)
{
    if (!reused) {
	UndoTokenTagChange *token = (UndoTokenTagChange *) item;

	UNMARK_POINTER(token->tagPtr);
	TkTextReleaseTag(sharedTextPtr, token->tagPtr, NULL);
	ckfree(token->lengths);
	token->lengths = NULL;
    }
}

/* TAG CLEAR *****************************************************************/

static Tcl_Obj *
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
    lastSegPtr->protectionFlag = true;
    CleanupSplitPoint(firstSegPtr, sharedTextPtr);
    CleanupSplitPoint(lastSegPtr, sharedTextPtr);
    TkBTreeIncrEpoch(sharedTextPtr->tree);
    TkTextRedrawTag(sharedTextPtr, NULL, &startIndex, &endIndex, NULL, affectsDisplayGeometry);

    if (redoInfo) {
	RedoTokenClearTags *redoToken = malloc(sizeof(RedoTokenClearTags));
	redoToken->undoType = &redoTokenClearTagsType;
	redoToken->startIndex = token->startIndex;
	redoToken->endIndex = token->endIndex;
	redoInfo->token = (TkTextUndoToken *) redoToken;
	DEBUG_ALLOC(tkTextCountNewUndoToken++);
    }








|







1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
    lastSegPtr->protectionFlag = true;
    CleanupSplitPoint(firstSegPtr, sharedTextPtr);
    CleanupSplitPoint(lastSegPtr, sharedTextPtr);
    TkBTreeIncrEpoch(sharedTextPtr->tree);
    TkTextRedrawTag(sharedTextPtr, NULL, &startIndex, &endIndex, NULL, affectsDisplayGeometry);

    if (redoInfo) {
	RedoTokenClearTags *redoToken = ckalloc(sizeof(RedoTokenClearTags));
	redoToken->undoType = &redoTokenClearTagsType;
	redoToken->startIndex = token->startIndex;
	redoToken->endIndex = token->endIndex;
	redoInfo->token = (TkTextUndoToken *) redoToken;
	DEBUG_ALLOC(tkTextCountNewUndoToken++);
    }

1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891

    assert(!reused);

    for (i = 0; i < n; ++i) {
	TkTextTagSetDecrRefCount(changeList[i].tagInfoPtr);
    }

    free(changeList);
}

static void
RedoClearTagsPerform(
    TkSharedText *sharedTextPtr,
    TkTextUndoInfo *undoInfo,
    TkTextUndoInfo *redoInfo,







|







1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892

    assert(!reused);

    for (i = 0; i < n; ++i) {
	TkTextTagSetDecrRefCount(changeList[i].tagInfoPtr);
    }

    ckfree(changeList);
}

static void
RedoClearTagsPerform(
    TkSharedText *sharedTextPtr,
    TkTextUndoInfo *undoInfo,
    TkTextUndoInfo *redoInfo,
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
     * operations easier. The second line contains the end marker. The tree
     * will have one node, which is also the root of the tree.
     *
     * The tree currently has no registered clients, so all pixel count
     * pointers are simply NULL.
     */

    rootPtr = memset(malloc(sizeof(Node)), 0, sizeof(Node));
    DEBUG_ALLOC(tkTextCountNewNode++);

    treePtr = memset(malloc(sizeof(BTree)), 0, sizeof(BTree));
    treePtr->rootPtr = rootPtr;
    treePtr->sharedTextPtr = sharedTextPtr;
    treePtr->stateEpoch = epoch;
    sharedTextPtr->tree = (TkTextBTree) treePtr;

    assert(!sharedTextPtr->startMarker->nextPtr);
    linePtr = InsertNewLine(sharedTextPtr, rootPtr, NULL, sharedTextPtr->startMarker);







|


|







1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
     * operations easier. The second line contains the end marker. The tree
     * will have one node, which is also the root of the tree.
     *
     * The tree currently has no registered clients, so all pixel count
     * pointers are simply NULL.
     */

    rootPtr = memset(ckalloc(sizeof(Node)), 0, sizeof(Node));
    DEBUG_ALLOC(tkTextCountNewNode++);

    treePtr = memset(ckalloc(sizeof(BTree)), 0, sizeof(BTree));
    treePtr->rootPtr = rootPtr;
    treePtr->sharedTextPtr = sharedTextPtr;
    treePtr->stateEpoch = epoch;
    sharedTextPtr->tree = (TkTextBTree) treePtr;

    assert(!sharedTextPtr->startMarker->nextPtr);
    linePtr = InsertNewLine(sharedTextPtr, rootPtr, NULL, sharedTextPtr->startMarker);
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
	unsigned useReference = treePtr->numPixelReferences;

	AdjustPixelClient(treePtr, defaultHeight, treePtr->rootPtr, TkBTreeGetStartLine(textPtr),
		TkBTreeGetLastLine(textPtr), useReference, useReference + 1, NULL);

	textPtr->pixelReference = useReference;
	treePtr->numPixelReferences += 1;
	treePtr->pixelInfoBuffer = realloc(treePtr->pixelInfoBuffer,
		sizeof(treePtr->pixelInfoBuffer[0])*treePtr->numPixelReferences);
    } else {
	textPtr->pixelReference = -1;
    }

    treePtr->clients += 1;
}







|







2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
	unsigned useReference = treePtr->numPixelReferences;

	AdjustPixelClient(treePtr, defaultHeight, treePtr->rootPtr, TkBTreeGetStartLine(textPtr),
		TkBTreeGetLastLine(textPtr), useReference, useReference + 1, NULL);

	textPtr->pixelReference = useReference;
	treePtr->numPixelReferences += 1;
	treePtr->pixelInfoBuffer = ckrealloc(treePtr->pixelInfoBuffer,
		sizeof(treePtr->pixelInfoBuffer[0])*treePtr->numPixelReferences);
    } else {
	textPtr->pixelReference = -1;
    }

    treePtr->clients += 1;
}
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203

    if (treePtr->clients == 1) {
	/*
	 * The last reference to the tree.
	 */

	DestroyNode(tree, treePtr->rootPtr);
	free(treePtr);
	return;
    }

    if (pixelReference == -1) {
	/*
	 * A client which doesn't care about pixels.
	 */







|







2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204

    if (treePtr->clients == 1) {
	/*
	 * The last reference to the tree.
	 */

	DestroyNode(tree, treePtr->rootPtr);
	ckfree(treePtr);
	return;
    }

    if (pixelReference == -1) {
	/*
	 * A client which doesn't care about pixels.
	 */
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
		adjustPtr = adjustPtr->next;
	    }
	    assert(adjustPtr);
	}

	treePtr->numPixelReferences -= 1;
	treePtr->clients -= 1;
	treePtr->pixelInfoBuffer = realloc(treePtr->pixelInfoBuffer,
		sizeof(treePtr->pixelInfoBuffer[0])*treePtr->numPixelReferences);
    }
}

/*
 *----------------------------------------------------------------------
 *







|







2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
		adjustPtr = adjustPtr->next;
	    }
	    assert(adjustPtr);
	}

	treePtr->numPixelReferences -= 1;
	treePtr->clients -= 1;
	treePtr->pixelInfoBuffer = ckrealloc(treePtr->pixelInfoBuffer,
		sizeof(treePtr->pixelInfoBuffer[0])*treePtr->numPixelReferences);
    }
}

/*
 *----------------------------------------------------------------------
 *
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
	    /*
	     * Notice that for the very last line, we are never counting and
	     * therefore this always has a height of 0 and an epoch of 1.
	     */

	    if (newPixelReferences > treePtr->numPixelReferences) {
		DEBUG_ALLOC(if (!linePtr->pixelInfo) tkTextCountNewPixelInfo++);
		linePtr->pixelInfo = realloc(linePtr->pixelInfo,
			sizeof(linePtr->pixelInfo[0])*newPixelReferences);
		memset(&linePtr->pixelInfo[useReference], 0, sizeof(TkTextPixelInfo));
	    } else if (linePtr->pixelInfo[useReference].dispLineInfo) {
		free(linePtr->pixelInfo[useReference].dispLineInfo);
		linePtr->pixelInfo[useReference].dispLineInfo = NULL;
		DEBUG_ALLOC(tkTextCountDestroyDispInfo++);
	    }

	    linePtr->pixelInfo[useReference].epoch = epoch;
	    pixelCount += (linePtr->pixelInfo[useReference].height = height);
	    numDispLines += GetDisplayLines(linePtr, useReference);
	}
    }

    if (newPixelReferences > treePtr->numPixelReferences) {
	DEBUG_ALLOC(if (!nodePtr->pixelInfo) tkTextCountNewPixelInfo++);
	nodePtr->pixelInfo = realloc(nodePtr->pixelInfo,
		sizeof(nodePtr->pixelInfo[0])*newPixelReferences);
    }
    nodePtr->pixelInfo[useReference].pixels = pixelCount;
    nodePtr->pixelInfo[useReference].numDispLines = numDispLines;
    if (numDispLinesPtr) {
	*numDispLinesPtr += numDispLines;
    }







|



|












|







2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
	    /*
	     * Notice that for the very last line, we are never counting and
	     * therefore this always has a height of 0 and an epoch of 1.
	     */

	    if (newPixelReferences > treePtr->numPixelReferences) {
		DEBUG_ALLOC(if (!linePtr->pixelInfo) tkTextCountNewPixelInfo++);
		linePtr->pixelInfo = ckrealloc(linePtr->pixelInfo,
			sizeof(linePtr->pixelInfo[0])*newPixelReferences);
		memset(&linePtr->pixelInfo[useReference], 0, sizeof(TkTextPixelInfo));
	    } else if (linePtr->pixelInfo[useReference].dispLineInfo) {
		ckfree(linePtr->pixelInfo[useReference].dispLineInfo);
		linePtr->pixelInfo[useReference].dispLineInfo = NULL;
		DEBUG_ALLOC(tkTextCountDestroyDispInfo++);
	    }

	    linePtr->pixelInfo[useReference].epoch = epoch;
	    pixelCount += (linePtr->pixelInfo[useReference].height = height);
	    numDispLines += GetDisplayLines(linePtr, useReference);
	}
    }

    if (newPixelReferences > treePtr->numPixelReferences) {
	DEBUG_ALLOC(if (!nodePtr->pixelInfo) tkTextCountNewPixelInfo++);
	nodePtr->pixelInfo = ckrealloc(nodePtr->pixelInfo,
		sizeof(nodePtr->pixelInfo[0])*newPixelReferences);
    }
    nodePtr->pixelInfo[useReference].pixels = pixelCount;
    nodePtr->pixelInfo[useReference].numDispLines = numDispLines;
    if (numDispLinesPtr) {
	*numDispLinesPtr += numDispLines;
    }
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
     * we're deleting).
     */

    if (overwriteWithLast != -1) {
	nodePtr->pixelInfo[overwriteWithLast] = nodePtr->pixelInfo[treePtr->numPixelReferences - 1];
    }
    if (treePtr->numPixelReferences == 1) {
	free(nodePtr->pixelInfo);
	nodePtr->pixelInfo = NULL;
	DEBUG_ALLOC(tkTextCountDestroyPixelInfo++);
    } else {
	nodePtr->pixelInfo = realloc(nodePtr->pixelInfo,
		sizeof(nodePtr->pixelInfo[0])*(treePtr->numPixelReferences - 1));
    }
    if (nodePtr->level != 0) {
	nodePtr = nodePtr->childPtr;
	while (nodePtr) {
	    RemovePixelClient(treePtr, nodePtr, useReference, overwriteWithLast);
	    nodePtr = nodePtr->nextPtr;
	}
    } else {
	TkTextLine *linePtr = nodePtr->linePtr;
	TkTextLine *lastPtr = nodePtr->lastPtr->nextPtr;

	while (linePtr != lastPtr) {
	    if (linePtr->pixelInfo[useReference].dispLineInfo) {
		free(linePtr->pixelInfo[useReference].dispLineInfo);
		DEBUG_ALLOC(tkTextCountDestroyDispInfo++);
	    }
	    if (overwriteWithLast != -1) {
		linePtr->pixelInfo[overwriteWithLast] =
			linePtr->pixelInfo[treePtr->numPixelReferences - 1];
	    }
	    if (treePtr->numPixelReferences == 1) {
		free(linePtr->pixelInfo);
		linePtr->pixelInfo = NULL;
		DEBUG_ALLOC(tkTextCountDestroyPixelInfo++);
	    } else {
		linePtr->pixelInfo = realloc(linePtr->pixelInfo,
			sizeof(linePtr->pixelInfo[0])*(treePtr->numPixelReferences - 1));
	    }
	    linePtr = linePtr->nextPtr;
	}
    }
}








|



|














|







|



|







2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
     * we're deleting).
     */

    if (overwriteWithLast != -1) {
	nodePtr->pixelInfo[overwriteWithLast] = nodePtr->pixelInfo[treePtr->numPixelReferences - 1];
    }
    if (treePtr->numPixelReferences == 1) {
	ckfree(nodePtr->pixelInfo);
	nodePtr->pixelInfo = NULL;
	DEBUG_ALLOC(tkTextCountDestroyPixelInfo++);
    } else {
	nodePtr->pixelInfo = ckrealloc(nodePtr->pixelInfo,
		sizeof(nodePtr->pixelInfo[0])*(treePtr->numPixelReferences - 1));
    }
    if (nodePtr->level != 0) {
	nodePtr = nodePtr->childPtr;
	while (nodePtr) {
	    RemovePixelClient(treePtr, nodePtr, useReference, overwriteWithLast);
	    nodePtr = nodePtr->nextPtr;
	}
    } else {
	TkTextLine *linePtr = nodePtr->linePtr;
	TkTextLine *lastPtr = nodePtr->lastPtr->nextPtr;

	while (linePtr != lastPtr) {
	    if (linePtr->pixelInfo[useReference].dispLineInfo) {
		ckfree(linePtr->pixelInfo[useReference].dispLineInfo);
		DEBUG_ALLOC(tkTextCountDestroyDispInfo++);
	    }
	    if (overwriteWithLast != -1) {
		linePtr->pixelInfo[overwriteWithLast] =
			linePtr->pixelInfo[treePtr->numPixelReferences - 1];
	    }
	    if (treePtr->numPixelReferences == 1) {
		ckfree(linePtr->pixelInfo);
		linePtr->pixelInfo = NULL;
		DEBUG_ALLOC(tkTextCountDestroyPixelInfo++);
	    } else {
		linePtr->pixelInfo = ckrealloc(linePtr->pixelInfo,
			sizeof(linePtr->pixelInfo[0])*(treePtr->numPixelReferences - 1));
	    }
	    linePtr = linePtr->nextPtr;
	}
    }
}

2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
	    myToken1->endIndex.lineIndex = myToken2->startIndex.lineIndex;
	} else {
	    myToken1->endIndex.u.byteIndex = myToken1->startIndex.u.byteIndex + byteSize1 + byteSize2;
	    myToken1->endIndex.lineIndex = myToken1->startIndex.lineIndex;
	}

	myToken1->numSegments += myToken2->numSegments;
	myToken1->segments = realloc(myToken1->segments,
		myToken1->numSegments*sizeof(myToken1->segments[0]));
	memcpy(myToken1->segments + numSegments1, myToken2->segments,
		myToken2->numSegments*sizeof(myToken2->segments[0]));
	free(myToken2->segments);
	myToken2->numSegments = 0;
    } else if (UndoIndexIsEqual(&myToken1->startIndex, &myToken2->endIndex)) {
	unsigned numSegments1 = myToken1->numSegments;
	TkTextSegment **segments;

	if (myToken2->startIndex.lineIndex == -1) {
	    myToken1->startIndex = myToken2->startIndex;
	} else if (myToken2->endIndex.lineIndex != -1) {
	    myToken1->startIndex.u.byteIndex = myToken2->endIndex.u.byteIndex - byteSize1;
	    myToken1->startIndex.lineIndex = myToken2->endIndex.lineIndex;
	} else if (myToken1->endIndex.lineIndex != -1) {
	    myToken1->startIndex.u.byteIndex = myToken1->endIndex.u.byteIndex - byteSize1 - byteSize2;
	    myToken1->startIndex.lineIndex = myToken1->endIndex.lineIndex;
	} else {
	    myToken1->startIndex.u.byteIndex = myToken1->startIndex.u.byteIndex + byteSize1 + byteSize2;
	    myToken1->startIndex.lineIndex = myToken1->startIndex.lineIndex;
	}

	myToken1->numSegments += myToken2->numSegments;
	segments = malloc(myToken1->numSegments*sizeof(segments[0]));
	memcpy(segments, myToken2->segments, myToken2->numSegments*sizeof(myToken2->segments[0]));
	memcpy(segments + myToken2->numSegments, myToken1->segments,
		numSegments1*sizeof(myToken1->segments[0]));
	free(myToken1->segments);
	free(myToken2->segments);
	myToken1->segments = segments;
	myToken2->numSegments = 0;
    } else {
	return false;
    }

    return true;







|



|



















|



|
|







2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
	    myToken1->endIndex.lineIndex = myToken2->startIndex.lineIndex;
	} else {
	    myToken1->endIndex.u.byteIndex = myToken1->startIndex.u.byteIndex + byteSize1 + byteSize2;
	    myToken1->endIndex.lineIndex = myToken1->startIndex.lineIndex;
	}

	myToken1->numSegments += myToken2->numSegments;
	myToken1->segments = ckrealloc(myToken1->segments,
		myToken1->numSegments*sizeof(myToken1->segments[0]));
	memcpy(myToken1->segments + numSegments1, myToken2->segments,
		myToken2->numSegments*sizeof(myToken2->segments[0]));
	ckfree(myToken2->segments);
	myToken2->numSegments = 0;
    } else if (UndoIndexIsEqual(&myToken1->startIndex, &myToken2->endIndex)) {
	unsigned numSegments1 = myToken1->numSegments;
	TkTextSegment **segments;

	if (myToken2->startIndex.lineIndex == -1) {
	    myToken1->startIndex = myToken2->startIndex;
	} else if (myToken2->endIndex.lineIndex != -1) {
	    myToken1->startIndex.u.byteIndex = myToken2->endIndex.u.byteIndex - byteSize1;
	    myToken1->startIndex.lineIndex = myToken2->endIndex.lineIndex;
	} else if (myToken1->endIndex.lineIndex != -1) {
	    myToken1->startIndex.u.byteIndex = myToken1->endIndex.u.byteIndex - byteSize1 - byteSize2;
	    myToken1->startIndex.lineIndex = myToken1->endIndex.lineIndex;
	} else {
	    myToken1->startIndex.u.byteIndex = myToken1->startIndex.u.byteIndex + byteSize1 + byteSize2;
	    myToken1->startIndex.lineIndex = myToken1->startIndex.lineIndex;
	}

	myToken1->numSegments += myToken2->numSegments;
	segments = ckalloc(myToken1->numSegments*sizeof(segments[0]));
	memcpy(segments, myToken2->segments, myToken2->numSegments*sizeof(myToken2->segments[0]));
	memcpy(segments + myToken2->numSegments, myToken1->segments,
		numSegments1*sizeof(myToken1->segments[0]));
	ckfree(myToken1->segments);
	ckfree(myToken2->segments);
	myToken1->segments = segments;
	myToken2->numSegments = 0;
    } else {
	return false;
    }

    return true;
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
    /*
     * There's no need to loop over each client of the tree, calling
     * 'TkBTreeRemoveClient', since the 'DestroyNode' will clean everything up
     * itself.
     */

    DestroyNode(tree, treePtr->rootPtr);
    free(treePtr);
}

/*
 *----------------------------------------------------------------------
 *
 * TkBTreeHaveElidedSegments --
 *







|







2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
    /*
     * There's no need to loop over each client of the tree, calling
     * 'TkBTreeRemoveClient', since the 'DestroyNode' will clean everything up
     * itself.
     */

    DestroyNode(tree, treePtr->rootPtr);
    ckfree(treePtr);
}

/*
 *----------------------------------------------------------------------
 *
 * TkBTreeHaveElidedSegments --
 *
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
static void
FreeNode(
    Node *nodePtr)	/* Free storage of this node. */
{
    assert(nodePtr->level > 0 || nodePtr->linePtr);
    TkTextTagSetDecrRefCount(nodePtr->tagonPtr);
    TkTextTagSetDecrRefCount(nodePtr->tagoffPtr);
    free(nodePtr->pixelInfo);
    DEBUG(nodePtr->linePtr = NULL); /* guarded deallocation */
    free(nodePtr);
    DEBUG_ALLOC(tkTextCountDestroyPixelInfo++);
    DEBUG_ALLOC(tkTextCountDestroyNode++);
}

/*
 *----------------------------------------------------------------------
 *







|

|







2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
static void
FreeNode(
    Node *nodePtr)	/* Free storage of this node. */
{
    assert(nodePtr->level > 0 || nodePtr->linePtr);
    TkTextTagSetDecrRefCount(nodePtr->tagonPtr);
    TkTextTagSetDecrRefCount(nodePtr->tagoffPtr);
    ckfree(nodePtr->pixelInfo);
    DEBUG(nodePtr->linePtr = NULL); /* guarded deallocation */
    ckfree(nodePtr);
    DEBUG_ALLOC(tkTextCountDestroyPixelInfo++);
    DEBUG_ALLOC(tkTextCountDestroyNode++);
}

/*
 *----------------------------------------------------------------------
 *
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
	changeToDispLines += (int) GetDisplayLines(linePtr, pixelReference);
	changeToPixels += pixelInfo->height;
	pixelInfo->epoch = 0;
	pixelInfo->height = 0;
	linePtr = linePtr->nextPtr;

	if (pixelInfo->dispLineInfo) {
	    free(pixelInfo->dispLineInfo);
	    pixelInfo->dispLineInfo = NULL;
	    DEBUG_ALLOC(tkTextCountDestroyDispInfo++);
	}

	if (nodePtr != linePtr->parentPtr) {
	    PropagateDispLineChange(nodePtr, pixelReference, changeToDispLines, changeToPixels);
	    changeToDispLines = 0;







|







2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
	changeToDispLines += (int) GetDisplayLines(linePtr, pixelReference);
	changeToPixels += pixelInfo->height;
	pixelInfo->epoch = 0;
	pixelInfo->height = 0;
	linePtr = linePtr->nextPtr;

	if (pixelInfo->dispLineInfo) {
	    ckfree(pixelInfo->dispLineInfo);
	    pixelInfo->dispLineInfo = NULL;
	    DEBUG_ALLOC(tkTextCountDestroyDispInfo++);
	}

	if (nodePtr != linePtr->parentPtr) {
	    PropagateDispLineChange(nodePtr, pixelReference, changeToDispLines, changeToPixels);
	    changeToDispLines = 0;
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914

	if (pixelInfo->dispLineInfo) {
	    changeToDispLines -= (int) GetDisplayLines(linePtr, pixelReference);
	    if (pixelInfo->height > 0) {
		changeToDispLines += 1;
	    }
	    if (pixelInfo->dispLineInfo) {
		free(pixelInfo->dispLineInfo);
		pixelInfo->dispLineInfo = NULL;
		DEBUG_ALLOC(tkTextCountDestroyDispInfo++);
	    }
	}

	pixelInfo->epoch = epoch;
	changeToPixels -= pixelInfo->height;







|







2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915

	if (pixelInfo->dispLineInfo) {
	    changeToDispLines -= (int) GetDisplayLines(linePtr, pixelReference);
	    if (pixelInfo->height > 0) {
		changeToDispLines += 1;
	    }
	    if (pixelInfo->dispLineInfo) {
		ckfree(pixelInfo->dispLineInfo);
		pixelInfo->dispLineInfo = NULL;
		DEBUG_ALLOC(tkTextCountDestroyDispInfo++);
	    }
	}

	pixelInfo->epoch = epoch;
	changeToPixels -= pixelInfo->height;
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
    unsigned ref;

    /*
     * Set up a starting default height, which will be re-adjusted later.
     * We need to do this for each referenced widget.
     */

    linePtr->pixelInfo = malloc(sizeof(TkTextPixelInfo)*treePtr->numPixelReferences);
    DEBUG_ALLOC(tkTextCountNewPixelInfo++);

    for (ref = 0; ref < treePtr->numPixelReferences; ++ref) {
	TkTextPixelInfo *pixelInfo = linePtr->pixelInfo + ref;
	const TkTextPixelInfo *refPixelInfo = refLinePtr->pixelInfo + ref;
	NodePixelInfo *pixelInfoChange = changeToPixelInfo + ref;
	int height = refPixelInfo->height;







|







3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
    unsigned ref;

    /*
     * Set up a starting default height, which will be re-adjusted later.
     * We need to do this for each referenced widget.
     */

    linePtr->pixelInfo = ckalloc(sizeof(TkTextPixelInfo)*treePtr->numPixelReferences);
    DEBUG_ALLOC(tkTextCountNewPixelInfo++);

    for (ref = 0; ref < treePtr->numPixelReferences; ++ref) {
	TkTextPixelInfo *pixelInfo = linePtr->pixelInfo + ref;
	const TkTextPixelInfo *refPixelInfo = refLinePtr->pixelInfo + ref;
	NodePixelInfo *pixelInfoChange = changeToPixelInfo + ref;
	int height = refPixelInfo->height;
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
    if (prevPtr) {
	prevPtr->nextPtr = NULL;
	lastPtr = prevLinePtr->lastPtr;
	prevLinePtr->lastPtr = prevPtr;
	segPtr->prevPtr = NULL;
    }

    newLinePtr = memset(malloc(sizeof(TkTextLine)), 0, sizeof(TkTextLine));
    newLinePtr->parentPtr = nodePtr;
    newLinePtr->prevPtr = prevLinePtr;
    newLinePtr->segPtr = segPtr;
    newLinePtr->lastPtr = lastPtr;
    newLinePtr->logicalLine = true;
    newLinePtr->changed = true;
    DEBUG_ALLOC(tkTextCountNewLine++);







|







3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
    if (prevPtr) {
	prevPtr->nextPtr = NULL;
	lastPtr = prevLinePtr->lastPtr;
	prevLinePtr->lastPtr = prevPtr;
	segPtr->prevPtr = NULL;
    }

    newLinePtr = memset(ckalloc(sizeof(TkTextLine)), 0, sizeof(TkTextLine));
    newLinePtr->parentPtr = nodePtr;
    newLinePtr->prevPtr = prevLinePtr;
    newLinePtr->segPtr = segPtr;
    newLinePtr->lastPtr = lastPtr;
    newLinePtr->logicalLine = true;
    newLinePtr->changed = true;
    DEBUG_ALLOC(tkTextCountNewLine++);
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221

    assert(*string); /* otherwise tag information might become erroneous */
    assert(indexPtr->textPtr);

    sharedTextPtr = treePtr->sharedTextPtr;

    if (undoInfo) {
	undoToken = malloc(sizeof(UndoTokenInsert));
	undoToken->undoType = &undoTokenInsertType;
	undoInfo->token = (TkTextUndoToken *) undoToken;
	undoInfo->byteSize = 0;
	MakeUndoIndex(sharedTextPtr, indexPtr, &undoToken->startIndex, GRAVITY_LEFT);
	DEBUG_ALLOC(tkTextCountNewUndoToken++);
    }








|







4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222

    assert(*string); /* otherwise tag information might become erroneous */
    assert(indexPtr->textPtr);

    sharedTextPtr = treePtr->sharedTextPtr;

    if (undoInfo) {
	undoToken = ckalloc(sizeof(UndoTokenInsert));
	undoToken->undoType = &undoTokenInsertType;
	undoInfo->token = (TkTextUndoToken *) undoToken;
	undoInfo->byteSize = 0;
	MakeUndoIndex(sharedTextPtr, indexPtr, &undoToken->startIndex, GRAVITY_LEFT);
	DEBUG_ALLOC(tkTextCountNewUndoToken++);
    }

5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
	    linePtr->lastPtr = succPtr;
	}
    } else {
	assert(linePtr->segPtr);
	if (linePtr->segPtr->typePtr == &tkTextLinkType) {
	    TkTextSection *newSectionPtr;

	    newSectionPtr = malloc(sizeof(TkTextSection));
	    newSectionPtr->linePtr = linePtr;
	    newSectionPtr->segPtr = succPtr;
	    newSectionPtr->nextPtr = linePtr->segPtr->sectionPtr->nextPtr;
	    newSectionPtr->prevPtr = NULL;
	    newSectionPtr->size = 0;
	    newSectionPtr->length = 0;
	    linePtr->segPtr->sectionPtr->prevPtr = newSectionPtr;







|







5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
	    linePtr->lastPtr = succPtr;
	}
    } else {
	assert(linePtr->segPtr);
	if (linePtr->segPtr->typePtr == &tkTextLinkType) {
	    TkTextSection *newSectionPtr;

	    newSectionPtr = ckalloc(sizeof(TkTextSection));
	    newSectionPtr->linePtr = linePtr;
	    newSectionPtr->segPtr = succPtr;
	    newSectionPtr->nextPtr = linePtr->segPtr->sectionPtr->nextPtr;
	    newSectionPtr->prevPtr = NULL;
	    newSectionPtr->size = 0;
	    newSectionPtr->length = 0;
	    linePtr->segPtr->sectionPtr->prevPtr = newSectionPtr;
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153

static void
FreeSection(
    TkTextSection *sectionPtr)
{
    assert(sectionPtr->linePtr);
    assert(!(sectionPtr->linePtr = NULL));
    free(sectionPtr);
    DEBUG_ALLOC(tkTextCountDestroySection++);
}

static TkTextSegment *
UnlinkSegment(
    TkTextSegment *segPtr)	/* Unlink this segment. */
{







|







5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154

static void
FreeSection(
    TkTextSection *sectionPtr)
{
    assert(sectionPtr->linePtr);
    assert(!(sectionPtr->linePtr = NULL));
    ckfree(sectionPtr);
    DEBUG_ALLOC(tkTextCountDestroySection++);
}

static TkTextSegment *
UnlinkSegment(
    TkTextSegment *segPtr)	/* Unlink this segment. */
{
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
	    }
	    sectionPtr->segPtr = segPtr;
	}

	assert(splitSegPtr);
	assert(lengthRHS == 0 || length - capacityLHS >= MIN_TEXT_SEGS);

	newSectionPtr = malloc(sizeof(TkTextSection));
	newSectionPtr->linePtr = sectionPtr->linePtr;
	newSectionPtr->segPtr = splitSegPtr;
	newSectionPtr->nextPtr = sectionPtr->nextPtr;
	newSectionPtr->prevPtr = sectionPtr;
	newSectionPtr->size = 0;
	newSectionPtr->length = 0;
	if (sectionPtr->nextPtr) {







|







5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
	    }
	    sectionPtr->segPtr = segPtr;
	}

	assert(splitSegPtr);
	assert(lengthRHS == 0 || length - capacityLHS >= MIN_TEXT_SEGS);

	newSectionPtr = ckalloc(sizeof(TkTextSection));
	newSectionPtr->linePtr = sectionPtr->linePtr;
	newSectionPtr->segPtr = splitSegPtr;
	newSectionPtr->nextPtr = sectionPtr->nextPtr;
	newSectionPtr->prevPtr = sectionPtr;
	newSectionPtr->size = 0;
	newSectionPtr->length = 0;
	if (sectionPtr->nextPtr) {
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
    linePtr->numLinks = 0;
    linePtr->size = 0;

    for (segPtr = linePtr->segPtr; segPtr; ) {
	if (!sectionPtr) {
	    TkTextSection *newSectionPtr;

	    newSectionPtr = memset(malloc(sizeof(TkTextSection)), 0, sizeof(TkTextSection));
	    if (prevSectionPtr) {
		prevSectionPtr->nextPtr = newSectionPtr;
	    } else {
		linePtr->segPtr->sectionPtr = newSectionPtr;
	    }
	    newSectionPtr->prevPtr = prevSectionPtr;
	    sectionPtr = newSectionPtr;







|







5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
    linePtr->numLinks = 0;
    linePtr->size = 0;

    for (segPtr = linePtr->segPtr; segPtr; ) {
	if (!sectionPtr) {
	    TkTextSection *newSectionPtr;

	    newSectionPtr = memset(ckalloc(sizeof(TkTextSection)), 0, sizeof(TkTextSection));
	    if (prevSectionPtr) {
		prevSectionPtr->nextPtr = newSectionPtr;
	    } else {
		linePtr->segPtr->sectionPtr = newSectionPtr;
	    }
	    newSectionPtr->prevPtr = prevSectionPtr;
	    sectionPtr = newSectionPtr;
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
    assert(linePtr->parentPtr);
    DEBUG(linePtr->parentPtr = NULL);

    for (i = 0; i < treePtr->numPixelReferences; ++i) {
	TkTextDispLineInfo *dispLineInfo = linePtr->pixelInfo[i].dispLineInfo;

	if (dispLineInfo) {
	    free(dispLineInfo);
	    DEBUG_ALLOC(tkTextCountDestroyDispInfo++);
	}
    }

    TkTextTagSetDecrRefCount(linePtr->tagoffPtr);
    TkTextTagSetDecrRefCount(linePtr->tagonPtr);
    free(linePtr->pixelInfo);
    DEBUG(linePtr->pixelInfo = NULL);
    free(linePtr);
    DEBUG_ALLOC(tkTextCountDestroyPixelInfo++);
    DEBUG_ALLOC(tkTextCountDestroyLine++);
}

/*
 *--------------------------------------------------------------
 *







|






|

|







5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
    assert(linePtr->parentPtr);
    DEBUG(linePtr->parentPtr = NULL);

    for (i = 0; i < treePtr->numPixelReferences; ++i) {
	TkTextDispLineInfo *dispLineInfo = linePtr->pixelInfo[i].dispLineInfo;

	if (dispLineInfo) {
	    ckfree(dispLineInfo);
	    DEBUG_ALLOC(tkTextCountDestroyDispInfo++);
	}
    }

    TkTextTagSetDecrRefCount(linePtr->tagoffPtr);
    TkTextTagSetDecrRefCount(linePtr->tagonPtr);
    ckfree(linePtr->pixelInfo);
    DEBUG(linePtr->pixelInfo = NULL);
    ckfree(linePtr);
    DEBUG_ALLOC(tkTextCountDestroyPixelInfo++);
    DEBUG_ALLOC(tkTextCountDestroyLine++);
}

/*
 *--------------------------------------------------------------
 *
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
{
    unsigned capacity;
    TkTextSegment *newPtr;

    assert(length <= newSize);

    capacity = CSEG_CAPACITY(newSize);
    newPtr = memset(malloc(CSEG_SIZE(capacity)), 0, SEG_SIZE(0));
    newPtr->typePtr = &tkTextCharType;
    newPtr->sectionPtr = sectionPtr;
    newPtr->size = newSize;
    newPtr->refCount = 1;
    memcpy(newPtr->body.chars, string, length);
    memset(newPtr->body.chars + length, 0, capacity - length);
    if ((newPtr->tagInfoPtr = tagInfoPtr)) {







|







5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
{
    unsigned capacity;
    TkTextSegment *newPtr;

    assert(length <= newSize);

    capacity = CSEG_CAPACITY(newSize);
    newPtr = memset(ckalloc(CSEG_SIZE(capacity)), 0, SEG_SIZE(0));
    newPtr->typePtr = &tkTextCharType;
    newPtr->sectionPtr = sectionPtr;
    newPtr->size = newSize;
    newPtr->refCount = 1;
    memcpy(newPtr->body.chars, string, length);
    memset(newPtr->body.chars + length, 0, capacity - length);
    if ((newPtr->tagInfoPtr = tagInfoPtr)) {
6087
6088
6089
6090
6091
6092
6093



6094
6095
6096
6097
6098
6099
6100

static TkTextSegment *
PrepareInsertIntoCharSeg(
    TkTextSegment *segPtr,	/* Split or modify this segment. */
    unsigned offset,		/* Offset in segment. */
    SplitInfo *splitInfo)	/* Additional arguments. */
{



    assert(splitInfo);
    assert(!splitInfo->splitted);
    assert(splitInfo->increase != 0);
    assert(segPtr);
    assert(segPtr->typePtr == &tkTextCharType);
    assert(offset <= segPtr->size);
    assert(offset < segPtr->size || segPtr->body.chars[segPtr->size - 1] != '\n');







>
>
>







6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104

static TkTextSegment *
PrepareInsertIntoCharSeg(
    TkTextSegment *segPtr,	/* Split or modify this segment. */
    unsigned offset,		/* Offset in segment. */
    SplitInfo *splitInfo)	/* Additional arguments. */
{
    unsigned oldCapacity;
    unsigned newCapacity;

    assert(splitInfo);
    assert(!splitInfo->splitted);
    assert(splitInfo->increase != 0);
    assert(segPtr);
    assert(segPtr->typePtr == &tkTextCharType);
    assert(offset <= segPtr->size);
    assert(offset < segPtr->size || segPtr->body.chars[segPtr->size - 1] != '\n');
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
	segPtr->size = decreasedSize;
	newPtr->size = 0; /* temporary; LinkSegment() should not change total size */
	LinkSegment(segPtr->sectionPtr->linePtr, segPtr, newPtr);
	newPtr->size = newSize;
	SplitSection(segPtr->sectionPtr);
    }

    unsigned oldCapacity = CSEG_CAPACITY(segPtr->size);
    unsigned newCapacity = CSEG_CAPACITY(segPtr->size + splitInfo->increase);

    if (oldCapacity != newCapacity) {
	/*
	 * We replace this segment by a larger (or smaller) one.
	 */
	segPtr = IncreaseCharSegment(segPtr, offset, splitInfo->increase);
    } else {







|
|







6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
	segPtr->size = decreasedSize;
	newPtr->size = 0; /* temporary; LinkSegment() should not change total size */
	LinkSegment(segPtr->sectionPtr->linePtr, segPtr, newPtr);
	newPtr->size = newSize;
	SplitSection(segPtr->sectionPtr);
    }

    oldCapacity = CSEG_CAPACITY(segPtr->size);
    newCapacity = CSEG_CAPACITY(segPtr->size + splitInfo->increase);

    if (oldCapacity != newCapacity) {
	/*
	 * We replace this segment by a larger (or smaller) one.
	 */
	segPtr = IncreaseCharSegment(segPtr, offset, splitInfo->increase);
    } else {
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
{
    TkTextSegment *newPtr;
    unsigned memsize = CSEG_SIZE(length + 1);

    assert(string);
    assert(tagInfoPtr);

    newPtr = memset(malloc(memsize), 0, memsize);
    newPtr->typePtr = &tkTextCharType;
    newPtr->size = length;
    newPtr->refCount = 1;
    TkTextTagSetIncrRefCount(newPtr->tagInfoPtr = tagInfoPtr);
    memcpy(newPtr->body.chars, string, length);
    newPtr->body.chars[length] = '\0';
    DEBUG_ALLOC(tkTextCountNewSegment++);







|







6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
{
    TkTextSegment *newPtr;
    unsigned memsize = CSEG_SIZE(length + 1);

    assert(string);
    assert(tagInfoPtr);

    newPtr = memset(ckalloc(memsize), 0, memsize);
    newPtr->typePtr = &tkTextCharType;
    newPtr->size = length;
    newPtr->refCount = 1;
    TkTextTagSetIncrRefCount(newPtr->tagInfoPtr = tagInfoPtr);
    memcpy(newPtr->body.chars, string, length);
    newPtr->body.chars[length] = '\0';
    DEBUG_ALLOC(tkTextCountNewSegment++);
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
	SetLineHasChanged(sharedTextPtr, linePtr2);
    }

    if (undoInfo) {
	/* reserve the first entry if needed */
	numSegments = (flags & DELETE_INCLUSIVE) && TkTextIsStableMark(firstSegPtr) ? 1 : 0;
	maxSegments = 100;
	segments = malloc(maxSegments * sizeof(TkTextSegment *));
	DEBUG(segments[0] = NULL);
    } else {
	flags |= DELETE_BRANCHES;
    }

    /*
     * This line now needs to have its height recalculated. This has to be done







|







6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
	SetLineHasChanged(sharedTextPtr, linePtr2);
    }

    if (undoInfo) {
	/* reserve the first entry if needed */
	numSegments = (flags & DELETE_INCLUSIVE) && TkTextIsStableMark(firstSegPtr) ? 1 : 0;
	maxSegments = 100;
	segments = ckalloc(maxSegments * sizeof(TkTextSegment *));
	DEBUG(segments[0] = NULL);
    } else {
	flags |= DELETE_BRANCHES;
    }

    /*
     * This line now needs to have its height recalculated. This has to be done
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
	    assert(segPtr->sectionPtr->linePtr == curLinePtr);
	    assert(segPtr->typePtr->deleteProc);
	    nextPtr = segPtr->nextPtr;
	    byteSize += segPtr->size;
	    if (undoInfo && !TkTextIsSpecialOrPrivateMark(segPtr)) {
		if (numSegments == maxSegments) {
		    maxSegments = MAX(50, numSegments * 2);
		    segments = realloc(segments, maxSegments * sizeof(TkTextSegment *));
		}
		if (segPtr->tagInfoPtr) {
		    segPtr->tagInfoPtr = TagSetRemoveBits(segPtr->tagInfoPtr,
			    sharedTextPtr->dontUndoTags, sharedTextPtr);
		}
		segments[numSegments++] = segPtr;
		segPtr->refCount += 1;







|







6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
	    assert(segPtr->sectionPtr->linePtr == curLinePtr);
	    assert(segPtr->typePtr->deleteProc);
	    nextPtr = segPtr->nextPtr;
	    byteSize += segPtr->size;
	    if (undoInfo && !TkTextIsSpecialOrPrivateMark(segPtr)) {
		if (numSegments == maxSegments) {
		    maxSegments = MAX(50, numSegments * 2);
		    segments = ckrealloc(segments, maxSegments * sizeof(TkTextSegment *));
		}
		if (segPtr->tagInfoPtr) {
		    segPtr->tagInfoPtr = TagSetRemoveBits(segPtr->tagInfoPtr,
			    sharedTextPtr->dontUndoTags, sharedTextPtr);
		}
		segments[numSegments++] = segPtr;
		segPtr->refCount += 1;
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
	    UnlinkSegment(lastSegPtr);
	    assert(lastSegPtr->typePtr->deleteProc);
	    if (!lastSegPtr->typePtr->deleteProc((TkTextBTree) treePtr, lastSegPtr, flags)) {
		assert(!"mark refuses to die"); /* this should not happen */
	    } else if (segments && TkTextIsStableMark(lastSegPtr)) {
		if (numSegments == maxSegments) {
		    maxSegments += 2;
		    segments = realloc(segments, maxSegments * sizeof(TkTextSegment *));
		}
		segments[numSegments++] = lastSegPtr;
		lastSegPtr->refCount += 1;
	    }
	    countChanges += 1;
	}
	if (countChanges == 0) {







|







7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
	    UnlinkSegment(lastSegPtr);
	    assert(lastSegPtr->typePtr->deleteProc);
	    if (!lastSegPtr->typePtr->deleteProc((TkTextBTree) treePtr, lastSegPtr, flags)) {
		assert(!"mark refuses to die"); /* this should not happen */
	    } else if (segments && TkTextIsStableMark(lastSegPtr)) {
		if (numSegments == maxSegments) {
		    maxSegments += 2;
		    segments = ckrealloc(segments, maxSegments * sizeof(TkTextSegment *));
		}
		segments[numSegments++] = lastSegPtr;
		lastSegPtr->refCount += 1;
	    }
	    countChanges += 1;
	}
	if (countChanges == 0) {
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093

    if (undoInfo) {
	UndoTokenDelete *undoToken = (UndoTokenDelete *) undoInfo->token;

	assert(numSegments == 0 || segments[0]);

	if (numSegments + 1 != maxSegments) {
	    segments = realloc(segments, (numSegments + 1)*sizeof(TkTextSegment *));
	}
	undoToken->segments = segments;
	undoToken->numSegments = numSegments;
	undoToken->inclusive = !!(flags & DELETE_INCLUSIVE);
	undoInfo->byteSize = byteSize;
    }








|







7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097

    if (undoInfo) {
	UndoTokenDelete *undoToken = (UndoTokenDelete *) undoInfo->token;

	assert(numSegments == 0 || segments[0]);

	if (numSegments + 1 != maxSegments) {
	    segments = ckrealloc(segments, (numSegments + 1)*sizeof(TkTextSegment *));
	}
	undoToken->segments = segments;
	undoToken->numSegments = numSegments;
	undoToken->inclusive = !!(flags & DELETE_INCLUSIVE);
	undoInfo->byteSize = byteSize;
    }

7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
    }

    TkBTreeIncrEpoch(sharedTextPtr->tree);

    if (redoInfo) {
	UndoTokenDelete *redoToken;

	redoToken = malloc(sizeof(UndoTokenDelete));
	redoToken->undoType = &undoTokenDeleteType;
	redoToken->segments = NULL;
	redoToken->numSegments = 0;
	if (undoToken) {
	    redoToken->startIndex = undoToken->startIndex;
	    redoToken->endIndex = undoToken->endIndex;
	} else {







|







7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
    }

    TkBTreeIncrEpoch(sharedTextPtr->tree);

    if (redoInfo) {
	UndoTokenDelete *redoToken;

	redoToken = ckalloc(sizeof(UndoTokenDelete));
	redoToken->undoType = &undoTokenDeleteType;
	redoToken->segments = NULL;
	redoToken->numSegments = 0;
	if (undoToken) {
	    redoToken->startIndex = undoToken->startIndex;
	    redoToken->endIndex = undoToken->endIndex;
	} else {
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650

static void
SaveLength(
    TreeTagData *data)
{
    if (++data->sizeOfLengths == data->capacityOfLengths) {
	unsigned newCapacity = 2*data->capacityOfLengths;
	data->lengths = realloc(data->lengths == data->lengthsBuf ? NULL : data->lengths, newCapacity);
	data->capacityOfLengths = newCapacity;
    }

    data->lengths[data->sizeOfLengths - 1] = data->currLength;
    data->currLength = 0;
}








|







8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654

static void
SaveLength(
    TreeTagData *data)
{
    if (++data->sizeOfLengths == data->capacityOfLengths) {
	unsigned newCapacity = 2*data->capacityOfLengths;
	data->lengths = ckrealloc(data->lengths == data->lengthsBuf ? NULL : data->lengths, newCapacity);
	data->capacityOfLengths = newCapacity;
    }

    data->lengths[data->sizeOfLengths - 1] = data->currLength;
    data->currLength = 0;
}

8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
    cmp2 = CompareIndices(indexPtr2, &prevToken->endIndex);
    wholeRange = data->sizeOfLengths == 0
	    && !((UndoTokenTagChange *) tagPtr->recentTagAddRemoveToken)->lengths;

    if (data->add == remove) {
	if (cmp1 <= 0 && cmp2 >= 0) {
	    if (!data->add || wholeRange) {
		free(prevToken->lengths);
		prevToken->lengths = NULL;
		return UNDO_ANNIHILATED;
	    }
	    return UNDO_NEEDED;
	}
	if (!wholeRange) {
	    return UNDO_NEEDED;







|







8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
    cmp2 = CompareIndices(indexPtr2, &prevToken->endIndex);
    wholeRange = data->sizeOfLengths == 0
	    && !((UndoTokenTagChange *) tagPtr->recentTagAddRemoveToken)->lengths;

    if (data->add == remove) {
	if (cmp1 <= 0 && cmp2 >= 0) {
	    if (!data->add || wholeRange) {
		ckfree(prevToken->lengths);
		prevToken->lengths = NULL;
		return UNDO_ANNIHILATED;
	    }
	    return UNDO_NEEDED;
	}
	if (!wholeRange) {
	    return UNDO_NEEDED;
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448

	    if (tagPtr->recentTagAddRemoveToken && !tagPtr->recentTagAddRemoveTokenIsNull) {
		undoInfo->token = (TkTextUndoToken *) tagPtr->recentTagAddRemoveToken;
		undoInfo->byteSize = 0;
		tagPtr->recentTagAddRemoveToken = NULL;
	    }
	    if (!tagPtr->recentTagAddRemoveToken) {
		tagPtr->recentTagAddRemoveToken = malloc(sizeof(UndoTokenTagChange));
		DEBUG_ALLOC(tkTextCountNewUndoToken++);
	    }

	    tagPtr->recentTagAddRemoveTokenIsNull = false;
	    undoToken = (UndoTokenTagChange *) tagPtr->recentTagAddRemoveToken;
	    undoToken->undoType = &undoTokenTagType;
	    undoToken->tagPtr = tagPtr;
	    if (!add) {
		MARK_POINTER(undoToken->tagPtr);
	    }
	    MakeUndoIndex(sharedTextPtr, &index1, &undoToken->startIndex, GRAVITY_LEFT);
	    MakeUndoIndex(sharedTextPtr, &index2, &undoToken->endIndex, GRAVITY_RIGHT);
	    if (data.sizeOfLengths > 0) {
		if (data.lengths == data.lengthsBuf) {
		    data.lengths = malloc(data.sizeOfLengths * sizeof(data.lengths[0]));
		    memcpy(data.lengths, data.lengthsBuf, data.sizeOfLengths * sizeof(data.lengths[0]));
		} else {
		    data.lengths = realloc(data.lengths, data.sizeOfLengths * sizeof(data.lengths[0]));
		}
		undoToken->lengths = data.lengths;
		data.lengths = data.lengthsBuf;
	    } else {
		undoToken->lengths = NULL;
	    }
	    TkTextTagAddRetainedUndo(sharedTextPtr, tagPtr);
	    break;
	}
	case UNDO_MERGED:
	    /* no action required */
	    break;
	case UNDO_ANNIHILATED:
	    tagPtr->recentTagAddRemoveTokenIsNull = true;
	    break;
	}

	if (data.lengths != data.lengthsBuf) {
	    free(data.lengths);
	}
    }

    assert(data.lengths == data.lengthsBuf);

    CleanupSplitPoint(segPtr1, sharedTextPtr);
    CleanupSplitPoint(segPtr2, sharedTextPtr);







|














|


|


















|







9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452

	    if (tagPtr->recentTagAddRemoveToken && !tagPtr->recentTagAddRemoveTokenIsNull) {
		undoInfo->token = (TkTextUndoToken *) tagPtr->recentTagAddRemoveToken;
		undoInfo->byteSize = 0;
		tagPtr->recentTagAddRemoveToken = NULL;
	    }
	    if (!tagPtr->recentTagAddRemoveToken) {
		tagPtr->recentTagAddRemoveToken = ckalloc(sizeof(UndoTokenTagChange));
		DEBUG_ALLOC(tkTextCountNewUndoToken++);
	    }

	    tagPtr->recentTagAddRemoveTokenIsNull = false;
	    undoToken = (UndoTokenTagChange *) tagPtr->recentTagAddRemoveToken;
	    undoToken->undoType = &undoTokenTagType;
	    undoToken->tagPtr = tagPtr;
	    if (!add) {
		MARK_POINTER(undoToken->tagPtr);
	    }
	    MakeUndoIndex(sharedTextPtr, &index1, &undoToken->startIndex, GRAVITY_LEFT);
	    MakeUndoIndex(sharedTextPtr, &index2, &undoToken->endIndex, GRAVITY_RIGHT);
	    if (data.sizeOfLengths > 0) {
		if (data.lengths == data.lengthsBuf) {
		    data.lengths = ckalloc(data.sizeOfLengths * sizeof(data.lengths[0]));
		    memcpy(data.lengths, data.lengthsBuf, data.sizeOfLengths * sizeof(data.lengths[0]));
		} else {
		    data.lengths = ckrealloc(data.lengths, data.sizeOfLengths * sizeof(data.lengths[0]));
		}
		undoToken->lengths = data.lengths;
		data.lengths = data.lengthsBuf;
	    } else {
		undoToken->lengths = NULL;
	    }
	    TkTextTagAddRetainedUndo(sharedTextPtr, tagPtr);
	    break;
	}
	case UNDO_MERGED:
	    /* no action required */
	    break;
	case UNDO_ANNIHILATED:
	    tagPtr->recentTagAddRemoveTokenIsNull = true;
	    break;
	}

	if (data.lengths != data.lengthsBuf) {
	    ckfree(data.lengths);
	}
    }

    assert(data.lengths == data.lengthsBuf);

    CleanupSplitPoint(segPtr1, sharedTextPtr);
    CleanupSplitPoint(segPtr2, sharedTextPtr);
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
				&& data->tagChangePtr
				&& TkTextTagSetIsEqual(data->tagChangePtr->tagInfoPtr, tagInfoPtr)) {
			    data->tagChangePtr->size += segPtr->size;
			    TkTextTagSetDecrRefCount(tagInfoPtr);
			} else {
			    if (undoToken->changeListSize == data->capacity) {
				data->capacity = MAX(2*data->capacity, 50);
				undoToken->changeList = realloc(undoToken->changeList,
					data->capacity * sizeof(undoToken->changeList[0]));
			    }
			    tagChangePtr = undoToken->changeList + undoToken->changeListSize++;
			    tagChangePtr->tagInfoPtr = tagInfoPtr;
			    tagChangePtr->size = segPtr->size;
			    tagChangePtr->skip = data->skip;
			    data->tagChangePtr = tagChangePtr;







|







9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
				&& data->tagChangePtr
				&& TkTextTagSetIsEqual(data->tagChangePtr->tagInfoPtr, tagInfoPtr)) {
			    data->tagChangePtr->size += segPtr->size;
			    TkTextTagSetDecrRefCount(tagInfoPtr);
			} else {
			    if (undoToken->changeListSize == data->capacity) {
				data->capacity = MAX(2*data->capacity, 50);
				undoToken->changeList = ckrealloc(undoToken->changeList,
					data->capacity * sizeof(undoToken->changeList[0]));
			    }
			    tagChangePtr = undoToken->changeList + undoToken->changeListSize++;
			    tagChangePtr->tagInfoPtr = tagInfoPtr;
			    tagChangePtr->size = segPtr->size;
			    tagChangePtr->skip = data->skip;
			    data->tagChangePtr = tagChangePtr;
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
			NULL, affectsDisplayGeometry);
	    }
	} else {
	    TkTextSegment *firstPtr, *lastPtr;
	    int lineNo1, lineNo2;

	    if (undoInfo) {
		undoToken = malloc(sizeof(UndoTokenTagClear));
		undoInfo->token = (TkTextUndoToken *) undoToken;
		undoInfo->byteSize = 0;
		undoToken->undoType = &undoTokenClearTagsType;
		undoToken->changeList = NULL;
		undoToken->changeListSize = 0;
		DEBUG_ALLOC(tkTextCountNewUndoToken++);
	    }







|







10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
			NULL, affectsDisplayGeometry);
	    }
	} else {
	    TkTextSegment *firstPtr, *lastPtr;
	    int lineNo1, lineNo2;

	    if (undoInfo) {
		undoToken = ckalloc(sizeof(UndoTokenTagClear));
		undoInfo->token = (TkTextUndoToken *) undoToken;
		undoInfo->byteSize = 0;
		undoToken->undoType = &undoTokenClearTagsType;
		undoToken->changeList = NULL;
		undoToken->changeListSize = 0;
		DEBUG_ALLOC(tkTextCountNewUndoToken++);
	    }
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
	    TkTextTagSetDecrRefCount(affectedTagInfoPtr);
	    TkBTreeIncrEpoch(sharedTextPtr->tree);
	}
    }

    if (undoToken) {
	if (undoToken->changeListSize == 0) {
	    free(undoToken->changeList);
	    free(undoToken);
	    undoInfo->token = NULL;
	    DEBUG_ALLOC(tkTextCountNewUndoToken--);
	} else {
	    undoToken->changeList = realloc(undoToken->changeList,
		    undoToken->changeListSize * sizeof(undoToken->changeList[0]));
	}
    }

    CleanupSplitPoint(segPtr1, sharedTextPtr);
    CleanupSplitPoint(segPtr2, sharedTextPtr);








|
|



|







10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
	    TkTextTagSetDecrRefCount(affectedTagInfoPtr);
	    TkBTreeIncrEpoch(sharedTextPtr->tree);
	}
    }

    if (undoToken) {
	if (undoToken->changeListSize == 0) {
	    ckfree(undoToken->changeList);
	    ckfree(undoToken);
	    undoInfo->token = NULL;
	    DEBUG_ALLOC(tkTextCountNewUndoToken--);
	} else {
	    undoToken->changeList = ckrealloc(undoToken->changeList,
		    undoToken->changeListSize * sizeof(undoToken->changeList[0]));
	}
    }

    CleanupSplitPoint(segPtr1, sharedTextPtr);
    CleanupSplitPoint(segPtr2, sharedTextPtr);

12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
    if (!TkTextTagSetContains(rootPtr->tagoffPtr, nodePtr->tagoffPtr)) {
	Tcl_Panic("CheckNodeConsistency: tagoff not propagated to root");
    }

    numChildren = numLines = numLogicalLines = numBranches = size = 0;

    memsize = sizeof(pixelInfo[0])*references;
    pixelInfo = (references > PIXEL_CLIENTS) ? (NodePixelInfo *) malloc(memsize) : pixelInfoBuf;
    memset(pixelInfo, 0, memsize);

    TkTextTagSetIncrRefCount(tagonPtr = sharedTextPtr->emptyTagInfoPtr);
    TkTextTagSetIncrRefCount(tagoffPtr = sharedTextPtr->emptyTagInfoPtr);
    additionalTagoffPtr = NULL;

    if (nodePtr->level == 0) {







|







12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
    if (!TkTextTagSetContains(rootPtr->tagoffPtr, nodePtr->tagoffPtr)) {
	Tcl_Panic("CheckNodeConsistency: tagoff not propagated to root");
    }

    numChildren = numLines = numLogicalLines = numBranches = size = 0;

    memsize = sizeof(pixelInfo[0])*references;
    pixelInfo = (references > PIXEL_CLIENTS) ? (NodePixelInfo *) ckalloc(memsize) : pixelInfoBuf;
    memset(pixelInfo, 0, memsize);

    TkTextTagSetIncrRefCount(tagonPtr = sharedTextPtr->emptyTagInfoPtr);
    TkTextTagSetIncrRefCount(tagoffPtr = sharedTextPtr->emptyTagInfoPtr);
    additionalTagoffPtr = NULL;

    if (nodePtr->level == 0) {
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
	    Tcl_Panic("CheckNodeConsistency: mismatch in number of display lines "
		    "(expected: %d, counted: %d) for widget (%d) at level %d",
		    pixelInfo[i].numDispLines, nodePtr->pixelInfo[i].numDispLines,
		    i, nodePtr->level);
	}
    }
    if (pixelInfo != pixelInfoBuf) {
	free(pixelInfo);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * DeleteEmptyNode --







|







12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
	    Tcl_Panic("CheckNodeConsistency: mismatch in number of display lines "
		    "(expected: %d, counted: %d) for widget (%d) at level %d",
		    pixelInfo[i].numDispLines, nodePtr->pixelInfo[i].numDispLines,
		    i, nodePtr->level);
	}
    }
    if (pixelInfo != pixelInfoBuf) {
	ckfree(pixelInfo);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * DeleteEmptyNode --
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
		Node *newPtr;

		/*
		 * If the node being split is the root node, then make a new root node above it first.
		 */

		if (!nodePtr->parentPtr) {
		    Node *newRootPtr = malloc(sizeof(Node));
		    newRootPtr->parentPtr = NULL;
		    newRootPtr->nextPtr = NULL;
		    newRootPtr->childPtr = nodePtr;
		    newRootPtr->linePtr = nodePtr->linePtr;
		    newRootPtr->lastPtr = nodePtr->lastPtr;
		    TkTextTagSetIncrRefCount(newRootPtr->tagonPtr = nodePtr->tagonPtr);
		    TkTextTagSetIncrRefCount(newRootPtr->tagoffPtr = nodePtr->tagoffPtr);
		    newRootPtr->numChildren = 1;
		    newRootPtr->numLines = nodePtr->numLines;
		    newRootPtr->numLogicalLines = nodePtr->numLogicalLines;
		    newRootPtr->numBranches = nodePtr->numBranches;
		    newRootPtr->level = nodePtr->level + 1;
		    newRootPtr->size = nodePtr->size;
		    newRootPtr->pixelInfo = memcpy(malloc(pixelSize), nodePtr->pixelInfo, pixelSize);
		    nodePtr->parentPtr = newRootPtr;
		    treePtr->rootPtr = newRootPtr;
		    DEBUG_ALLOC(tkTextCountNewNode++);
		    DEBUG_ALLOC(tkTextCountNewPixelInfo++);
		}

		newPtr = malloc(sizeof(Node));
		newPtr->parentPtr = nodePtr->parentPtr;
		newPtr->nextPtr = nodePtr->nextPtr;
		newPtr->lastPtr = nodePtr->lastPtr;
		newPtr->tagonPtr = treePtr->sharedTextPtr->emptyTagInfoPtr;
		newPtr->tagoffPtr = treePtr->sharedTextPtr->emptyTagInfoPtr;
		TkTextTagSetIncrRefCount(newPtr->tagonPtr);
		TkTextTagSetIncrRefCount(newPtr->tagoffPtr);
		newPtr->numChildren = nodePtr->numChildren - MIN_CHILDREN;
		newPtr->level = nodePtr->level;
		newPtr->size = nodePtr->size;
		newPtr->pixelInfo = nodePtr->pixelInfo;
		newPtr->numLines = nodePtr->numLines;
		newPtr->numLogicalLines = nodePtr->numLogicalLines;
		newPtr->numBranches = nodePtr->numBranches;
		nodePtr->nextPtr = newPtr;
		nodePtr->numChildren = MIN_CHILDREN;
		nodePtr->pixelInfo = memset(malloc(pixelSize), 0, pixelSize);
		TagSetAssign(&nodePtr->tagonPtr, treePtr->sharedTextPtr->emptyTagInfoPtr);
		TagSetAssign(&nodePtr->tagoffPtr, treePtr->sharedTextPtr->emptyTagInfoPtr);
		DEBUG_ALLOC(tkTextCountNewNode++);
		DEBUG_ALLOC(tkTextCountNewPixelInfo++);
		if (nodePtr->level == 0) {
		    TkTextLine *linePtr = RebalanceDivideLines(nodePtr, MIN_CHILDREN, numRefs);
		    assert(linePtr->nextPtr);







|













|






|
















|







13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
		Node *newPtr;

		/*
		 * If the node being split is the root node, then make a new root node above it first.
		 */

		if (!nodePtr->parentPtr) {
		    Node *newRootPtr = ckalloc(sizeof(Node));
		    newRootPtr->parentPtr = NULL;
		    newRootPtr->nextPtr = NULL;
		    newRootPtr->childPtr = nodePtr;
		    newRootPtr->linePtr = nodePtr->linePtr;
		    newRootPtr->lastPtr = nodePtr->lastPtr;
		    TkTextTagSetIncrRefCount(newRootPtr->tagonPtr = nodePtr->tagonPtr);
		    TkTextTagSetIncrRefCount(newRootPtr->tagoffPtr = nodePtr->tagoffPtr);
		    newRootPtr->numChildren = 1;
		    newRootPtr->numLines = nodePtr->numLines;
		    newRootPtr->numLogicalLines = nodePtr->numLogicalLines;
		    newRootPtr->numBranches = nodePtr->numBranches;
		    newRootPtr->level = nodePtr->level + 1;
		    newRootPtr->size = nodePtr->size;
		    newRootPtr->pixelInfo = memcpy(ckalloc(pixelSize), nodePtr->pixelInfo, pixelSize);
		    nodePtr->parentPtr = newRootPtr;
		    treePtr->rootPtr = newRootPtr;
		    DEBUG_ALLOC(tkTextCountNewNode++);
		    DEBUG_ALLOC(tkTextCountNewPixelInfo++);
		}

		newPtr = ckalloc(sizeof(Node));
		newPtr->parentPtr = nodePtr->parentPtr;
		newPtr->nextPtr = nodePtr->nextPtr;
		newPtr->lastPtr = nodePtr->lastPtr;
		newPtr->tagonPtr = treePtr->sharedTextPtr->emptyTagInfoPtr;
		newPtr->tagoffPtr = treePtr->sharedTextPtr->emptyTagInfoPtr;
		TkTextTagSetIncrRefCount(newPtr->tagonPtr);
		TkTextTagSetIncrRefCount(newPtr->tagoffPtr);
		newPtr->numChildren = nodePtr->numChildren - MIN_CHILDREN;
		newPtr->level = nodePtr->level;
		newPtr->size = nodePtr->size;
		newPtr->pixelInfo = nodePtr->pixelInfo;
		newPtr->numLines = nodePtr->numLines;
		newPtr->numLogicalLines = nodePtr->numLogicalLines;
		newPtr->numBranches = nodePtr->numBranches;
		nodePtr->nextPtr = newPtr;
		nodePtr->numChildren = MIN_CHILDREN;
		nodePtr->pixelInfo = memset(ckalloc(pixelSize), 0, pixelSize);
		TagSetAssign(&nodePtr->tagonPtr, treePtr->sharedTextPtr->emptyTagInfoPtr);
		TagSetAssign(&nodePtr->tagoffPtr, treePtr->sharedTextPtr->emptyTagInfoPtr);
		DEBUG_ALLOC(tkTextCountNewNode++);
		DEBUG_ALLOC(tkTextCountNewPixelInfo++);
		if (nodePtr->level == 0) {
		    TkTextLine *linePtr = RebalanceDivideLines(nodePtr, MIN_CHILDREN, numRefs);
		    assert(linePtr->nextPtr);

Changes to generic/tkTextDisp.c.

1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
{
    TkSharedText *sharedTextPtr = textPtr->sharedTextPtr;
    TkTextBTree tree = sharedTextPtr->tree;
    TextDInfo *dInfoPtr;
    XGCValues gcValues;
    bool isMonospaced;

    dInfoPtr = memset(malloc(sizeof(TextDInfo)), 0, sizeof(TextDInfo));
    Tcl_InitHashTable(&dInfoPtr->styleTable, sizeof(StyleValues)/sizeof(int));
    dInfoPtr->copyGC = None;
    gcValues.graphics_exposures = True;
    dInfoPtr->scrollGC = Tk_GetGC(textPtr->tkwin, GCGraphicsExposures, &gcValues);
    dInfoPtr->insertFgGC = None;
    dInfoPtr->xScrollFirst = -1;
    dInfoPtr->xScrollLast = -1;
    dInfoPtr->yScrollFirst = -1;
    dInfoPtr->yScrollLast = -1;
    dInfoPtr->topLineNo = -1;
    dInfoPtr->topByteIndex = -1;
    dInfoPtr->flags = DINFO_OUT_OF_DATE;
    dInfoPtr->lineMetricUpdateRanges = TkRangeListCreate(64);
    dInfoPtr->firstLineNo = TkBTreeLinesTo(tree, NULL, TkBTreeGetStartLine(textPtr), NULL);
    dInfoPtr->lastLineNo = TkBTreeLinesTo(tree, NULL, TkBTreeGetLastLine(textPtr), NULL);
    dInfoPtr->lineMetricUpdateEpoch = 1;
    dInfoPtr->strBufferSize = 512;
    dInfoPtr->strBuffer = malloc(dInfoPtr->strBufferSize);
    TkTextIndexClear(&dInfoPtr->metricIndex, textPtr);
    TkTextIndexClear(&dInfoPtr->currChunkIndex, textPtr);
    SetupEolSegment(textPtr, dInfoPtr);

    if (textPtr->state == TK_TEXT_STATE_NORMAL
	    && textPtr->blockCursorType
	    && textPtr->showInsertFgColor) {







|

















|







1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
{
    TkSharedText *sharedTextPtr = textPtr->sharedTextPtr;
    TkTextBTree tree = sharedTextPtr->tree;
    TextDInfo *dInfoPtr;
    XGCValues gcValues;
    bool isMonospaced;

    dInfoPtr = memset(ckalloc(sizeof(TextDInfo)), 0, sizeof(TextDInfo));
    Tcl_InitHashTable(&dInfoPtr->styleTable, sizeof(StyleValues)/sizeof(int));
    dInfoPtr->copyGC = None;
    gcValues.graphics_exposures = True;
    dInfoPtr->scrollGC = Tk_GetGC(textPtr->tkwin, GCGraphicsExposures, &gcValues);
    dInfoPtr->insertFgGC = None;
    dInfoPtr->xScrollFirst = -1;
    dInfoPtr->xScrollLast = -1;
    dInfoPtr->yScrollFirst = -1;
    dInfoPtr->yScrollLast = -1;
    dInfoPtr->topLineNo = -1;
    dInfoPtr->topByteIndex = -1;
    dInfoPtr->flags = DINFO_OUT_OF_DATE;
    dInfoPtr->lineMetricUpdateRanges = TkRangeListCreate(64);
    dInfoPtr->firstLineNo = TkBTreeLinesTo(tree, NULL, TkBTreeGetStartLine(textPtr), NULL);
    dInfoPtr->lastLineNo = TkBTreeLinesTo(tree, NULL, TkBTreeGetLastLine(textPtr), NULL);
    dInfoPtr->lineMetricUpdateEpoch = 1;
    dInfoPtr->strBufferSize = 512;
    dInfoPtr->strBuffer = ckalloc(dInfoPtr->strBufferSize);
    TkTextIndexClear(&dInfoPtr->metricIndex, textPtr);
    TkTextIndexClear(&dInfoPtr->currChunkIndex, textPtr);
    SetupEolSegment(textPtr, dInfoPtr);

    if (textPtr->state == TK_TEXT_STATE_NORMAL
	    && textPtr->blockCursorType
	    && textPtr->showInsertFgColor) {
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604

    assert(breakInfoTable);

    for (hPtr = Tcl_FirstHashEntry(breakInfoTable, &search); hPtr; hPtr = Tcl_NextHashEntry(&search)) {
	BreakInfo *breakInfo = Tcl_GetHashValue(hPtr);

	assert(breakInfo->brks);
	free(breakInfo->brks);
	free(breakInfo);
	DEBUG_ALLOC(tkTextCountDestroyBreakInfo++);
    }
}

/*
 *----------------------------------------------------------------------
 *







|
|







1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604

    assert(breakInfoTable);

    for (hPtr = Tcl_FirstHashEntry(breakInfoTable, &search); hPtr; hPtr = Tcl_NextHashEntry(&search)) {
	BreakInfo *breakInfo = Tcl_GetHashValue(hPtr);

	assert(breakInfo->brks);
	ckfree(breakInfo->brks);
	ckfree(breakInfo);
	DEBUG_ALLOC(tkTextCountDestroyBreakInfo++);
    }
}

/*
 *----------------------------------------------------------------------
 *
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
	Tcl_DeleteTimerHandler(dInfoPtr->repickTimer);
	textPtr->refCount -= 1;
	dInfoPtr->repickTimer = NULL;
    }
    ciPtr = dInfoPtr->charInfoPoolPtr;
    while (ciPtr) {
	CharInfo *nextPtr = ciPtr->u.next;
	free(ciPtr);
	DEBUG_ALLOC(tkTextCountDestroyCharInfo++);
	ciPtr = nextPtr;
    }
    sectionPtr = dInfoPtr->sectionPoolPtr;
    while (sectionPtr) {
	TkTextDispChunkSection *nextPtr = sectionPtr->nextPtr;
	free(sectionPtr);
	DEBUG_ALLOC(tkTextCountDestroySection++);
	sectionPtr = nextPtr;
    }
    chunkPtr = dInfoPtr->chunkPoolPtr;
    while (chunkPtr) {
	TkTextDispChunk *nextPtr = chunkPtr->nextPtr;
	free(chunkPtr);
	DEBUG_ALLOC(tkTextCountDestroyChunk++);
	chunkPtr = nextPtr;
    }
    dlPtr = dInfoPtr->dLinePoolPtr;
    while (dlPtr) {
	DLine *nextPtr = dlPtr->nextPtr;
	free(dlPtr);
	DEBUG_ALLOC(tkTextCountDestroyDLine++);
	dlPtr = nextPtr;
    }
    if (dInfoPtr->defaultStyle) {
#if 0
	/*
	 * TODO: The following assertion sometimes fails. Luckily it doesn't matter,
	 * because it will be freed anyway, but why can it fail (and only sometimes)?
	 */
	 DEBUG_ALLOC(assert(dInfoPtr->defaultStyle->refCount == 1));
#endif
	FreeStyle(textPtr, dInfoPtr->defaultStyle);
    }
    Tcl_DeleteHashTable(&dInfoPtr->styleTable);
    TkRangeListDestroy(&dInfoPtr->lineMetricUpdateRanges);
    TkBTreeFreeSegment(dInfoPtr->endOfLineSegPtr);
    free(dInfoPtr->strBuffer);
    free(dInfoPtr);
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextResetDInfo --
 *







|






|






|






|
















|
|







1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
	Tcl_DeleteTimerHandler(dInfoPtr->repickTimer);
	textPtr->refCount -= 1;
	dInfoPtr->repickTimer = NULL;
    }
    ciPtr = dInfoPtr->charInfoPoolPtr;
    while (ciPtr) {
	CharInfo *nextPtr = ciPtr->u.next;
	ckfree(ciPtr);
	DEBUG_ALLOC(tkTextCountDestroyCharInfo++);
	ciPtr = nextPtr;
    }
    sectionPtr = dInfoPtr->sectionPoolPtr;
    while (sectionPtr) {
	TkTextDispChunkSection *nextPtr = sectionPtr->nextPtr;
	ckfree(sectionPtr);
	DEBUG_ALLOC(tkTextCountDestroySection++);
	sectionPtr = nextPtr;
    }
    chunkPtr = dInfoPtr->chunkPoolPtr;
    while (chunkPtr) {
	TkTextDispChunk *nextPtr = chunkPtr->nextPtr;
	ckfree(chunkPtr);
	DEBUG_ALLOC(tkTextCountDestroyChunk++);
	chunkPtr = nextPtr;
    }
    dlPtr = dInfoPtr->dLinePoolPtr;
    while (dlPtr) {
	DLine *nextPtr = dlPtr->nextPtr;
	ckfree(dlPtr);
	DEBUG_ALLOC(tkTextCountDestroyDLine++);
	dlPtr = nextPtr;
    }
    if (dInfoPtr->defaultStyle) {
#if 0
	/*
	 * TODO: The following assertion sometimes fails. Luckily it doesn't matter,
	 * because it will be freed anyway, but why can it fail (and only sometimes)?
	 */
	 DEBUG_ALLOC(assert(dInfoPtr->defaultStyle->refCount == 1));
#endif
	FreeStyle(textPtr, dInfoPtr->defaultStyle);
    }
    Tcl_DeleteHashTable(&dInfoPtr->styleTable);
    TkRangeListDestroy(&dInfoPtr->lineMetricUpdateRanges);
    TkBTreeFreeSegment(dInfoPtr->endOfLineSegPtr);
    ckfree(dInfoPtr->strBuffer);
    ckfree(dInfoPtr);
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextResetDInfo --
 *
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
	return Tcl_GetHashValue(hPtr);
    }

    /*
     * No existing style matched. Make a new one.
     */

    stylePtr = malloc(sizeof(TextStyle));
    stylePtr->refCount = 0;
    if (styleValues.border) {
	gcValues.foreground = Tk_3DBorderColor(styleValues.border)->pixel;
	mask = GCForeground;
	if (styleValues.bgStipple != None) {
	    gcValues.stipple = styleValues.bgStipple;
	    gcValues.fill_style = FillStippled;







|







2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
	return Tcl_GetHashValue(hPtr);
    }

    /*
     * No existing style matched. Make a new one.
     */

    stylePtr = ckalloc(sizeof(TextStyle));
    stylePtr->refCount = 0;
    if (styleValues.border) {
	gcValues.foreground = Tk_3DBorderColor(styleValues.border)->pixel;
	mask = GCForeground;
	if (styleValues.bgStipple != None) {
	    gcValues.stipple = styleValues.bgStipple;
	    gcValues.fill_style = FillStippled;
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
	if (stylePtr->eolGC != None) {
	    Tk_FreeGC(textPtr->display, stylePtr->eolGC);
	}
	if (stylePtr->hyphenGC != None) {
	    Tk_FreeGC(textPtr->display, stylePtr->hyphenGC);
	}
	Tcl_DeleteHashEntry(stylePtr->hPtr);
	free(stylePtr);
	DEBUG_ALLOC(tkTextCountDestroyStyle++);
    }
}

/*
 *----------------------------------------------------------------------
 *







|







2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
	if (stylePtr->eolGC != None) {
	    Tk_FreeGC(textPtr->display, stylePtr->eolGC);
	}
	if (stylePtr->hyphenGC != None) {
	    Tk_FreeGC(textPtr->display, stylePtr->hyphenGC);
	}
	Tcl_DeleteHashEntry(stylePtr->hPtr);
	ckfree(stylePtr);
	DEBUG_ALLOC(tkTextCountDestroyStyle++);
    }
}

/*
 *----------------------------------------------------------------------
 *
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
LayoutSetupDispLineInfo(
    TkTextPixelInfo *pixelInfo)
{
    TkTextDispLineInfo *dispLineInfo = pixelInfo->dispLineInfo;
    unsigned oldNumDispLines = TkBTreeGetNumberOfDisplayLines(pixelInfo);

    if (!dispLineInfo) {
	dispLineInfo = malloc(TEXT_DISPLINEINFO_SIZE(2));
	DEBUG(memset(dispLineInfo, 0xff, TEXT_DISPLINEINFO_SIZE(2)));
	DEBUG_ALLOC(tkTextCountNewDispInfo++);
	pixelInfo->dispLineInfo = dispLineInfo;
    }

    dispLineInfo->numDispLines = 1;
    /* remember old display line count, see TkBTreeGetNumberOfDisplayLines */







|







2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
LayoutSetupDispLineInfo(
    TkTextPixelInfo *pixelInfo)
{
    TkTextDispLineInfo *dispLineInfo = pixelInfo->dispLineInfo;
    unsigned oldNumDispLines = TkBTreeGetNumberOfDisplayLines(pixelInfo);

    if (!dispLineInfo) {
	dispLineInfo = ckalloc(TEXT_DISPLINEINFO_SIZE(2));
	DEBUG(memset(dispLineInfo, 0xff, TEXT_DISPLINEINFO_SIZE(2)));
	DEBUG_ALLOC(tkTextCountNewDispInfo++);
	pixelInfo->dispLineInfo = dispLineInfo;
    }

    dispLineInfo->numDispLines = 1;
    /* remember old display line count, see TkBTreeGetNumberOfDisplayLines */
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398

	assert(dispLineInfo);
	assert(data->byteOffset == dispLineInfo->entry[dlPtr->displayLineNo].byteOffset);

	if (dlPtr->displayLineNo >= dispLineInfo->numDispLines
		&& !IsPowerOf2(dlPtr->displayLineNo + 2)) {
	    unsigned size = NextPowerOf2(dlPtr->displayLineNo + 2);
	    dispLineInfo = realloc(dispLineInfo, TEXT_DISPLINEINFO_SIZE(size));
	    DEBUG(memset(dispLineInfo->entry + dlPtr->displayLineNo + 1, 0xff,
		    (size - dlPtr->displayLineNo - 1)*sizeof(dispLineInfo->entry[0])));
	    pixelInfo->dispLineInfo = dispLineInfo;
	}
	dispLineInfo->numDispLines = dlPtr->displayLineNo + 1;
	dispLineEntry = dispLineInfo->entry + dlPtr->displayLineNo;
	(dispLineEntry + 1)->byteOffset = data->byteOffset + dlPtr->byteCount;







|







2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398

	assert(dispLineInfo);
	assert(data->byteOffset == dispLineInfo->entry[dlPtr->displayLineNo].byteOffset);

	if (dlPtr->displayLineNo >= dispLineInfo->numDispLines
		&& !IsPowerOf2(dlPtr->displayLineNo + 2)) {
	    unsigned size = NextPowerOf2(dlPtr->displayLineNo + 2);
	    dispLineInfo = ckrealloc(dispLineInfo, TEXT_DISPLINEINFO_SIZE(size));
	    DEBUG(memset(dispLineInfo->entry + dlPtr->displayLineNo + 1, 0xff,
		    (size - dlPtr->displayLineNo - 1)*sizeof(dispLineInfo->entry[0])));
	    pixelInfo->dispLineInfo = dispLineInfo;
	}
	dispLineInfo->numDispLines = dlPtr->displayLineNo + 1;
	dispLineEntry = dispLineInfo->entry + dlPtr->displayLineNo;
	(dispLineEntry + 1)->byteOffset = data->byteOffset + dlPtr->byteCount;
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
	}
	if (dispLineInfo && dlPtr->displayLineNo == 0) {
	    /*
	     * This is the right place to destroy the superfluous dispLineInfo. Don't do
	     * this before TkBTreeAdjustPixelHeight has been called, because the latter
	     * function needs the old display line count.
	     */
	    free(dispLineInfo);
	    DEBUG_ALLOC(tkTextCountDestroyDispInfo++);
	    pixelInfo->dispLineInfo = NULL;
	}
	textPtr->dInfoPtr->lineMetricUpdateCounter += 1;
	pixelInfo->epoch = epoch;
	lineNo = TkBTreeLinesTo(textPtr->sharedTextPtr->tree, textPtr, linePtr, NULL);
	for (i = 0; i < mergedLines; ++i) {
	    pixelInfo = TkBTreeLinePixelInfo(textPtr, linePtr = linePtr->nextPtr);
	    pixelInfo->epoch = epoch;
	    if (pixelInfo->dispLineInfo) {
		free(pixelInfo->dispLineInfo);
		DEBUG_ALLOC(tkTextCountDestroyDispInfo++);
		pixelInfo->dispLineInfo = NULL;
	    }
	}
	TkRangeListRemove(textPtr->dInfoPtr->lineMetricUpdateRanges, lineNo, lineNo + mergedLines);
    } else {
	/*







|










|







2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
	}
	if (dispLineInfo && dlPtr->displayLineNo == 0) {
	    /*
	     * This is the right place to destroy the superfluous dispLineInfo. Don't do
	     * this before TkBTreeAdjustPixelHeight has been called, because the latter
	     * function needs the old display line count.
	     */
	    ckfree(dispLineInfo);
	    DEBUG_ALLOC(tkTextCountDestroyDispInfo++);
	    pixelInfo->dispLineInfo = NULL;
	}
	textPtr->dInfoPtr->lineMetricUpdateCounter += 1;
	pixelInfo->epoch = epoch;
	lineNo = TkBTreeLinesTo(textPtr->sharedTextPtr->tree, textPtr, linePtr, NULL);
	for (i = 0; i < mergedLines; ++i) {
	    pixelInfo = TkBTreeLinePixelInfo(textPtr, linePtr = linePtr->nextPtr);
	    pixelInfo->epoch = epoch;
	    if (pixelInfo->dispLineInfo) {
		ckfree(pixelInfo->dispLineInfo);
		DEBUG_ALLOC(tkTextCountDestroyDispInfo++);
		pixelInfo->dispLineInfo = NULL;
	    }
	}
	TkRangeListRemove(textPtr->dInfoPtr->lineMetricUpdateRanges, lineNo, lineNo + mergedLines);
    } else {
	/*
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
		    if (myLang[0] != lang[0] || myLang[1] != lang[1]) {
			nextLang = myLang;
			break;
		    }
		}
		if ((newSize = size + segPtr->size) >= capacity) {
		    capacity = MAX(2*capacity, newSize + 1);
		    str = realloc(str, newSize);
		}
		memcpy(str + size, segPtr->body.chars, segPtr->size);
		size = newSize;
		break;
	    }
	    case SEG_GROUP_HYPHEN:
		if (useUniBreak) {
		    const char *myLang = TkBTreeGetLang(textPtr, segPtr);

		    if (myLang[0] != lang[0] || myLang[1] != lang[1]) {
			nextLang = myLang;
			break;
		    }
		}
		if (size + 1 >= capacity) {
		    assert(2*capacity > size + 1);
		    str = realloc(str, capacity *= 2);
		}

		/*
		 * Use TAB (U+0009) instead of SHY (U+00AD), because SHY needs two bytes,
		 * but TAB needs only one byte, and this corresponds to the byte size of
		 * a hyphen segment. The TAB character has the same character class as
		 * the SHY character, so it's a proper substitution.
		 *
		 * NOTE: Do not use '-' (U+002D) for substitution, because the meaning
		 * of this character is contextual.
		 */

		str[size++] = '\t';
		break;
	    case SEG_GROUP_IMAGE:
	    case SEG_GROUP_WINDOW:
		/* The language variable doesn't matter here. */
		if (size + 1 >= capacity) {
		    assert(2*capacity > size + 1);
		    str = realloc(str, capacity *= 2);
		}
		/* Substitute with a TAB, so we can break at this point. */
		str[size++] = '\t';
		break;
	    case SEG_GROUP_BRANCH:
		segPtr = segPtr->body.branch.nextPtr;
	    	break;
	    }
	}
	if (size > 0) {
	    newTotalSize = totalSize + size;

	    if (newTotalSize > textPtr->brksBufferSize) {
		/*
		 * Take into account that the buffer must be a bit larger, because we need
		 * one additional byte for trailing NUL (see below).
		 */
		textPtr->brksBufferSize = MAX(newTotalSize, textPtr->brksBufferSize + 512);
		textPtr->brksBuffer = realloc(textPtr->brksBuffer, textPtr->brksBufferSize + 1);
		brks = textPtr->brksBuffer;
	    }

	    str[size] = '\0'; /* TkTextComputeBreakLocations expects traling nul */
	    TkTextComputeBreakLocations(data->textPtr->interp, str, size,
		    lang ? (*lang ? lang : "en") : NULL, brks + totalSize);
	    totalSize = newTotalSize;







|
















|



















|


















|







2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
		    if (myLang[0] != lang[0] || myLang[1] != lang[1]) {
			nextLang = myLang;
			break;
		    }
		}
		if ((newSize = size + segPtr->size) >= capacity) {
		    capacity = MAX(2*capacity, newSize + 1);
		    str = ckrealloc(str, newSize);
		}
		memcpy(str + size, segPtr->body.chars, segPtr->size);
		size = newSize;
		break;
	    }
	    case SEG_GROUP_HYPHEN:
		if (useUniBreak) {
		    const char *myLang = TkBTreeGetLang(textPtr, segPtr);

		    if (myLang[0] != lang[0] || myLang[1] != lang[1]) {
			nextLang = myLang;
			break;
		    }
		}
		if (size + 1 >= capacity) {
		    assert(2*capacity > size + 1);
		    str = ckrealloc(str, capacity *= 2);
		}

		/*
		 * Use TAB (U+0009) instead of SHY (U+00AD), because SHY needs two bytes,
		 * but TAB needs only one byte, and this corresponds to the byte size of
		 * a hyphen segment. The TAB character has the same character class as
		 * the SHY character, so it's a proper substitution.
		 *
		 * NOTE: Do not use '-' (U+002D) for substitution, because the meaning
		 * of this character is contextual.
		 */

		str[size++] = '\t';
		break;
	    case SEG_GROUP_IMAGE:
	    case SEG_GROUP_WINDOW:
		/* The language variable doesn't matter here. */
		if (size + 1 >= capacity) {
		    assert(2*capacity > size + 1);
		    str = ckrealloc(str, capacity *= 2);
		}
		/* Substitute with a TAB, so we can break at this point. */
		str[size++] = '\t';
		break;
	    case SEG_GROUP_BRANCH:
		segPtr = segPtr->body.branch.nextPtr;
	    	break;
	    }
	}
	if (size > 0) {
	    newTotalSize = totalSize + size;

	    if (newTotalSize > textPtr->brksBufferSize) {
		/*
		 * Take into account that the buffer must be a bit larger, because we need
		 * one additional byte for trailing NUL (see below).
		 */
		textPtr->brksBufferSize = MAX(newTotalSize, textPtr->brksBufferSize + 512);
		textPtr->brksBuffer = ckrealloc(textPtr->brksBuffer, textPtr->brksBufferSize + 1);
		brks = textPtr->brksBuffer;
	    }

	    str[size] = '\0'; /* TkTextComputeBreakLocations expects traling nul */
	    TkTextComputeBreakLocations(data->textPtr->interp, str, size,
		    lang ? (*lang ? lang : "en") : NULL, brks + totalSize);
	    totalSize = newTotalSize;
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
{
    TkTextDispChunkSection *sectionPtr = dInfoPtr->sectionPoolPtr;

    if (sectionPtr) {
	dInfoPtr->sectionPoolPtr = dInfoPtr->sectionPoolPtr->nextPtr;
    } else {
	DEBUG_ALLOC(tkTextCountNewSection++);
	sectionPtr = malloc(sizeof(TkTextDispChunkSection));
    }

    memset(sectionPtr, 0, sizeof(TkTextDispChunkSection));
    return sectionPtr;
}

static void
LayoutMakeNewChunk(
    LayoutData *data)
{
    TkTextDispChunk *newChunkPtr;
    TextDInfo *dInfoPtr = data->textPtr->dInfoPtr;

    LayoutFinalizeChunk(data);
    if ((newChunkPtr = dInfoPtr->chunkPoolPtr)) {
	dInfoPtr->chunkPoolPtr = newChunkPtr->nextPtr;
    } else {
	newChunkPtr = malloc(sizeof(TkTextDispChunk));
	DEBUG_ALLOC(tkTextCountNewChunk++);
    }
    memset(newChunkPtr, 0, sizeof(TkTextDispChunk));
    newChunkPtr->prevPtr = data->lastChunkPtr;
    newChunkPtr->prevCharChunkPtr = data->lastCharChunkPtr;
    newChunkPtr->stylePtr = GetStyle(data->textPtr, NULL);
    newChunkPtr->x = data->x;







|

















|







2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
{
    TkTextDispChunkSection *sectionPtr = dInfoPtr->sectionPoolPtr;

    if (sectionPtr) {
	dInfoPtr->sectionPoolPtr = dInfoPtr->sectionPoolPtr->nextPtr;
    } else {
	DEBUG_ALLOC(tkTextCountNewSection++);
	sectionPtr = ckalloc(sizeof(TkTextDispChunkSection));
    }

    memset(sectionPtr, 0, sizeof(TkTextDispChunkSection));
    return sectionPtr;
}

static void
LayoutMakeNewChunk(
    LayoutData *data)
{
    TkTextDispChunk *newChunkPtr;
    TextDInfo *dInfoPtr = data->textPtr->dInfoPtr;

    LayoutFinalizeChunk(data);
    if ((newChunkPtr = dInfoPtr->chunkPoolPtr)) {
	dInfoPtr->chunkPoolPtr = newChunkPtr->nextPtr;
    } else {
	newChunkPtr = ckalloc(sizeof(TkTextDispChunk));
	DEBUG_ALLOC(tkTextCountNewChunk++);
    }
    memset(newChunkPtr, 0, sizeof(TkTextDispChunk));
    newChunkPtr->prevPtr = data->lastChunkPtr;
    newChunkPtr->prevCharChunkPtr = data->lastCharChunkPtr;
    newChunkPtr->stylePtr = GetStyle(data->textPtr, NULL);
    newChunkPtr->x = data->x;
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
	    BreakInfo *breakInfo;
	    int new;

	    hPtr = Tcl_CreateHashEntry(&textPtr->sharedTextPtr->breakInfoTable,
		    (void *) data->logicalLinePtr, &new);

	    if (new) {
		breakInfo = malloc(sizeof(BreakInfo));
		breakInfo->refCount = 1;
		breakInfo->brks = NULL;
		data->logicalLinePtr->changed = false;
		Tcl_SetHashValue(hPtr, breakInfo);
		DEBUG_ALLOC(tkTextCountNewBreakInfo++);
	    } else {
		breakInfo = Tcl_GetHashValue(hPtr);







|







3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
	    BreakInfo *breakInfo;
	    int new;

	    hPtr = Tcl_CreateHashEntry(&textPtr->sharedTextPtr->breakInfoTable,
		    (void *) data->logicalLinePtr, &new);

	    if (new) {
		breakInfo = ckalloc(sizeof(BreakInfo));
		breakInfo->refCount = 1;
		breakInfo->brks = NULL;
		data->logicalLinePtr->changed = false;
		Tcl_SetHashValue(hPtr, breakInfo);
		DEBUG_ALLOC(tkTextCountNewBreakInfo++);
	    } else {
		breakInfo = Tcl_GetHashValue(hPtr);
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120

		/*
		 * In this case we have to parse the whole logical line for the computation
		 * of the break locations.
		 */

		brksSize = LayoutComputeBreakLocations(data);
		breakInfo->brks = realloc(breakInfo->brks, brksSize);
		memcpy(breakInfo->brks, textPtr->brksBuffer, brksSize);
		DEBUG(stats.breakInfo += 1);
	    }

	    data->breakInfo = breakInfo;
	    data->brks = breakInfo->brks;
	}







|







3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120

		/*
		 * In this case we have to parse the whole logical line for the computation
		 * of the break locations.
		 */

		brksSize = LayoutComputeBreakLocations(data);
		breakInfo->brks = ckrealloc(breakInfo->brks, brksSize);
		memcpy(breakInfo->brks, textPtr->brksBuffer, brksSize);
		DEBUG(stats.breakInfo += 1);
	    }

	    data->breakInfo = breakInfo;
	    data->brks = breakInfo->brks;
	}
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
     * Create and initialize a new DLine structure.
     */

    if (dInfoPtr->dLinePoolPtr) {
	dlPtr = dInfoPtr->dLinePoolPtr;
	dInfoPtr->dLinePoolPtr = dlPtr->nextPtr;
    } else {
	dlPtr = malloc(sizeof(DLine));
	DEBUG_ALLOC(tkTextCountNewDLine++);
    }
    dlPtr = memset(dlPtr, 0, sizeof(DLine));
    dlPtr->flags = NEW_LAYOUT|OLD_Y_INVALID;
    dlPtr->index = *indexPtr;
    dlPtr->displayLineNo = displayLineNo;
    TkTextIndexToByteIndex(&dlPtr->index);







|







4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
     * Create and initialize a new DLine structure.
     */

    if (dInfoPtr->dLinePoolPtr) {
	dlPtr = dInfoPtr->dLinePoolPtr;
	dInfoPtr->dLinePoolPtr = dlPtr->nextPtr;
    } else {
	dlPtr = ckalloc(sizeof(DLine));
	DEBUG_ALLOC(tkTextCountNewDLine++);
    }
    dlPtr = memset(dlPtr, 0, sizeof(DLine));
    dlPtr->flags = NEW_LAYOUT|OLD_Y_INVALID;
    dlPtr->index = *indexPtr;
    dlPtr->displayLineNo = displayLineNo;
    TkTextIndexToByteIndex(&dlPtr->index);
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
		}
	    }

	    if (dlPtr->breakInfo
		    && (action != DLINE_UNLINK_KEEP_BRKS || LineIsOutsideOfPeer(textPtr, &dlPtr->index))
		    && --dlPtr->breakInfo->refCount == 0) {
		assert(dlPtr->breakInfo->brks);
		free(dlPtr->breakInfo->brks);
		free(dlPtr->breakInfo);
		Tcl_DeleteHashEntry(Tcl_FindHashEntry(
			&textPtr->sharedTextPtr->breakInfoTable,
			(void *) TkBTreeGetLogicalLine(textPtr->sharedTextPtr, textPtr,
			    TkTextIndexGetLine(&dlPtr->index))));
		DEBUG_ALLOC(tkTextCountDestroyBreakInfo++);
	    }








|
|







5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
		}
	    }

	    if (dlPtr->breakInfo
		    && (action != DLINE_UNLINK_KEEP_BRKS || LineIsOutsideOfPeer(textPtr, &dlPtr->index))
		    && --dlPtr->breakInfo->refCount == 0) {
		assert(dlPtr->breakInfo->brks);
		ckfree(dlPtr->breakInfo->brks);
		ckfree(dlPtr->breakInfo);
		Tcl_DeleteHashEntry(Tcl_FindHashEntry(
			&textPtr->sharedTextPtr->breakInfoTable,
			(void *) TkBTreeGetLogicalLine(textPtr->sharedTextPtr, textPtr,
			    TkTextIndexGetLine(&dlPtr->index))));
		DEBUG_ALLOC(tkTextCountDestroyBreakInfo++);
	    }

5674
5675
5676
5677
5678
5679
5680


5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
	    dInfoPtr->lastDLinePtr = firstPtr->prevPtr;
	}
	dInfoPtr->dLinesInvalidated = true;
	assert(!dInfoPtr->dLinePtr || !dInfoPtr->dLinePtr->prevPtr);
	ReleaseLines(textPtr, firstPtr, lastPtr, action);
	break;
    case DLINE_SAVE: {


	if (!firstPtr || firstPtr == lastPtr) {
	    return NULL;
	}
	assert(firstPtr == dInfoPtr->dLinePtr);
	assert(lastPtr);

	unsigned epoch = dInfoPtr->lineMetricUpdateEpoch;
	DLine *dlPtr;

	assert(lastPtr->prevPtr);
	dInfoPtr->dLinePtr = lastPtr;

	/*
	 * Free all expired lines, we will only save valid lines.
	 */







>
>






|
<







5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689

5690
5691
5692
5693
5694
5695
5696
	    dInfoPtr->lastDLinePtr = firstPtr->prevPtr;
	}
	dInfoPtr->dLinesInvalidated = true;
	assert(!dInfoPtr->dLinePtr || !dInfoPtr->dLinePtr->prevPtr);
	ReleaseLines(textPtr, firstPtr, lastPtr, action);
	break;
    case DLINE_SAVE: {
	unsigned epoch;
	DLine *dlPtr;
	if (!firstPtr || firstPtr == lastPtr) {
	    return NULL;
	}
	assert(firstPtr == dInfoPtr->dLinePtr);
	assert(lastPtr);

	epoch = dInfoPtr->lineMetricUpdateEpoch;


	assert(lastPtr->prevPtr);
	dInfoPtr->dLinePtr = lastPtr;

	/*
	 * Free all expired lines, we will only save valid lines.
	 */
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540

    assert(textPtr);

    dInfoPtr = textPtr->dInfoPtr;
    if ((ciPtr = dInfoPtr->charInfoPoolPtr)) {
	dInfoPtr->charInfoPoolPtr = dInfoPtr->charInfoPoolPtr->u.next;
    } else {
	ciPtr = malloc(sizeof(CharInfo));
	DEBUG_ALLOC(tkTextCountNewCharInfo++);
    }

    return ciPtr;
}

/*







|







12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541

    assert(textPtr);

    dInfoPtr = textPtr->dInfoPtr;
    if ((ciPtr = dInfoPtr->charInfoPoolPtr)) {
	dInfoPtr->charInfoPoolPtr = dInfoPtr->charInfoPoolPtr->u.next;
    } else {
	ciPtr = ckalloc(sizeof(CharInfo));
	DEBUG_ALLOC(tkTextCountNewCharInfo++);
    }

    return ciPtr;
}

/*
13078
13079
13080
13081
13082
13083
13084




13085
13086
13087
13088
13089
13090
13091
	    default:
		return false;
	    }
	}
    }
    return false;
}





int
TkTextCharLayoutProc(
    const TkTextIndex *indexPtr,/* Index of first character to lay out (corresponds to segPtr and
    				 * offset). */
    TkTextSegment *segPtr,	/* Segment being layed out. */
    int byteOffset,		/* Byte offset within segment of first character to consider. */







>
>
>
>







13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
	    default:
		return false;
	    }
	}
    }
    return false;
}

#ifndef isblank
#define isblank(c) ((c) == '\t' || (c) == ' ')
#endif

int
TkTextCharLayoutProc(
    const TkTextIndex *indexPtr,/* Index of first character to lay out (corresponds to segPtr and
    				 * offset). */
    TkTextSegment *segPtr,	/* Segment being layed out. */
    int byteOffset,		/* Byte offset within segment of first character to consider. */

Changes to generic/tkTextImage.c.

235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
{
    const UndoTokenLinkSegment *token = (const UndoTokenLinkSegment *) undoInfo->token;
    TkTextSegment *segPtr = token->segPtr;
    TkTextIndex index;

    if (redoInfo) {
	RedoTokenLinkSegment *redoToken;
	redoToken = malloc(sizeof(RedoTokenLinkSegment));
	redoToken->undoType = &redoTokenLinkSegmentType;
	TkBTreeMakeUndoIndex(sharedTextPtr, segPtr, &redoToken->index);
	redoInfo->token = (TkTextUndoToken *) redoToken;
	(redoToken->segPtr = segPtr)->refCount += 1;
	DEBUG_ALLOC(tkTextCountNewUndoToken++);
    }








|







235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
{
    const UndoTokenLinkSegment *token = (const UndoTokenLinkSegment *) undoInfo->token;
    TkTextSegment *segPtr = token->segPtr;
    TkTextIndex index;

    if (redoInfo) {
	RedoTokenLinkSegment *redoToken;
	redoToken = ckalloc(sizeof(RedoTokenLinkSegment));
	redoToken->undoType = &redoTokenLinkSegmentType;
	TkBTreeMakeUndoIndex(sharedTextPtr, segPtr, &redoToken->index);
	redoInfo->token = (TkTextUndoToken *) redoToken;
	(redoToken->segPtr = segPtr)->refCount += 1;
	DEBUG_ALLOC(tkTextCountNewUndoToken++);
    }

561
562
563
564
565
566
567
568
569
570
571
572
573
574
575

	    if (!TkTextUndoStackIsFull(sharedTextPtr->undoStack)) {
		UndoTokenLinkSegment *token;

		assert(sharedTextPtr->undoStack);
		assert(eiPtr->typePtr == &tkTextEmbImageType);

		token = malloc(sizeof(UndoTokenLinkSegment));
		token->undoType = &undoTokenLinkSegmentType;
		token->segPtr = eiPtr;
		eiPtr->refCount += 1;
		DEBUG_ALLOC(tkTextCountNewUndoToken++);

		TkTextPushUndoToken(sharedTextPtr, token, 0);
	    }







|







561
562
563
564
565
566
567
568
569
570
571
572
573
574
575

	    if (!TkTextUndoStackIsFull(sharedTextPtr->undoStack)) {
		UndoTokenLinkSegment *token;

		assert(sharedTextPtr->undoStack);
		assert(eiPtr->typePtr == &tkTextEmbImageType);

		token = ckalloc(sizeof(UndoTokenLinkSegment));
		token->undoType = &undoTokenLinkSegmentType;
		token->segPtr = eiPtr;
		eiPtr->refCount += 1;
		DEBUG_ALLOC(tkTextCountNewUndoToken++);

		TkTextPushUndoToken(sharedTextPtr, token, 0);
	    }
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673

static TkTextSegment *
MakeImage(
    TkText *textPtr)		/* Information about text widget that contains embedded image. */
{
    TkTextSegment *eiPtr;

    eiPtr = memset(malloc(SEG_SIZE(TkTextEmbImage)), 0, SEG_SIZE(TkTextEmbImage));
    eiPtr->typePtr = &tkTextEmbImageType;
    eiPtr->size = 1;
    eiPtr->refCount = 1;
    eiPtr->body.ei.sharedTextPtr = textPtr->sharedTextPtr;
    eiPtr->body.ei.align = ALIGN_CENTER;
    eiPtr->body.ei.optionTable = Tk_CreateOptionTable(textPtr->interp, optionSpecs);
    DEBUG_ALLOC(tkTextCountNewSegment++);







|







659
660
661
662
663
664
665
666
667
668
669
670
671
672
673

static TkTextSegment *
MakeImage(
    TkText *textPtr)		/* Information about text widget that contains embedded image. */
{
    TkTextSegment *eiPtr;

    eiPtr = memset(ckalloc(SEG_SIZE(TkTextEmbImage)), 0, SEG_SIZE(TkTextEmbImage));
    eiPtr->typePtr = &tkTextEmbImageType;
    eiPtr->size = 1;
    eiPtr->refCount = 1;
    eiPtr->body.ei.sharedTextPtr = textPtr->sharedTextPtr;
    eiPtr->body.ei.align = ALIGN_CENTER;
    eiPtr->body.ei.optionTable = Tk_CreateOptionTable(textPtr->interp, optionSpecs);
    DEBUG_ALLOC(tkTextCountNewSegment++);
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
    }
    length = strlen(name);

    img = &eiPtr->body.ei;
    img->hPtr = Tcl_CreateHashEntry(&textPtr->sharedTextPtr->imageTable, name, &dummy);
    textPtr->sharedTextPtr->numImages += 1;
    Tcl_SetHashValue(img->hPtr, eiPtr);
    img->name = malloc(length + 1);
    memcpy(img->name, name, length + 1);
    Tcl_SetObjResult(textPtr->interp, Tcl_NewStringObj(name, -1));
    Tcl_DStringFree(&newName);
}

static int
EmbImageConfigure(







|







767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
    }
    length = strlen(name);

    img = &eiPtr->body.ei;
    img->hPtr = Tcl_CreateHashEntry(&textPtr->sharedTextPtr->imageTable, name, &dummy);
    textPtr->sharedTextPtr->numImages += 1;
    Tcl_SetHashValue(img->hPtr, eiPtr);
    img->name = ckalloc(length + 1);
    memcpy(img->name, name, length + 1);
    Tcl_SetObjResult(textPtr->interp, Tcl_NewStringObj(name, -1));
    Tcl_DStringFree(&newName);
}

static int
EmbImageConfigure(
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940

    /*
     * No need to supply a tkwin argument, since we have no window-specific options.
     */

    Tk_FreeConfigOptions((char *) img, img->optionTable, NULL);
    if (img->name) {
	free(img->name);
    }
    if (img->bbox) {
	free(img->bbox);
    }
    TkTextTagSetDecrRefCount(eiPtr->tagInfoPtr);
    FREE_SEGMENT(eiPtr);
    DEBUG_ALLOC(tkTextCountDestroySegment++);
}

/*







|


|







923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940

    /*
     * No need to supply a tkwin argument, since we have no window-specific options.
     */

    Tk_FreeConfigOptions((char *) img, img->optionTable, NULL);
    if (img->name) {
	ckfree(img->name);
    }
    if (img->bbox) {
	ckfree(img->bbox);
    }
    TkTextTagSetDecrRefCount(eiPtr->tagInfoPtr);
    FREE_SEGMENT(eiPtr);
    DEBUG_ALLOC(tkTextCountDestroySegment++);
}

/*
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
	textPtr->configureBboxTree = false;
    }

    if (img->numClients <= textPtr->pixelReference) {
	unsigned numClients = textPtr->pixelReference + 1;

	assert((img->numClients == 0) == !img->bbox);
	img->bbox = realloc(img->bbox, numClients * sizeof(img->bbox[0]));
	memset(img->bbox + img->numClients, 0, (numClients - img->numClients) * sizeof(img->bbox[0]));
	img->numClients = numClients;
    }

    /*
     * Update the bounding box, used for detection of mouse hovering.
     */







|







1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
	textPtr->configureBboxTree = false;
    }

    if (img->numClients <= textPtr->pixelReference) {
	unsigned numClients = textPtr->pixelReference + 1;

	assert((img->numClients == 0) == !img->bbox);
	img->bbox = ckrealloc(img->bbox, numClients * sizeof(img->bbox[0]));
	memset(img->bbox + img->numClients, 0, (numClients - img->numClients) * sizeof(img->bbox[0]));
	img->numClients = numClients;
    }

    /*
     * Update the bounding box, used for detection of mouse hovering.
     */

Changes to generic/tkTextIndex.c.

2960
2961
2962
2963
2964
2965
2966

2967
2968
2969
2970
2971
2972
2973
2974
2975
	    return byteIndex <= lineLength ? 0 : 1;
	}
    } else if (!linePtr->nextPtr) {
	return 1;
    }

    if ((byteIndex = dstPtr->priv.byteIndex + byteCount) > linePtr->size) {

	DEBUG(TkTextIndex index = *srcPtr);
	bool rc = TkBTreeMoveForward(dstPtr, byteCount);
	assert(!rc || TkTextIndexCountBytes(&index, dstPtr) == byteCount);
	return rc ? 0 : 1;
    }

    if (byteIndex == linePtr->size) {
	assert(linePtr->nextPtr);
	TkTextIndexSetByteIndex2(dstPtr, linePtr->nextPtr, 0);







>

|







2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
	    return byteIndex <= lineLength ? 0 : 1;
	}
    } else if (!linePtr->nextPtr) {
	return 1;
    }

    if ((byteIndex = dstPtr->priv.byteIndex + byteCount) > linePtr->size) {
	bool rc;
	DEBUG(TkTextIndex index = *srcPtr);
	rc = TkBTreeMoveForward(dstPtr, byteCount);
	assert(!rc || TkTextIndexCountBytes(&index, dstPtr) == byteCount);
	return rc ? 0 : 1;
    }

    if (byteIndex == linePtr->size) {
	assert(linePtr->nextPtr);
	TkTextIndexSetByteIndex2(dstPtr, linePtr->nextPtr, 0);
3468
3469
3470
3471
3472
3473
3474

3475
3476
3477
3478
3479
3480
3481
3482
3483
	}

	TkTextIndexSetByteIndex(dstPtr, byteIndex);
	return 0;
    }

    if (byteCount > byteIndex + 1) {

	DEBUG(TkTextIndex index = *srcPtr);
	bool rc = TkBTreeMoveBackward(dstPtr, byteCount);
	assert(!rc || TkTextIndexCountBytes(dstPtr, &index) == byteCount);
	return rc ? 0 : 1;
    }

    if ((byteIndex -= byteCount) >= 0) {
	TkTextIndexSetByteIndex(dstPtr, byteIndex);
	return 0;







>

|







3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
	}

	TkTextIndexSetByteIndex(dstPtr, byteIndex);
	return 0;
    }

    if (byteCount > byteIndex + 1) {
	bool rc;
	DEBUG(TkTextIndex index = *srcPtr);
	rc = TkBTreeMoveBackward(dstPtr, byteCount);
	assert(!rc || TkTextIndexCountBytes(dstPtr, &index) == byteCount);
	return rc ? 0 : 1;
    }

    if ((byteIndex -= byteCount) >= 0) {
	TkTextIndexSetByteIndex(dstPtr, byteIndex);
	return 0;

Changes to generic/tkTextMark.c.

11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "tkInt.h"
#include "tkText.h"
#include "tk3d.h"
#include <inttypes.h>
#include <assert.h>

#ifndef MAX
# define MAX(a,b) ((a) < (b) ? b : a)
#endif
#ifndef MIN
# define MIN(a,b) ((a) < (b) ? a : b)







<







11
12
13
14
15
16
17

18
19
20
21
22
23
24
 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "tkInt.h"
#include "tkText.h"
#include "tk3d.h"

#include <assert.h>

#ifndef MAX
# define MAX(a,b) ((a) < (b) ? b : a)
#endif
#ifndef MIN
# define MIN(a,b) ((a) < (b) ? a : b)
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458

    TkBTreeReInsertSegment(sharedTextPtr, &token->index, markPtr);
    markPtr->refCount += 1;

    if (redoInfo) {
	UndoTokenSetMark *redoToken;

	redoToken = malloc(sizeof(UndoTokenSetMark));
	redoToken->markPtr = token->markPtr;
	redoToken->undoType = &undoTokenSetMarkType;
	redoInfo->token = (TkTextUndoToken *) redoToken;
	DEBUG_ALLOC(tkTextCountNewUndoToken++);
	markPtr->refCount += 1;
    }
}







|







443
444
445
446
447
448
449
450
451
452
453
454
455
456
457

    TkBTreeReInsertSegment(sharedTextPtr, &token->index, markPtr);
    markPtr->refCount += 1;

    if (redoInfo) {
	UndoTokenSetMark *redoToken;

	redoToken = ckalloc(sizeof(UndoTokenSetMark));
	redoToken->markPtr = token->markPtr;
	redoToken->undoType = &undoTokenSetMarkType;
	redoInfo->token = (TkTextUndoToken *) redoToken;
	DEBUG_ALLOC(tkTextCountNewUndoToken++);
	markPtr->refCount += 1;
    }
}
634
635
636
637
638
639
640



641
642
643



644
645
646
647
648
649
650
	char uniqName[100];

	TkTextIndexClear(&index, textPtr);
	TkTextIndexSetSegment(&index, textPtr->startMarker);
	/* ensure fixed length (depending on pointer size) */
	snprintf(uniqName, sizeof(uniqName),
#ifdef TCL_WIDE_INT_IS_LONG



	    "##ID##0x%016"PRIx64"##0x%016"PRIx64"##%08u##", /* we're on a real 64-bit system */
	    (uint64_t) textPtr, (uint64_t) textPtr->sharedTextPtr, ++textPtr->uniqueIdCounter);
#else /* ifndef TCL_WIDE_INT_IS_LONG */



	    "##ID##0x%08"PRIx32"##0x%08"PRIx32"##%08u##",   /* we're on a 32-bit system */
	    (uint32_t) textPtr, (uint32_t) textPtr->sharedTextPtr, ++textPtr->uniqueIdCounter);
#endif /* TCL_WIDE_INT_IS_LONG */
	assert(!TkTextFindMark(textPtr, uniqName));
    	markPtr = TkTextMakeMark(textPtr, uniqName);
    	markPtr->privateMarkFlag = true;
	textPtr->sharedTextPtr->numMarks -= 1; /* take back counting */







>
>
>



>
>
>







633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
	char uniqName[100];

	TkTextIndexClear(&index, textPtr);
	TkTextIndexSetSegment(&index, textPtr->startMarker);
	/* ensure fixed length (depending on pointer size) */
	snprintf(uniqName, sizeof(uniqName),
#ifdef TCL_WIDE_INT_IS_LONG
        #ifndef PRIx64
            #define PRIx64 "llx"
        #endif
	    "##ID##0x%016"PRIx64"##0x%016"PRIx64"##%08u##", /* we're on a real 64-bit system */
	    (uint64_t) textPtr, (uint64_t) textPtr->sharedTextPtr, ++textPtr->uniqueIdCounter);
#else /* ifndef TCL_WIDE_INT_IS_LONG */
        #ifndef PRIx32
            #define PRIx32 "lx"
        #endif
	    "##ID##0x%08"PRIx32"##0x%08"PRIx32"##%08u##",   /* we're on a 32-bit system */
	    (uint32_t) textPtr, (uint32_t) textPtr->sharedTextPtr, ++textPtr->uniqueIdCounter);
#endif /* TCL_WIDE_INT_IS_LONG */
	assert(!TkTextFindMark(textPtr, uniqName));
    	markPtr = TkTextMakeMark(textPtr, uniqName);
    	markPtr->privateMarkFlag = true;
	textPtr->sharedTextPtr->numMarks -= 1; /* take back counting */
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
    bool isNew;

    assert(IS_PRESERVED(markPtr));

    name = GET_NAME(markPtr);
    hPtr = Tcl_CreateHashEntry(&sharedTextPtr->markTable, name, (int *) &isNew);
    assert(isNew);
    free(name);
    Tcl_SetHashValue(hPtr, markPtr);
    markPtr->body.mark.ptr = PTR_TO_INT(hPtr);
}

/*
 *----------------------------------------------------------------------
 *







|







915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
    bool isNew;

    assert(IS_PRESERVED(markPtr));

    name = GET_NAME(markPtr);
    hPtr = Tcl_CreateHashEntry(&sharedTextPtr->markTable, name, (int *) &isNew);
    assert(isNew);
    ckfree(name);
    Tcl_SetHashValue(hPtr, markPtr);
    markPtr->body.mark.ptr = PTR_TO_INT(hPtr);
}

/*
 *----------------------------------------------------------------------
 *
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
	    char *dup;

	    MarkDeleteProc(sharedTextPtr->tree, markPtr, 0);
	    markPtr->nextPtr = NULL;
	    markPtr->prevPtr = NULL;
	    markPtr->sectionPtr = NULL;
	    markPtr->nextPtr = chainPtr;
	    dup = malloc(strlen(name) + 1);
	    markPtr->body.mark.ptr = PTR_TO_INT(strcpy(dup, name));
	    MAKE_PRESERVED(markPtr);
	    chainPtr = markPtr;
	}
    }

    Tcl_DeleteHashTable(&sharedTextPtr->markTable);







|







964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
	    char *dup;

	    MarkDeleteProc(sharedTextPtr->tree, markPtr, 0);
	    markPtr->nextPtr = NULL;
	    markPtr->prevPtr = NULL;
	    markPtr->sectionPtr = NULL;
	    markPtr->nextPtr = chainPtr;
	    dup = ckalloc(strlen(name) + 1);
	    markPtr->body.mark.ptr = PTR_TO_INT(strcpy(dup, name));
	    MAKE_PRESERVED(markPtr);
	    chainPtr = markPtr;
	}
    }

    Tcl_DeleteHashTable(&sharedTextPtr->markTable);
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089

static TkTextSegment *
MakeMark(
    TkText *textPtr)		/* Text widget in which to create mark. */
{
    TkTextSegment *markPtr;

    markPtr = memset(malloc(SEG_SIZE(TkTextMark)), 0, SEG_SIZE(TkTextMark));
    markPtr->typePtr = &tkTextRightMarkType;
    markPtr->refCount = 1;
    markPtr->body.mark.textPtr = textPtr;
    DEBUG_ALLOC(tkTextCountNewSegment++);
    return markPtr;
}








|







1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094

static TkTextSegment *
MakeMark(
    TkText *textPtr)		/* Text widget in which to create mark. */
{
    TkTextSegment *markPtr;

    markPtr = memset(ckalloc(SEG_SIZE(TkTextMark)), 0, SEG_SIZE(TkTextMark));
    markPtr->typePtr = &tkTextRightMarkType;
    markPtr->refCount = 1;
    markPtr->body.mark.textPtr = textPtr;
    DEBUG_ALLOC(tkTextCountNewSegment++);
    return markPtr;
}

1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
    TkTextMarkChange *changePtr = markPtr->body.mark.changePtr;

    assert(TkTextIsNormalMark(markPtr));

    if (!changePtr) {
	if (sharedTextPtr->undoMarkListCount == sharedTextPtr->undoMarkListSize) {
	    sharedTextPtr->undoMarkListSize = MAX(20, 2*sharedTextPtr->undoMarkListSize);
	    sharedTextPtr->undoMarkList = realloc(sharedTextPtr->undoMarkList,
		    sharedTextPtr->undoMarkListSize * sizeof(sharedTextPtr->undoMarkList[0]));
	}
	changePtr = &sharedTextPtr->undoMarkList[sharedTextPtr->undoMarkListCount++];
	memset(changePtr, 0, sizeof(*changePtr));
	markPtr->body.mark.changePtr = changePtr;
	(changePtr->markPtr = markPtr)->refCount += 1;
    }







|







1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
    TkTextMarkChange *changePtr = markPtr->body.mark.changePtr;

    assert(TkTextIsNormalMark(markPtr));

    if (!changePtr) {
	if (sharedTextPtr->undoMarkListCount == sharedTextPtr->undoMarkListSize) {
	    sharedTextPtr->undoMarkListSize = MAX(20, 2*sharedTextPtr->undoMarkListSize);
	    sharedTextPtr->undoMarkList = ckrealloc(sharedTextPtr->undoMarkList,
		    sharedTextPtr->undoMarkListSize * sizeof(sharedTextPtr->undoMarkList[0]));
	}
	changePtr = &sharedTextPtr->undoMarkList[sharedTextPtr->undoMarkListCount++];
	memset(changePtr, 0, sizeof(*changePtr));
	markPtr->body.mark.changePtr = changePtr;
	(changePtr->markPtr = markPtr)->refCount += 1;
    }
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228

    if (!markPtr->body.mark.changePtr
	    || (!markPtr->body.mark.changePtr->setMark
		&& !markPtr->body.mark.changePtr->toggleGravity)) {
	TkTextMarkChange *changePtr = MakeChangeItem(sharedTextPtr, markPtr);
	UndoTokenToggleGravity *token;

	token = memset(malloc(sizeof(UndoTokenToggleGravity)), 0, sizeof(UndoTokenToggleGravity));
	token->undoType = &undoTokenToggleGravityType;
	(token->markPtr = markPtr)->refCount += 1;
	DEBUG_ALLOC(tkTextCountNewUndoToken++);
	changePtr->toggleGravity = (TkTextUndoToken *) token;
	changePtr->savedMarkType = oldTypePtr;
	sharedTextPtr->lastUndoTokenType = -1;
	return (TkTextUndoToken *) token;







|







1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233

    if (!markPtr->body.mark.changePtr
	    || (!markPtr->body.mark.changePtr->setMark
		&& !markPtr->body.mark.changePtr->toggleGravity)) {
	TkTextMarkChange *changePtr = MakeChangeItem(sharedTextPtr, markPtr);
	UndoTokenToggleGravity *token;

	token = memset(ckalloc(sizeof(UndoTokenToggleGravity)), 0, sizeof(UndoTokenToggleGravity));
	token->undoType = &undoTokenToggleGravityType;
	(token->markPtr = markPtr)->refCount += 1;
	DEBUG_ALLOC(tkTextCountNewUndoToken++);
	changePtr->toggleGravity = (TkTextUndoToken *) token;
	changePtr->savedMarkType = oldTypePtr;
	sharedTextPtr->lastUndoTokenType = -1;
	return (TkTextUndoToken *) token;
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346

	if ((changePtr = markPtr->body.mark.changePtr)) {
	    if (changePtr->toggleGravity) {
		TkTextUndoPushItem(sharedTextPtr->undoStack, changePtr->toggleGravity, 0);
		changePtr->toggleGravity = NULL;
	    }
	    if (changePtr->moveMark) {
		free(changePtr->moveMark);
		changePtr->moveMark = NULL;
		DEBUG_ALLOC(tkTextCountDestroyUndoToken++);
		assert(markPtr->refCount > 1);
		markPtr->refCount -= 1;
	    }
	    if (changePtr->setMark) {
		free(changePtr->setMark);
		changePtr->setMark = NULL;
		DEBUG_ALLOC(tkTextCountDestroyUndoToken++);
		assert(markPtr->refCount > 1);
		markPtr->refCount -= 1;
	    }
	}

	memset(redoInfo, 0, sizeof(*redoInfo));
	token = malloc(sizeof(RedoTokenSetMark));
	token->undoType = &redoTokenSetMarkType;
	markPtr->refCount += 1;
	token->markPtr = markPtr;
	MARK_POINTER(token->markPtr);
	TkBTreeMakeUndoIndex(sharedTextPtr, markPtr, &token->index);
	DEBUG_ALLOC(tkTextCountNewUndoToken++);
	redoInfo->token = (TkTextUndoToken *) token;







|






|








|







1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351

	if ((changePtr = markPtr->body.mark.changePtr)) {
	    if (changePtr->toggleGravity) {
		TkTextUndoPushItem(sharedTextPtr->undoStack, changePtr->toggleGravity, 0);
		changePtr->toggleGravity = NULL;
	    }
	    if (changePtr->moveMark) {
		ckfree(changePtr->moveMark);
		changePtr->moveMark = NULL;
		DEBUG_ALLOC(tkTextCountDestroyUndoToken++);
		assert(markPtr->refCount > 1);
		markPtr->refCount -= 1;
	    }
	    if (changePtr->setMark) {
		ckfree(changePtr->setMark);
		changePtr->setMark = NULL;
		DEBUG_ALLOC(tkTextCountDestroyUndoToken++);
		assert(markPtr->refCount > 1);
		markPtr->refCount -= 1;
	    }
	}

	memset(redoInfo, 0, sizeof(*redoInfo));
	token = ckalloc(sizeof(RedoTokenSetMark));
	token->undoType = &redoTokenSetMarkType;
	markPtr->refCount += 1;
	token->markPtr = markPtr;
	MARK_POINTER(token->markPtr);
	TkBTreeMakeUndoIndex(sharedTextPtr, markPtr, &token->index);
	DEBUG_ALLOC(tkTextCountNewUndoToken++);
	redoInfo->token = (TkTextUndoToken *) token;
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
    numTags = 0;
    tagArrayPtr = tagArrayBuffer;
    tagArraySize = sizeof(tagArrayBuffer)/sizeof(tagArrayBuffer[0]);
    tagPtr = TkBTreeGetTags(&index);
    for ( ; tagPtr; tagPtr = tagPtr->nextPtr) {
	if (numTags == tagArraySize) {
	    tagArraySize *= 2;
	    tagArrayPtr = realloc(tagArrayPtr == tagArrayBuffer ? NULL : tagArrayPtr, tagArraySize);
	}
	tagArrayPtr[numTags++] = tagPtr;
    }
    TkTextSortTags(numTags, tagArrayPtr);
    for (i = 0; i < numTags; ++i) {
	Tcl_DStringAppendElement(&buf, tagArrayPtr[i]->name);
    }
    if (tagArrayPtr != tagArrayBuffer) {
	free(tagArrayPtr);
    }

    rc = TkTextTriggerWatchCmd(textPtr, "cursor", idx[0], idx[1], Tcl_DStringValue(&buf), false);
    Tcl_DStringFree(&buf);
    return rc;
}








|








|







1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
    numTags = 0;
    tagArrayPtr = tagArrayBuffer;
    tagArraySize = sizeof(tagArrayBuffer)/sizeof(tagArrayBuffer[0]);
    tagPtr = TkBTreeGetTags(&index);
    for ( ; tagPtr; tagPtr = tagPtr->nextPtr) {
	if (numTags == tagArraySize) {
	    tagArraySize *= 2;
	    tagArrayPtr = ckrealloc(tagArrayPtr == tagArrayBuffer ? NULL : tagArrayPtr, tagArraySize);
	}
	tagArrayPtr[numTags++] = tagPtr;
    }
    TkTextSortTags(numTags, tagArrayPtr);
    for (i = 0; i < numTags; ++i) {
	Tcl_DStringAppendElement(&buf, tagArrayPtr[i]->name);
    }
    if (tagArrayPtr != tagArrayBuffer) {
	ckfree(tagArrayPtr);
    }

    rc = TkTextTriggerWatchCmd(textPtr, "cursor", idx[0], idx[1], Tcl_DStringValue(&buf), false);
    Tcl_DStringFree(&buf);
    return rc;
}

1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
    if (!changePtr->markPtr) {
	return; /* already released */
    }

    assert(changePtr->markPtr->body.mark.changePtr);

    if (changePtr->toggleGravity) {
	free(changePtr->toggleGravity);
	changePtr->toggleGravity = NULL;
	DEBUG_ALLOC(tkTextCountDestroyUndoToken++);
	assert(changePtr->markPtr->refCount > 1);
	changePtr->markPtr->refCount -= 1;
    }
    if (changePtr->moveMark) {
	free(changePtr->moveMark);
	changePtr->moveMark = NULL;
	DEBUG_ALLOC(tkTextCountDestroyUndoToken++);
	assert(changePtr->markPtr->refCount > 1);
	changePtr->markPtr->refCount -= 1;
    }
    if (changePtr->setMark) {
	free(changePtr->setMark);
	changePtr->setMark = NULL;
	DEBUG_ALLOC(tkTextCountDestroyUndoToken++);
	assert(changePtr->markPtr->refCount > 1);
	changePtr->markPtr->refCount -= 1;
    }

    assert(changePtr->markPtr->refCount > 1);







|






|






|







1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
    if (!changePtr->markPtr) {
	return; /* already released */
    }

    assert(changePtr->markPtr->body.mark.changePtr);

    if (changePtr->toggleGravity) {
	ckfree(changePtr->toggleGravity);
	changePtr->toggleGravity = NULL;
	DEBUG_ALLOC(tkTextCountDestroyUndoToken++);
	assert(changePtr->markPtr->refCount > 1);
	changePtr->markPtr->refCount -= 1;
    }
    if (changePtr->moveMark) {
	ckfree(changePtr->moveMark);
	changePtr->moveMark = NULL;
	DEBUG_ALLOC(tkTextCountDestroyUndoToken++);
	assert(changePtr->markPtr->refCount > 1);
	changePtr->markPtr->refCount -= 1;
    }
    if (changePtr->setMark) {
	ckfree(changePtr->setMark);
	changePtr->setMark = NULL;
	DEBUG_ALLOC(tkTextCountDestroyUndoToken++);
	assert(changePtr->markPtr->refCount > 1);
	changePtr->markPtr->refCount -= 1;
    }

    assert(changePtr->markPtr->refCount > 1);
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539

    if (changePtr->toggleGravity) {
	UndoTokenToggleGravity *token = (UndoTokenToggleGravity *) changePtr->toggleGravity;

	if (changePtr->savedMarkType != token->markPtr->typePtr) {
	    TkTextUndoPushItem(sharedTextPtr->undoStack, (TkTextUndoToken *) token, 0);
	} else {
	    free(token);
	    DEBUG_ALLOC(tkTextCountDestroyUndoToken++);
	    assert(changePtr->markPtr->refCount > 1);
	    changePtr->markPtr->refCount -= 1;
	}
	changePtr->toggleGravity = NULL;
    }
    if (changePtr->moveMark) {







|







1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544

    if (changePtr->toggleGravity) {
	UndoTokenToggleGravity *token = (UndoTokenToggleGravity *) changePtr->toggleGravity;

	if (changePtr->savedMarkType != token->markPtr->typePtr) {
	    TkTextUndoPushItem(sharedTextPtr->undoStack, (TkTextUndoToken *) token, 0);
	} else {
	    ckfree(token);
	    DEBUG_ALLOC(tkTextCountDestroyUndoToken++);
	    assert(changePtr->markPtr->refCount > 1);
	    changePtr->markPtr->refCount -= 1;
	}
	changePtr->toggleGravity = NULL;
    }
    if (changePtr->moveMark) {
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772

	changePtr = MakeChangeItem(sharedTextPtr, markPtr);

	if (!changePtr->setMark && !changePtr->moveMark) {
	    if (TkTextIndexIsEmpty(&oldIndex)) {
		UndoTokenSetMark *token;

		token = malloc(sizeof(UndoTokenSetMark));
		token->undoType = &undoTokenSetMarkType;
		(token->markPtr = markPtr)->refCount += 1;
		DEBUG_ALLOC(tkTextCountNewUndoToken++);
		changePtr->setMark = (TkTextUndoToken *) token;
		sharedTextPtr->undoStackEvent = true;
		sharedTextPtr->lastUndoTokenType = -1;
		oldTypePtr = NULL;
	    } else {
		UndoTokenMoveMark *token;

		token = malloc(sizeof(UndoTokenMoveMark));
		token->undoType = &undoTokenMoveMarkType;
		(token->markPtr = markPtr)->refCount += 1;
		token->index = undoIndex;
		DEBUG_ALLOC(tkTextCountNewUndoToken++);
		changePtr->moveMark = (TkTextUndoToken *) token;
		sharedTextPtr->undoStackEvent = true;
		sharedTextPtr->lastUndoTokenType = -1;







|










|







1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777

	changePtr = MakeChangeItem(sharedTextPtr, markPtr);

	if (!changePtr->setMark && !changePtr->moveMark) {
	    if (TkTextIndexIsEmpty(&oldIndex)) {
		UndoTokenSetMark *token;

		token = ckalloc(sizeof(UndoTokenSetMark));
		token->undoType = &undoTokenSetMarkType;
		(token->markPtr = markPtr)->refCount += 1;
		DEBUG_ALLOC(tkTextCountNewUndoToken++);
		changePtr->setMark = (TkTextUndoToken *) token;
		sharedTextPtr->undoStackEvent = true;
		sharedTextPtr->lastUndoTokenType = -1;
		oldTypePtr = NULL;
	    } else {
		UndoTokenMoveMark *token;

		token = ckalloc(sizeof(UndoTokenMoveMark));
		token->undoType = &undoTokenMoveMarkType;
		(token->markPtr = markPtr)->refCount += 1;
		token->index = undoIndex;
		DEBUG_ALLOC(tkTextCountNewUndoToken++);
		changePtr->moveMark = (TkTextUndoToken *) token;
		sharedTextPtr->undoStackEvent = true;
		sharedTextPtr->lastUndoTokenType = -1;
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
	TkTextReleaseUndoMarkTokens(sharedTextPtr, segPtr->body.mark.changePtr);
	memmove(sharedTextPtr->undoMarkList + index, sharedTextPtr->undoMarkList + index + 1,
		--sharedTextPtr->undoMarkListCount - index);
    }

    if (--segPtr->refCount == 0) {
	if (IS_PRESERVED(segPtr)) {
	    free(GET_NAME(segPtr));
	} else {
	    sharedTextPtr->numMarks -= 1;
	    Tcl_DeleteHashEntry(GET_HPTR(segPtr));
	}
	FREE_SEGMENT(segPtr);
	DEBUG_ALLOC(tkTextCountDestroySegment++);
    } else if ((flags & DELETE_PRESERVE) && !IS_PRESERVED(segPtr)) {
	Tcl_HashEntry *hPtr;
	const char *name;
	unsigned size;

	name = Tcl_GetHashKey(&sharedTextPtr->markTable, hPtr = GET_HPTR(segPtr));
	size = strlen(name) + 1;
	segPtr->body.mark.ptr = PTR_TO_INT(memcpy(malloc(size), name, size));
	MAKE_PRESERVED(segPtr);
	Tcl_DeleteHashEntry(hPtr);
	sharedTextPtr->numMarks -= 1;
    }

    return true;
}







|













|







2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
	TkTextReleaseUndoMarkTokens(sharedTextPtr, segPtr->body.mark.changePtr);
	memmove(sharedTextPtr->undoMarkList + index, sharedTextPtr->undoMarkList + index + 1,
		--sharedTextPtr->undoMarkListCount - index);
    }

    if (--segPtr->refCount == 0) {
	if (IS_PRESERVED(segPtr)) {
	    ckfree(GET_NAME(segPtr));
	} else {
	    sharedTextPtr->numMarks -= 1;
	    Tcl_DeleteHashEntry(GET_HPTR(segPtr));
	}
	FREE_SEGMENT(segPtr);
	DEBUG_ALLOC(tkTextCountDestroySegment++);
    } else if ((flags & DELETE_PRESERVE) && !IS_PRESERVED(segPtr)) {
	Tcl_HashEntry *hPtr;
	const char *name;
	unsigned size;

	name = Tcl_GetHashKey(&sharedTextPtr->markTable, hPtr = GET_HPTR(segPtr));
	size = strlen(name) + 1;
	segPtr->body.mark.ptr = PTR_TO_INT(memcpy(ckalloc(size), name, size));
	MAKE_PRESERVED(segPtr);
	Tcl_DeleteHashEntry(hPtr);
	sharedTextPtr->numMarks -= 1;
    }

    return true;
}
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
	TkSharedText *sharedTextPtr = segPtr->body.mark.textPtr->sharedTextPtr;
	Tcl_HashEntry *hPtr;
	int isNew;

	hPtr = Tcl_CreateHashEntry(&sharedTextPtr->markTable, GET_NAME(segPtr), &isNew);
	assert(isNew);
	Tcl_SetHashValue(hPtr, segPtr);
	free(GET_NAME(segPtr));
	segPtr->body.mark.ptr = PTR_TO_INT(hPtr);
	sharedTextPtr->numMarks += 1;
    }
}

/*
 *--------------------------------------------------------------







|







2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
	TkSharedText *sharedTextPtr = segPtr->body.mark.textPtr->sharedTextPtr;
	Tcl_HashEntry *hPtr;
	int isNew;

	hPtr = Tcl_CreateHashEntry(&sharedTextPtr->markTable, GET_NAME(segPtr), &isNew);
	assert(isNew);
	Tcl_SetHashValue(hPtr, segPtr);
	ckfree(GET_NAME(segPtr));
	segPtr->body.mark.ptr = PTR_TO_INT(hPtr);
	sharedTextPtr->numMarks += 1;
    }
}

/*
 *--------------------------------------------------------------

Changes to generic/tkTextTag.c.

412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
		Tcl_SetErrorCode(interp, "TK", "TEXT", "BAD_OPTION", NULL);
		return TCL_ERROR;
	    }
	}

	discardSelection = false;
	epoch = TkBTreeEpoch(sharedTextPtr->tree);
	arrayPtr = malloc(sharedTextPtr->numEnabledTags * sizeof(TkTextTag *));
	countTags = 0;
	anyChanges = false;

	for (i = arg; i < objc; i += 2) {
	    TkTextIndex index1, index2;
	    TkTextTag *tagPtr;








|







412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
		Tcl_SetErrorCode(interp, "TK", "TEXT", "BAD_OPTION", NULL);
		return TCL_ERROR;
	    }
	}

	discardSelection = false;
	epoch = TkBTreeEpoch(sharedTextPtr->tree);
	arrayPtr = ckalloc(sharedTextPtr->numEnabledTags * sizeof(TkTextTag *));
	countTags = 0;
	anyChanges = false;

	for (i = arg; i < objc; i += 2) {
	    TkTextIndex index1, index2;
	    TkTextTag *tagPtr;

460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
	    }
	}

	if (anyChanges) {
	    TkTextUpdateAlteredFlag(sharedTextPtr);
	}
	AppendTags(interp, countTags, arrayPtr);
	free(arrayPtr);
	break;
    }
    case TAG_CONFIGURE:
	if (objc < 4) {
	    Tcl_WrongNumArgs(interp, 3, objv, "tagName ?option? ?value? ?option value ...?");
	    return TCL_ERROR;
	}







|







460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
	    }
	}

	if (anyChanges) {
	    TkTextUpdateAlteredFlag(sharedTextPtr);
	}
	AppendTags(interp, countTags, arrayPtr);
	ckfree(arrayPtr);
	break;
    }
    case TAG_CONFIGURE:
	if (objc < 4) {
	    Tcl_WrongNumArgs(interp, 3, objv, "tagName ?option? ?value? ?option value ...?");
	    return TCL_ERROR;
	}
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
	    return TCL_ERROR;
	}
	if (tagPtr->spacing3 < 0) {
	    tagPtr->spacing3 = 0;
	}
    }
    if (tagPtr->tabArrayPtr) {
	free(tagPtr->tabArrayPtr);
	tagPtr->tabArrayPtr = NULL;
    }
    if (tagPtr->tabStringPtr) {
	if (!(tagPtr->tabArrayPtr = TkTextGetTabs(interp, textPtr, tagPtr->tabStringPtr))) {
	    return TCL_ERROR;
	}
    }







|







1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
	    return TCL_ERROR;
	}
	if (tagPtr->spacing3 < 0) {
	    tagPtr->spacing3 = 0;
	}
    }
    if (tagPtr->tabArrayPtr) {
	ckfree(tagPtr->tabArrayPtr);
	tagPtr->tabArrayPtr = NULL;
    }
    if (tagPtr->tabStringPtr) {
	if (!(tagPtr->tabArrayPtr = TkTextGetTabs(interp, textPtr, tagPtr->tabStringPtr))) {
	    return TCL_ERROR;
	}
    }
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188

	if (TkBitTest(sharedTextPtr->selectionTags, tagPtr->index)) {
	    /*
	     * It's not allowed to set the elide attribute of the special selection tag
	     * to 'true' (this would cause errors, because this case is not implemented).
	     */

	    free(tagPtr->elideString);
	    tagPtr->elideString = NULL;
	    tagPtr->elide = false;
            Tcl_SetObjResult(interp, Tcl_ObjPrintf(
                    "not allowed to set elide option of selection tag \"%s\"", tagPtr->name));
            Tcl_SetErrorCode(interp, "TK", "VALUE", "ELIDE", NULL);
	    return TCL_ERROR;
	}







|







1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188

	if (TkBitTest(sharedTextPtr->selectionTags, tagPtr->index)) {
	    /*
	     * It's not allowed to set the elide attribute of the special selection tag
	     * to 'true' (this would cause errors, because this case is not implemented).
	     */

	    ckfree(tagPtr->elideString);
	    tagPtr->elideString = NULL;
	    tagPtr->elide = false;
            Tcl_SetObjResult(interp, Tcl_ObjPrintf(
                    "not allowed to set elide option of selection tag \"%s\"", tagPtr->name));
            Tcl_SetErrorCode(interp, "TK", "VALUE", "ELIDE", NULL);
	    return TCL_ERROR;
	}
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
{
    TkTextTag *tagPtr;
    TkTextTag **tagArray;
    unsigned count;

    assert(segPtr);

    tagArray = malloc(textPtr->sharedTextPtr->numEnabledTags * sizeof(TkTextTag *));
    tagPtr = TkBTreeGetSegmentTags(textPtr->sharedTextPtr, segPtr, textPtr);

    for (count = 0; tagPtr; tagPtr = tagPtr->nextPtr) {
	if (!discardSelection || tagPtr != textPtr->selTagPtr) {
	    tagArray[count++] = tagPtr;
	}
    }

    AppendTags(interp, count, tagArray);
    free(tagArray);
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextTagChangedUndoRedo --
 *







|









|







1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
{
    TkTextTag *tagPtr;
    TkTextTag **tagArray;
    unsigned count;

    assert(segPtr);

    tagArray = ckalloc(textPtr->sharedTextPtr->numEnabledTags * sizeof(TkTextTag *));
    tagPtr = TkBTreeGetSegmentTags(textPtr->sharedTextPtr, segPtr, textPtr);

    for (count = 0; tagPtr; tagPtr = tagPtr->nextPtr) {
	if (!discardSelection || tagPtr != textPtr->selTagPtr) {
	    tagArray[count++] = tagPtr;
	}
    }

    AppendTags(interp, count, tagArray);
    ckfree(tagArray);
}

/*
 *----------------------------------------------------------------------
 *
 * TkTextTagChangedUndoRedo --
 *
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
	sharedTextPtr->notAffectDisplayTags = TkBitResize(sharedTextPtr->notAffectDisplayTags, newSize);
	sharedTextPtr->affectDisplayNonSelTags = TkBitResize(
		sharedTextPtr->affectDisplayNonSelTags, newSize);
	sharedTextPtr->affectGeometryTags = TkBitResize( sharedTextPtr->affectGeometryTags, newSize);
	sharedTextPtr->affectGeometryNonSelTags = TkBitResize(
		sharedTextPtr->affectGeometryNonSelTags, newSize);
	sharedTextPtr->affectLineHeightTags = TkBitResize(sharedTextPtr->affectLineHeightTags, newSize);
	sharedTextPtr->tagLookup = realloc(sharedTextPtr->tagLookup, newSize * sizeof(TkTextTag *));
	DEBUG(memset(sharedTextPtr->tagLookup + oldSize, 0, (newSize - oldSize) * sizeof(TkTextTag *)));
    }

    if (sharedTextPtr->tagInfoSize <= index) {
	sharedTextPtr->tagInfoSize = TkBitAdjustSize(index + 1);
    }

    /*
     * No existing entry. Create a new one, initialize it, and add a pointer
     * to it to the hash table entry.
     */

    tagPtr = memset(malloc(sizeof(TkTextTag)), 0, sizeof(TkTextTag));
    tagPtr->name = name;
    tagPtr->index = index;
    tagPtr->priority = textPtr->sharedTextPtr->numEnabledTags;
    tagPtr->relief = TK_RELIEF_FLAT;
    tagPtr->bgStipple = None;
    tagPtr->fgStipple = None;
    tagPtr->justify = TK_TEXT_JUSTIFY_LEFT;







|












|







1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
	sharedTextPtr->notAffectDisplayTags = TkBitResize(sharedTextPtr->notAffectDisplayTags, newSize);
	sharedTextPtr->affectDisplayNonSelTags = TkBitResize(
		sharedTextPtr->affectDisplayNonSelTags, newSize);
	sharedTextPtr->affectGeometryTags = TkBitResize( sharedTextPtr->affectGeometryTags, newSize);
	sharedTextPtr->affectGeometryNonSelTags = TkBitResize(
		sharedTextPtr->affectGeometryNonSelTags, newSize);
	sharedTextPtr->affectLineHeightTags = TkBitResize(sharedTextPtr->affectLineHeightTags, newSize);
	sharedTextPtr->tagLookup = ckrealloc(sharedTextPtr->tagLookup, newSize * sizeof(TkTextTag *));
	DEBUG(memset(sharedTextPtr->tagLookup + oldSize, 0, (newSize - oldSize) * sizeof(TkTextTag *)));
    }

    if (sharedTextPtr->tagInfoSize <= index) {
	sharedTextPtr->tagInfoSize = TkBitAdjustSize(index + 1);
    }

    /*
     * No existing entry. Create a new one, initialize it, and add a pointer
     * to it to the hash table entry.
     */

    tagPtr = memset(ckalloc(sizeof(TkTextTag)), 0, sizeof(TkTextTag));
    tagPtr->name = name;
    tagPtr->index = index;
    tagPtr->priority = textPtr->sharedTextPtr->numEnabledTags;
    tagPtr->relief = TK_RELIEF_FLAT;
    tagPtr->bgStipple = None;
    tagPtr->fgStipple = None;
    tagPtr->justify = TK_TEXT_JUSTIFY_LEFT;
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
    Tk_FreeConfigOptions((char *) tagPtr, tagPtr->optionTable, sharedTextPtr->peers->tkwin);

    /*
     * This associated information is managed by us.
     */

    if (tagPtr->tabArrayPtr) {
	free(tagPtr->tabArrayPtr);
    }

    if (sharedTextPtr->tagBindingTable) {
	Tk_DeleteAllBindings(sharedTextPtr->tagBindingTable, (ClientData) tagPtr->name);
    }

    /*
     * If this tag is widget-specific (peer widgets) then clean up the
     * refCount it holds.
     */

    if (tagPtr->textPtr) {
	if (--((TkText *) tagPtr->textPtr)->refCount == 0) {
	    free(tagPtr->textPtr);
	}
	tagPtr->textPtr = NULL;
    }

    /*
     * Finally free the tag's memory.
     */

    free(tagPtr);
    DEBUG_ALLOC(tkTextCountDestroyTag++);
}
/*
 *----------------------------------------------------------------------
 *
 * TkTextDeleteTag --
 *







|













|








|







1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
    Tk_FreeConfigOptions((char *) tagPtr, tagPtr->optionTable, sharedTextPtr->peers->tkwin);

    /*
     * This associated information is managed by us.
     */

    if (tagPtr->tabArrayPtr) {
	ckfree(tagPtr->tabArrayPtr);
    }

    if (sharedTextPtr->tagBindingTable) {
	Tk_DeleteAllBindings(sharedTextPtr->tagBindingTable, (ClientData) tagPtr->name);
    }

    /*
     * If this tag is widget-specific (peer widgets) then clean up the
     * refCount it holds.
     */

    if (tagPtr->textPtr) {
	if (--((TkText *) tagPtr->textPtr)->refCount == 0) {
	    ckfree(tagPtr->textPtr);
	}
	tagPtr->textPtr = NULL;
    }

    /*
     * Finally free the tag's memory.
     */

    ckfree(tagPtr);
    DEBUG_ALLOC(tkTextCountDestroyTag++);
}
/*
 *----------------------------------------------------------------------
 *
 * TkTextDeleteTag --
 *
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
	Tk_FreeConfigOptions((char *) tagPtr, tagPtr->optionTable, textPtr->tkwin);

	/*
	 * This associated information is managed by us.
	 */

	if (tagPtr->tabArrayPtr) {
	    free(tagPtr->tabArrayPtr);
	}

	if (tagPtr->undoTagListIndex >= 0) {
	    TkTextReleaseUndoTagToken(sharedTextPtr, tagPtr);
	}

	/*
	 * If this tag is widget-specific (peer widgets) then clean up the
	 * refCount it holds.
	 */

	if (tagPtr->textPtr) {
	    assert(textPtr == tagPtr->textPtr);
	    if (--textPtr->refCount == 0) {
		free(textPtr);
	    }
	    tagPtr->textPtr = NULL;
	}

	/*
	 * Finally free the tag's memory.
	 */

	free(tagPtr);
	DEBUG_ALLOC(tkTextCountDestroyTag++);
    }

    textPtr->numCurTags = 0;
    TkBitClear(sharedTextPtr->usedTags);
    TkBitClear(sharedTextPtr->elisionTags);
    TkBitClear(sharedTextPtr->affectDisplayTags);







|














|








|







2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
	Tk_FreeConfigOptions((char *) tagPtr, tagPtr->optionTable, textPtr->tkwin);

	/*
	 * This associated information is managed by us.
	 */

	if (tagPtr->tabArrayPtr) {
	    ckfree(tagPtr->tabArrayPtr);
	}

	if (tagPtr->undoTagListIndex >= 0) {
	    TkTextReleaseUndoTagToken(sharedTextPtr, tagPtr);
	}

	/*
	 * If this tag is widget-specific (peer widgets) then clean up the
	 * refCount it holds.
	 */

	if (tagPtr->textPtr) {
	    assert(textPtr == tagPtr->textPtr);
	    if (--textPtr->refCount == 0) {
		ckfree(textPtr);
	    }
	    tagPtr->textPtr = NULL;
	}

	/*
	 * Finally free the tag's memory.
	 */

	ckfree(tagPtr);
	DEBUG_ALLOC(tkTextCountDestroyTag++);
    }

    textPtr->numCurTags = 0;
    TkBitClear(sharedTextPtr->usedTags);
    TkBitClear(sharedTextPtr->elisionTags);
    TkBitClear(sharedTextPtr->affectDisplayTags);
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
	return;
    }

    assert(tagPtr->undoTagListIndex >= 0);
    assert(tagPtr->undoTagListIndex < sharedTextPtr->undoTagListCount);

    if (tagPtr->recentTagAddRemoveToken) {
	free(tagPtr->recentTagAddRemoveToken);
	DEBUG_ALLOC(tkTextCountDestroyUndoToken++);
	tagPtr->recentTagAddRemoveToken = NULL;
    }
    if (tagPtr->recentChangePriorityToken) {
	free(tagPtr->recentChangePriorityToken);
	DEBUG_ALLOC(tkTextCountDestroyUndoToken++);
	tagPtr->recentChangePriorityToken = NULL;
    }

    sharedTextPtr->undoTagList[tagPtr->undoTagListIndex] = NULL;
    tagPtr->undoTagListIndex = -1;
    assert(tagPtr->refCount > 1);







|




|







2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
	return;
    }

    assert(tagPtr->undoTagListIndex >= 0);
    assert(tagPtr->undoTagListIndex < sharedTextPtr->undoTagListCount);

    if (tagPtr->recentTagAddRemoveToken) {
	ckfree(tagPtr->recentTagAddRemoveToken);
	DEBUG_ALLOC(tkTextCountDestroyUndoToken++);
	tagPtr->recentTagAddRemoveToken = NULL;
    }
    if (tagPtr->recentChangePriorityToken) {
	ckfree(tagPtr->recentChangePriorityToken);
	DEBUG_ALLOC(tkTextCountDestroyUndoToken++);
	tagPtr->recentChangePriorityToken = NULL;
    }

    sharedTextPtr->undoTagList[tagPtr->undoTagListIndex] = NULL;
    tagPtr->undoTagListIndex = -1;
    assert(tagPtr->refCount > 1);
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
    }

    assert(tagPtr->undoTagListIndex >= 0);
    assert(tagPtr->undoTagListIndex < sharedTextPtr->undoTagListCount);

    if (tagPtr->recentTagAddRemoveToken) {
	if (tagPtr->recentTagAddRemoveTokenIsNull) {
	    free(tagPtr->recentTagAddRemoveToken);
	    DEBUG_ALLOC(tkTextCountDestroyUndoToken++);
	} else {
	    TkTextUndoPushItem(sharedTextPtr->undoStack, tagPtr->recentTagAddRemoveToken, 0);
	    tagPtr->refCount += 1;
	}
	tagPtr->recentTagAddRemoveToken = NULL;
    }
    if (tagPtr->recentChangePriorityToken) {
	if (tagPtr->savedPriority != tagPtr->priority) {
	    TkTextUndoPushItem(sharedTextPtr->undoStack, tagPtr->recentChangePriorityToken, 0);
	    tagPtr->refCount += 1;
	} else {
	    free(tagPtr->recentChangePriorityToken);
	    DEBUG_ALLOC(tkTextCountDestroyUndoToken++);
	}
	tagPtr->recentChangePriorityToken = NULL;
    }

    sharedTextPtr->undoTagList[tagPtr->undoTagListIndex] = NULL;
    tagPtr->undoTagListIndex = -1;







|












|







2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
    }

    assert(tagPtr->undoTagListIndex >= 0);
    assert(tagPtr->undoTagListIndex < sharedTextPtr->undoTagListCount);

    if (tagPtr->recentTagAddRemoveToken) {
	if (tagPtr->recentTagAddRemoveTokenIsNull) {
	    ckfree(tagPtr->recentTagAddRemoveToken);
	    DEBUG_ALLOC(tkTextCountDestroyUndoToken++);
	} else {
	    TkTextUndoPushItem(sharedTextPtr->undoStack, tagPtr->recentTagAddRemoveToken, 0);
	    tagPtr->refCount += 1;
	}
	tagPtr->recentTagAddRemoveToken = NULL;
    }
    if (tagPtr->recentChangePriorityToken) {
	if (tagPtr->savedPriority != tagPtr->priority) {
	    TkTextUndoPushItem(sharedTextPtr->undoStack, tagPtr->recentChangePriorityToken, 0);
	    tagPtr->refCount += 1;
	} else {
	    ckfree(tagPtr->recentChangePriorityToken);
	    DEBUG_ALLOC(tkTextCountDestroyUndoToken++);
	}
	tagPtr->recentChangePriorityToken = NULL;
    }

    sharedTextPtr->undoTagList[tagPtr->undoTagListIndex] = NULL;
    tagPtr->undoTagListIndex = -1;
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411

    if (tagPtr->undoTagListIndex >= 0) {
	return;
    }

    if (sharedTextPtr->undoTagListCount == sharedTextPtr->undoTagListSize) {
	sharedTextPtr->undoTagListSize = 2*sharedTextPtr->numEnabledTags;
	sharedTextPtr->undoTagList = realloc(sharedTextPtr->undoTagList,
		sharedTextPtr->undoTagListSize * sizeof(sharedTextPtr->undoTagList[0]));
    }
    sharedTextPtr->undoTagList[sharedTextPtr->undoTagListCount] = tagPtr;
    sharedTextPtr->undoStackEvent = true;
    sharedTextPtr->lastUndoTokenType = -1;
    tagPtr->undoTagListIndex = sharedTextPtr->undoTagListCount++;
    tagPtr->refCount += 1;







|







2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411

    if (tagPtr->undoTagListIndex >= 0) {
	return;
    }

    if (sharedTextPtr->undoTagListCount == sharedTextPtr->undoTagListSize) {
	sharedTextPtr->undoTagListSize = 2*sharedTextPtr->numEnabledTags;
	sharedTextPtr->undoTagList = ckrealloc(sharedTextPtr->undoTagList,
		sharedTextPtr->undoTagListSize * sizeof(sharedTextPtr->undoTagList[0]));
    }
    sharedTextPtr->undoTagList[sharedTextPtr->undoTagListCount] = tagPtr;
    sharedTextPtr->undoStackEvent = true;
    sharedTextPtr->lastUndoTokenType = -1;
    tagPtr->undoTagListIndex = sharedTextPtr->undoTagListCount++;
    tagPtr->refCount += 1;
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
TkTextPushTagPriorityUndo(
    TkSharedText *sharedTextPtr,
    TkTextTag *tagPtr,
    unsigned priority)
{
    UndoTokenTagPriority *token;

    token = malloc(sizeof(UndoTokenTagPriority));
    token->undoType = &undoTokenTagPriorityType;
    (token->tagPtr = tagPtr)->refCount += 1;
    token->priority = priority;
    DEBUG_ALLOC(tkTextCountNewUndoToken++);

    TkTextPushUndoToken(sharedTextPtr, token, 0);
}







|







2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
TkTextPushTagPriorityUndo(
    TkSharedText *sharedTextPtr,
    TkTextTag *tagPtr,
    unsigned priority)
{
    UndoTokenTagPriority *token;

    token = ckalloc(sizeof(UndoTokenTagPriority));
    token->undoType = &undoTokenTagPriorityType;
    (token->tagPtr = tagPtr)->refCount += 1;
    token->priority = priority;
    DEBUG_ALLOC(tkTextCountNewUndoToken++);

    TkTextPushUndoToken(sharedTextPtr, token, 0);
}
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
TkTextPushTagPriorityRedo(
    TkSharedText *sharedTextPtr,
    TkTextTag *tagPtr,
    unsigned priority)
{
    UndoTokenTagPriority *token;

    token = malloc(sizeof(UndoTokenTagPriority));
    token->undoType = &redoTokenTagPriorityType;
    (token->tagPtr = tagPtr)->refCount += 1;
    token->priority = priority;
    DEBUG_ALLOC(tkTextCountNewUndoToken++);

    TkTextPushRedoToken(sharedTextPtr, token, 0);
}







|







2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
TkTextPushTagPriorityRedo(
    TkSharedText *sharedTextPtr,
    TkTextTag *tagPtr,
    unsigned priority)
{
    UndoTokenTagPriority *token;

    token = ckalloc(sizeof(UndoTokenTagPriority));
    token->undoType = &redoTokenTagPriorityType;
    (token->tagPtr = tagPtr)->refCount += 1;
    token->priority = priority;
    DEBUG_ALLOC(tkTextCountNewUndoToken++);

    TkTextPushRedoToken(sharedTextPtr, token, 0);
}
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
	 * may blow up the stack. We save this undo token inside the tag, in this way
	 * only the relevant changes will be pushed as soon as a separator will be
	 * pushed.
	 */
	
	if (!tagPtr->recentChangePriorityToken) {
	    tagPtr->savedPriority = tagPtr->priority;
	    token = malloc(sizeof(UndoTokenTagPriority));
	    DEBUG_ALLOC(tkTextCountNewUndoToken++);
	    tagPtr->recentChangePriorityToken = (TkTextUndoToken *) token;
	    TkTextTagAddRetainedUndo(sharedTextPtr, tagPtr);
	}

	token->undoType = &undoTokenTagPriorityType;
	token->tagPtr = tagPtr;







|







2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
	 * may blow up the stack. We save this undo token inside the tag, in this way
	 * only the relevant changes will be pushed as soon as a separator will be
	 * pushed.
	 */
	
	if (!tagPtr->recentChangePriorityToken) {
	    tagPtr->savedPriority = tagPtr->priority;
	    token = ckalloc(sizeof(UndoTokenTagPriority));
	    DEBUG_ALLOC(tkTextCountNewUndoToken++);
	    tagPtr->recentChangePriorityToken = (TkTextUndoToken *) token;
	    TkTextTagAddRetainedUndo(sharedTextPtr, tagPtr);
	}

	token->undoType = &undoTokenTagPriorityType;
	token->tagPtr = tagPtr;
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
	    TkTextPickCurrent(textPtr, eventPtr);
	}
	eventPtr->xbutton.state = oldState;
    }

  done:
    if (--textPtr->refCount == 0) {
	free(textPtr);
    }
}

/*
 *--------------------------------------------------------------
 *
 * TkTextPickCurrent --







|







2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
	    TkTextPickCurrent(textPtr, eventPtr);
	}
	eventPtr->xbutton.state = oldState;
    }

  done:
    if (--textPtr->refCount == 0) {
	ckfree(textPtr);
    }
}

/*
 *--------------------------------------------------------------
 *
 * TkTextPickCurrent --
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
	    sameChunkWithUnchangedTags = false;
	}

	if (!nearby && !sameChunkWithUnchangedTags) {
	    TkTextTag *tagPtr = TkBTreeGetTags(&index);
	    if (tagPtr) {
		epoch = ++sharedTextPtr->pickEpoch;
		newArrayPtr = malloc(sharedTextPtr->numEnabledTags * sizeof(newArrayPtr[0]));
		for (i = 0; i < textPtr->numCurTags; ++i) {
		    textPtr->curTagArrayPtr[i]->flag = false; /* mark as *not* common */
		    textPtr->curTagArrayPtr[i]->epoch = epoch;
		}
		for ( ; tagPtr; tagPtr = tagPtr->nextPtr) {
		    newArrayPtr[numNewTags++] = tagPtr;
		    tagPtr->flag = (tagPtr->epoch == epoch); /* is common? */







|







2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
	    sameChunkWithUnchangedTags = false;
	}

	if (!nearby && !sameChunkWithUnchangedTags) {
	    TkTextTag *tagPtr = TkBTreeGetTags(&index);
	    if (tagPtr) {
		epoch = ++sharedTextPtr->pickEpoch;
		newArrayPtr = ckalloc(sharedTextPtr->numEnabledTags * sizeof(newArrayPtr[0]));
		for (i = 0; i < textPtr->numCurTags; ++i) {
		    textPtr->curTagArrayPtr[i]->flag = false; /* mark as *not* common */
		    textPtr->curTagArrayPtr[i]->epoch = epoch;
		}
		for ( ; tagPtr; tagPtr = tagPtr->nextPtr) {
		    newArrayPtr[numNewTags++] = tagPtr;
		    tagPtr->flag = (tagPtr->epoch == epoch); /* is common? */
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851

	TkTextSortTags(textPtr->numCurTags, textPtr->curTagArrayPtr);
	if (numNewTags > 0) {
	    size = numNewTags * sizeof(copyArrayPtr[0]);
	    if (size < sizeof(copyArrayBuffer)/sizeof(copyArrayBuffer[0])) {
		copyArrayPtr = copyArrayBuffer;
	    } else {
		copyArrayPtr = memcpy(malloc(size), newArrayPtr, size);
	    }
	    memcpy(copyArrayPtr, newArrayPtr, size);

	    /*
	     * Omit common tags. Note that the complexity of this algorithm is linear,
	     * the complexity of old implementation (wish8.6) was quadratic.
	     */







|







2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851

	TkTextSortTags(textPtr->numCurTags, textPtr->curTagArrayPtr);
	if (numNewTags > 0) {
	    size = numNewTags * sizeof(copyArrayPtr[0]);
	    if (size < sizeof(copyArrayBuffer)/sizeof(copyArrayBuffer[0])) {
		copyArrayPtr = copyArrayBuffer;
	    } else {
		copyArrayPtr = memcpy(ckalloc(size), newArrayPtr, size);
	    }
	    memcpy(copyArrayPtr, newArrayPtr, size);

	    /*
	     * Omit common tags. Note that the complexity of this algorithm is linear,
	     * the complexity of old implementation (wish8.6) was quadratic.
	     */
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
		 * consistent, this avoids problems where the binding code will
		 * discard NotifyInferior events.
		 */

		event.xcrossing.detail = NotifyAncestor;
		TagBindEvent(textPtr, &event, numOldTags, oldArrayPtr);
	    }
	    free(oldArrayPtr);
	}
    }

    if (textPtr->flags & DESTROYED) {
	return;
    }








|







2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
		 * consistent, this avoids problems where the binding code will
		 * discard NotifyInferior events.
		 */

		event.xcrossing.detail = NotifyAncestor;
		TagBindEvent(textPtr, &event, numOldTags, oldArrayPtr);
	    }
	    ckfree(oldArrayPtr);
	}
    }

    if (textPtr->flags & DESTROYED) {
	return;
    }

2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
	    assert(!nearby);
	    event = textPtr->pickEvent;
	    event.type = EnterNotify;
	    event.xcrossing.detail = NotifyAncestor;
	    TagBindEvent(textPtr, &event, numNewTags, copyArrayPtr);
	}
	if (copyArrayPtr != copyArrayBuffer) {
	    free(copyArrayPtr);
	}
    }

    if (textPtr->flags & DESTROYED) {
	return;
    }








|







2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
	    assert(!nearby);
	    event = textPtr->pickEvent;
	    event.type = EnterNotify;
	    event.xcrossing.detail = NotifyAncestor;
	    TagBindEvent(textPtr, &event, numNewTags, copyArrayPtr);
	}
	if (copyArrayPtr != copyArrayBuffer) {
	    ckfree(copyArrayPtr);
	}
    }

    if (textPtr->flags & DESTROYED) {
	return;
    }

2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
		Tk_BindEvent(sharedTextPtr->imageBindingTable, &event,
			textPtr->tkwin, 1, (ClientData *) &eiPtr->name);
	    }
	}
	textPtr->hoveredImageArrSize = 0;
	if (countHoveredImages > textPtr->hoveredImageArrCapacity) {
	    textPtr->hoveredImageArrCapacity = MAX(4, 2*textPtr->hoveredImageArrCapacity);
	    textPtr->hoveredImageArr = realloc(textPtr->hoveredImageArr,
		textPtr->hoveredImageArrCapacity * sizeof(textPtr->hoveredImageArr[0]));
	}
	for (eiPtr = eiListPtr; eiPtr; eiPtr = eiPtr->nextPtr) {
	    if (eiPtr->hovered) {
		assert(eiPtr->image);
		event.type = EnterNotify;
		event.xcrossing.detail = NotifyAncestor;







|







2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
		Tk_BindEvent(sharedTextPtr->imageBindingTable, &event,
			textPtr->tkwin, 1, (ClientData *) &eiPtr->name);
	    }
	}
	textPtr->hoveredImageArrSize = 0;
	if (countHoveredImages > textPtr->hoveredImageArrCapacity) {
	    textPtr->hoveredImageArrCapacity = MAX(4, 2*textPtr->hoveredImageArrCapacity);
	    textPtr->hoveredImageArr = ckrealloc(textPtr->hoveredImageArr,
		textPtr->hoveredImageArrCapacity * sizeof(textPtr->hoveredImageArr[0]));
	}
	for (eiPtr = eiListPtr; eiPtr; eiPtr = eiPtr->nextPtr) {
	    if (eiPtr->hovered) {
		assert(eiPtr->image);
		event.type = EnterNotify;
		event.xcrossing.detail = NotifyAncestor;
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
    unsigned i;

    /*
     * Try to avoid allocation unless there are lots of tags.
     */

    if (numTags > sizeof(nameArrayBuf) / sizeof(nameArrayBuf[0])) {
	nameArrPtr = malloc(numTags * sizeof(nameArrPtr[0]));
    } else {
	nameArrPtr = nameArrayBuf;
    }

    /*
     * We use tag names as keys in the hash table. We do this instead of using
     * the actual tagPtr objects because we want one "sel" tag binding for all







|







3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
    unsigned i;

    /*
     * Try to avoid allocation unless there are lots of tags.
     */

    if (numTags > sizeof(nameArrayBuf) / sizeof(nameArrayBuf[0])) {
	nameArrPtr = ckalloc(numTags * sizeof(nameArrPtr[0]));
    } else {
	nameArrPtr = nameArrayBuf;
    }

    /*
     * We use tag names as keys in the hash table. We do this instead of using
     * the actual tagPtr objects because we want one "sel" tag binding for all
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
	    nameArrPtr[i] = NULL;
	}
    }
    Tk_BindEvent(textPtr->sharedTextPtr->tagBindingTable, eventPtr,
	    textPtr->tkwin, numTags, (ClientData *) nameArrPtr);

    if (nameArrPtr != nameArrayBuf) {
	free(nameArrPtr);
    }
}

/*
 *--------------------------------------------------------------
 *
 * EnumerateTags --







|







3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
	    nameArrPtr[i] = NULL;
	}
    }
    Tk_BindEvent(textPtr->sharedTextPtr->tagBindingTable, eventPtr,
	    textPtr->tkwin, numTags, (ClientData *) nameArrPtr);

    if (nameArrPtr != nameArrayBuf) {
	ckfree(nameArrPtr);
    }
}

/*
 *--------------------------------------------------------------
 *
 * EnumerateTags --
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
	    TkBitIncrRefCount(includeBits = sharedTextPtr->usedTags);
	}
    }
    if (discardBits) {
	TkBitRemove(includeBits, discardBits);
    }

    arrayPtr = malloc(sharedTextPtr->numEnabledTags * sizeof(TkTextTag *));
    countTags = 0;

    for (i = TkBitFindFirst(includeBits); i != TK_BIT_NPOS; i = TkBitFindNext(includeBits, i)) {
	arrayPtr[countTags++] = sharedTextPtr->tagLookup[i];
    }

    AppendTags(interp, countTags, arrayPtr);
    free(arrayPtr);

    TkBitDecrRefCount(includeBits);
    if (discardBits) {
	TkBitDecrRefCount(discardBits);
    }

    return TCL_OK;







|







|







3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
	    TkBitIncrRefCount(includeBits = sharedTextPtr->usedTags);
	}
    }
    if (discardBits) {
	TkBitRemove(includeBits, discardBits);
    }

    arrayPtr = ckalloc(sharedTextPtr->numEnabledTags * sizeof(TkTextTag *));
    countTags = 0;

    for (i = TkBitFindFirst(includeBits); i != TK_BIT_NPOS; i = TkBitFindNext(includeBits, i)) {
	arrayPtr[countTags++] = sharedTextPtr->tagLookup[i];
    }

    AppendTags(interp, countTags, arrayPtr);
    ckfree(arrayPtr);

    TkBitDecrRefCount(includeBits);
    if (discardBits) {
	TkBitDecrRefCount(discardBits);
    }

    return TCL_OK;

Changes to generic/tkTextTagSet.h.

13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

#ifndef _TKTEXTTAGSET
#define _TKTEXTTAGSET

#include "tkBitField.h"
#include "tkIntSet.h"

#include <stdint.h>

#if defined(__GNUC__) || defined(__clang__)
# define __warn_unused__ __attribute__((warn_unused_result))
#else
# define __warn_unused__
#endif








|







13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

#ifndef _TKTEXTTAGSET
#define _TKTEXTTAGSET

#include "tkBitField.h"
#include "tkIntSet.h"

#include "mystdint.h"

#if defined(__GNUC__) || defined(__clang__)
# define __warn_unused__ __attribute__((warn_unused_result))
#else
# define __warn_unused__
#endif

Changes to generic/tkTextUndo.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/*
 * tkTextUndo.c --
 *
 *	This module provides the implementation of an undo stack.
 *
 * Copyright (c) 2015-2017 Gregor Cramer.
 *
 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "tkTextUndo.h"
#include "tkInt.h"
#include "tkAlloc.h"
#include <assert.h>

#if !(__STDC_VERSION__ >= 199901L || (defined(_MSC_VER) && _MSC_VER >= 1900))
# define _TK_NEED_IMPLEMENTATION
# include "tkTextUndoPriv.h"
#endif














<







1
2
3
4
5
6
7
8
9
10
11
12
13

14
15
16
17
18
19
20
/*
 * tkTextUndo.c --
 *
 *	This module provides the implementation of an undo stack.
 *
 * Copyright (c) 2015-2017 Gregor Cramer.
 *
 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "tkTextUndo.h"
#include "tkInt.h"

#include <assert.h>

#if !(__STDC_VERSION__ >= 199901L || (defined(_MSC_VER) && _MSC_VER >= 1900))
# define _TK_NEED_IMPLEMENTATION
# include "tkTextUndoPriv.h"
#endif

115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
    /*
     * Now delete all atoms starting at 'atom' until we reach the end (inclusive).
     */

    do {
	MyUndoAtom *next = atom->next;
	FreeItems(stack, &atom->data);
	free(atom);
	atom = next;
    } while (atom != root);

    /*
     * Update the list pointers accordingly.
     */








|







114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
    /*
     * Now delete all atoms starting at 'atom' until we reach the end (inclusive).
     */

    do {
	MyUndoAtom *next = atom->next;
	FreeItems(stack, &atom->data);
	ckfree(atom);
	atom = next;
    } while (atom != root);

    /*
     * Update the list pointers accordingly.
     */

145
146
147
148
149
150
151
152

153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179

    if (current) {
	FreeItems(stack, &current->data);
    }

    if (force || !current || current->capacity > InitialCapacity) {
	static unsigned Size = ATOM_SIZE(InitialCapacity);
	current = stack->current = memset(realloc(current, Size), 0, Size);

	current->capacity = InitialCapacity;
    }

    current->data.arraySize = 0;
    current->data.size = 0;
    current->undoSize = 0;
}


static MyUndoAtom *
SwapCurrent(
    TkTextUndoStack stack,
    MyUndoAtom *atom)
{
    MyUndoAtom *current = stack->current;

    assert(atom != current);

    if (current->capacity != current->data.size) {
	current = stack->current = realloc(current, ATOM_SIZE(current->data.arraySize));
	current->capacity = current->data.arraySize;
    }

    if (!atom) {
	/*
	 * Just use the 'stack->current' item.
	 */







|
>



















|







144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179

    if (current) {
	FreeItems(stack, &current->data);
    }

    if (force || !current || current->capacity > InitialCapacity) {
	static unsigned Size = ATOM_SIZE(InitialCapacity);
	current = stack->current = ckrealloc(current, Size);
	memset(current, 0, Size);
	current->capacity = InitialCapacity;
    }

    current->data.arraySize = 0;
    current->data.size = 0;
    current->undoSize = 0;
}


static MyUndoAtom *
SwapCurrent(
    TkTextUndoStack stack,
    MyUndoAtom *atom)
{
    MyUndoAtom *current = stack->current;

    assert(atom != current);

    if (current->capacity != current->data.size) {
	current = stack->current = ckrealloc(current, ATOM_SIZE(current->data.arraySize));
	current->capacity = current->data.arraySize;
    }

    if (!atom) {
	/*
	 * Just use the 'stack->current' item.
	 */
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
    TkTextUndoFreeProc freeProc,
    TkTextUndoStackContentChangedProc contentChangedProc)
{
    TkTextUndoStack stack;

    assert(undoProc);

    stack = memset(malloc(sizeof(*stack)), 0, sizeof(*stack));
    stack->undoProc = undoProc;
    stack->freeProc = freeProc;
    stack->contentChangedProc = contentChangedProc;
    stack->maxUndoDepth = maxUndoDepth;
    stack->maxRedoDepth = MAX(maxRedoDepth, -1);
    stack->maxSize = maxSize;








|







410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
    TkTextUndoFreeProc freeProc,
    TkTextUndoStackContentChangedProc contentChangedProc)
{
    TkTextUndoStack stack;

    assert(undoProc);

    stack = memset(ckalloc(sizeof(*stack)), 0, sizeof(*stack));
    stack->undoProc = undoProc;
    stack->freeProc = freeProc;
    stack->contentChangedProc = contentChangedProc;
    stack->maxUndoDepth = maxUndoDepth;
    stack->maxRedoDepth = MAX(maxRedoDepth, -1);
    stack->maxSize = maxSize;

435
436
437
438
439
440
441
442
443
444
445
446
447
448
449

	if (stack) {
	    assert(stack);
	    TkTextUndoClearStack(stack);
	    if (stack->current) {
		FreeItems(stack, &stack->current->data);
	    }
	    free(stack);
	    *stackPtr = NULL;
	}
    }
}


int







|







435
436
437
438
439
440
441
442
443
444
445
446
447
448
449

	if (stack) {
	    assert(stack);
	    TkTextUndoClearStack(stack);
	    if (stack->current) {
		FreeItems(stack, &stack->current->data);
	    }
	    ckfree(stack);
	    *stackPtr = NULL;
	}
    }
}


int
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
    atom = stack->current;

    if (!atom) {
	ResetCurrent(stack, true);
	atom = stack->current;
    } else if (atom->data.arraySize == atom->capacity) {
	atom->capacity *= 2;
	atom = stack->current = realloc(atom, ATOM_SIZE(atom->capacity));
    }

    subAtom = ((TkTextUndoSubAtom *) atom->data.array) + atom->data.arraySize++;
    subAtom->item = item;
    subAtom->size = size;
    subAtom->redo = stack->doingUndo;
    atom->data.size += size;







|







751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
    atom = stack->current;

    if (!atom) {
	ResetCurrent(stack, true);
	atom = stack->current;
    } else if (atom->data.arraySize == atom->capacity) {
	atom->capacity *= 2;
	atom = stack->current = ckrealloc(atom, ATOM_SIZE(atom->capacity));
    }

    subAtom = ((TkTextUndoSubAtom *) atom->data.array) + atom->data.arraySize++;
    subAtom->item = item;
    subAtom->size = size;
    subAtom->redo = stack->doingUndo;
    atom->data.size += size;

Changes to generic/tkTextUndo.h.

27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#ifndef _TKTEXTUNDO
#define _TKTEXTUNDO

#include "tkBool.h"
#include <stdint.h>

#ifdef _MSC_VER
# if _MSC_VER >= 1900
#  define inline __inline
# else
#  define inline
# endif







|







27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#ifndef _TKTEXTUNDO
#define _TKTEXTUNDO

#include "tkBool.h"
#include "mystdint.h"

#ifdef _MSC_VER
# if _MSC_VER >= 1900
#  define inline __inline
# else
#  define inline
# endif

Changes to generic/tkTextWind.c.

253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
{
    const UndoTokenLinkSegment *token = (const UndoTokenLinkSegment *) undoInfo->token;
    TkTextSegment *segPtr = token->segPtr;
    TkTextIndex index;

    if (redoInfo) {
	RedoTokenLinkSegment *redoToken;
	redoToken = malloc(sizeof(RedoTokenLinkSegment));
	redoToken->undoType = &redoTokenLinkSegmentType;
	TkBTreeMakeUndoIndex(sharedTextPtr, segPtr, &redoToken->index);
	redoInfo->token = (TkTextUndoToken *) redoToken;
	(redoToken->segPtr = segPtr)->refCount += 1;
	DEBUG_ALLOC(tkTextCountNewUndoToken++);
    }








|







253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
{
    const UndoTokenLinkSegment *token = (const UndoTokenLinkSegment *) undoInfo->token;
    TkTextSegment *segPtr = token->segPtr;
    TkTextIndex index;

    if (redoInfo) {
	RedoTokenLinkSegment *redoToken;
	redoToken = ckalloc(sizeof(RedoTokenLinkSegment));
	redoToken->undoType = &redoTokenLinkSegmentType;
	TkBTreeMakeUndoIndex(sharedTextPtr, segPtr, &redoToken->index);
	redoInfo->token = (TkTextUndoToken *) redoToken;
	(redoToken->segPtr = segPtr)->refCount += 1;
	DEBUG_ALLOC(tkTextCountNewUndoToken++);
    }

555
556
557
558
559
560
561
562
563
564
565
566
567
568
569

	if (!TkTextUndoStackIsFull(sharedTextPtr->undoStack)) {
	    UndoTokenLinkSegment *token;

	    assert(sharedTextPtr->undoStack);
	    assert(ewPtr->typePtr == &tkTextEmbWindowType);

	    token = malloc(sizeof(UndoTokenLinkSegment));
	    token->undoType = &undoTokenLinkSegmentType;
	    token->segPtr = ewPtr;
	    ewPtr->refCount += 1;
	    DEBUG_ALLOC(tkTextCountNewUndoToken++);

	    TkTextPushUndoToken(sharedTextPtr, token, 0);
	}







|







555
556
557
558
559
560
561
562
563
564
565
566
567
568
569

	if (!TkTextUndoStackIsFull(sharedTextPtr->undoStack)) {
	    UndoTokenLinkSegment *token;

	    assert(sharedTextPtr->undoStack);
	    assert(ewPtr->typePtr == &tkTextEmbWindowType);

	    token = ckalloc(sizeof(UndoTokenLinkSegment));
	    token->undoType = &undoTokenLinkSegmentType;
	    token->segPtr = ewPtr;
	    ewPtr->refCount += 1;
	    DEBUG_ALLOC(tkTextCountNewUndoToken++);

	    TkTextPushUndoToken(sharedTextPtr, token, 0);
	}
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
static TkTextSegment *
MakeWindow(
    TkText *textPtr)		/* Information about text widget that contains embedded image. */
{
    TkTextSegment *ewPtr;
    TkTextEmbWindowClient *client;

    ewPtr = memset(malloc(SEG_SIZE(TkTextEmbWindow)), 0, SEG_SIZE(TkTextEmbWindow));
    ewPtr->typePtr = &tkTextEmbWindowType;
    ewPtr->size = 1;
    ewPtr->refCount = 1;
    ewPtr->body.ew.sharedTextPtr = textPtr->sharedTextPtr;
    ewPtr->body.ew.align = ALIGN_CENTER;
    ewPtr->body.ew.optionTable = Tk_CreateOptionTable(textPtr->interp, optionSpecs);
    DEBUG_ALLOC(tkTextCountNewSegment++);

    client = memset(malloc(sizeof(TkTextEmbWindowClient)), 0, sizeof(TkTextEmbWindowClient));
    client->textPtr = textPtr;
    client->parent = ewPtr;
    ewPtr->body.ew.clients = client;

    return ewPtr;
}








|








|







613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
static TkTextSegment *
MakeWindow(
    TkText *textPtr)		/* Information about text widget that contains embedded image. */
{
    TkTextSegment *ewPtr;
    TkTextEmbWindowClient *client;

    ewPtr = memset(ckalloc(SEG_SIZE(TkTextEmbWindow)), 0, SEG_SIZE(TkTextEmbWindow));
    ewPtr->typePtr = &tkTextEmbWindowType;
    ewPtr->size = 1;
    ewPtr->refCount = 1;
    ewPtr->body.ew.sharedTextPtr = textPtr->sharedTextPtr;
    ewPtr->body.ew.align = ALIGN_CENTER;
    ewPtr->body.ew.optionTable = Tk_CreateOptionTable(textPtr->interp, optionSpecs);
    DEBUG_ALLOC(tkTextCountNewSegment++);

    client = memset(ckalloc(sizeof(TkTextEmbWindowClient)), 0, sizeof(TkTextEmbWindowClient));
    client->textPtr = textPtr;
    client->parent = ewPtr;
    ewPtr->body.ew.clients = client;

    return ewPtr;
}

792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
	    }

	    if (!client) {
		/*
		 * Have to make the new client.
		 */

		client = malloc(sizeof(TkTextEmbWindowClient));
		memset(client, 0, sizeof(TkTextEmbWindowClient));
		client->next = ewPtr->body.ew.clients;
		client->textPtr = textPtr;
		client->parent = ewPtr;
		ewPtr->body.ew.clients = client;
	    }
	    client->tkwin = ewPtr->body.ew.tkwin;







|







792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
	    }

	    if (!client) {
		/*
		 * Have to make the new client.
		 */

		client = ckalloc(sizeof(TkTextEmbWindowClient));
		memset(client, 0, sizeof(TkTextEmbWindowClient));
		client->next = ewPtr->body.ew.clients;
		client->textPtr = textPtr;
		client->parent = ewPtr;
		ewPtr->body.ew.clients = client;
	    }
	    client->tkwin = ewPtr->body.ew.tkwin;
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
	ewPtr->body.ew.clients = client->next;
    } else {
	while (loop->next != client) {
	    loop = loop->next;
	}
	loop->next = client->next;
    }
    free(client);

    TkTextIndexClear(&index, textPtr);
    TkTextIndexSetSegment(&index, ewPtr);
    TextChanged(ewPtr->body.ew.sharedTextPtr, &index);
}

/*







|







971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
	ewPtr->body.ew.clients = client->next;
    } else {
	while (loop->next != client) {
	    loop = loop->next;
	}
	loop->next = client->next;
    }
    ckfree(client);

    TkTextIndexClear(&index, textPtr);
    TkTextIndexSetSegment(&index, ewPtr);
    TextChanged(ewPtr->body.ew.sharedTextPtr, &index);
}

/*
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
    }
    Tcl_CancelIdleCall(EmbWinDelayedUnmap, client);

    /*
     * Free up this client.
     */

    free(client);
}

/*
 *--------------------------------------------------------------
 *
 * EmbWinInspectProc --
 *







|







1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
    }
    Tcl_CancelIdleCall(EmbWinDelayedUnmap, client);

    /*
     * Free up this client.
     */

    ckfree(client);
}

/*
 *--------------------------------------------------------------
 *
 * EmbWinInspectProc --
 *
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405

	if (!client) {
	    /*
	     * We just used a '-create' script to make a new window, which we
	     * now need to add to our client list.
	     */

	    client = malloc(sizeof(TkTextEmbWindowClient));
	    memset(client, 0, sizeof(TkTextEmbWindowClient));
	    client->next = ewPtr->body.ew.clients;
	    client->textPtr = textPtr;
	    client->parent = ewPtr;
	    ewPtr->body.ew.clients = client;
	}








|







1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405

	if (!client) {
	    /*
	     * We just used a '-create' script to make a new window, which we
	     * now need to add to our client list.
	     */

	    client = ckalloc(sizeof(TkTextEmbWindowClient));
	    memset(client, 0, sizeof(TkTextEmbWindowClient));
	    client->next = ewPtr->body.ew.clients;
	    client->textPtr = textPtr;
	    client->parent = ewPtr;
	    ewPtr->body.ew.clients = client;
	}

Changes to win/makefile.vc.

425
426
427
428
429
430
431
432
433






434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
RCDIR		= $(WINDIR)\rc

TK_INCLUDES	= -I"$(WINDIR)" -I"$(GENERICDIR)" -I"$(BITMAPDIR)" -I"$(XLIBDIR)" \
			$(TCL_INCLUDES)

CONFIG_DEFS     =-DSTDC_HEADERS=1 -DHAVE_SYS_TYPES_H=1 -DHAVE_SYS_STAT_H=1 \
		 -DHAVE_STDLIB_H=1 -DHAVE_STRING_H=1 -DHAVE_MEMORY_H=1 \
		 -DHAVE_STRINGS_H=1 -DHAVE_INTTYPES_H=1 -DHAVE_STDINT_H=1 \
		 -DSUPPORT_CONFIG_EMBEDDED \






!if $(HAVE_UXTHEME_H)
		 -DHAVE_UXTHEME_H=1 \
!endif
!if $(TTK_SQUARE_WIDGET)
		 -DTTK_SQUARE_WIDGET=1 \
!endif

TK_DEFINES	=-DBUILD_ttk $(OPTDEFINES)  $(CONFIG_DEFS) -Dinline=__inline

#---------------------------------------------------------------------
# Compile flags
#---------------------------------------------------------------------

!if !$(DEBUG)
!if $(OPTIMIZING)







|

>
>
>
>
>
>







|







425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
RCDIR		= $(WINDIR)\rc

TK_INCLUDES	= -I"$(WINDIR)" -I"$(GENERICDIR)" -I"$(BITMAPDIR)" -I"$(XLIBDIR)" \
			$(TCL_INCLUDES)

CONFIG_DEFS     =-DSTDC_HEADERS=1 -DHAVE_SYS_TYPES_H=1 -DHAVE_SYS_STAT_H=1 \
		 -DHAVE_STDLIB_H=1 -DHAVE_STRING_H=1 -DHAVE_MEMORY_H=1 \
		 -DHAVE_STRINGS_H=1 \
		 -DSUPPORT_CONFIG_EMBEDDED \
!if $(VCVERSION) > 1500
		 -DHAVE_STDINT_H=1 \
!endif
!if $(VCVERSION) > 1700
		 -DHAVE_INTTYPES_H=1 \
!endif
!if $(HAVE_UXTHEME_H)
		 -DHAVE_UXTHEME_H=1 \
!endif
!if $(TTK_SQUARE_WIDGET)
		 -DTTK_SQUARE_WIDGET=1 \
!endif

TK_DEFINES	=-DBUILD_ttk $(OPTDEFINES)  $(CONFIG_DEFS) -Dinline=__inline -DMODULE_SCOPE=""

#---------------------------------------------------------------------
# Compile flags
#---------------------------------------------------------------------

!if !$(DEBUG)
!if $(OPTIMIZING)