-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdoc-text.c
2592 lines (2382 loc) · 62.5 KB
/
doc-text.c
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
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
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
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
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
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
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
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
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
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
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
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
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
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
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
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
/*
* Copyright Neil Brown ©2015-2023 <[email protected]>
* May be distributed under terms of GPLv2 - see file:COPYING
*
* Generic text document.
*
* This allows for a file to be read in, and edited by creating
* a linked list of chunks of text - the original isn't changed.
* This means that pointers outside of the edit region are mostly
* left untouched.
*
* Indefinite undo is kept as a record of changes to the list of chunks.
* New text is added to the end of a list of allocations.
*
* Text.
*
* The text of a document is stored in a collection of allocations
* which are immutable once created. They are attached to the 'document'
* and freed only when the document is discard.
* The current state of the document is represented by a linked list of
* 'chunks' which each point to part of some allocation.
*
* Each chunk can have 'attributes' which add arbitrary annotations to
* ranges of text. Unlike the text itself, these are not immutable. Only
* the 'current' attributes are stored. It is assumed that following
* 'undo', the appropriate attributes can be re-computed. i.e. they are
* a cache. The owner can get notified of changes which imply that
* attributes may have been lost.
*
* When text is removed from a document, the 'chunk' is modified to
* reference less text. If the chunk becomes empty, it is removed
* from the list, but not freed - as it will be in the undo list.
* When text is added to a document a new chunk is created which
* points to the next free space in the latest allocation, and text is
* added there. If the text is being added to the end of a chunk and
* it already points to the end of the latest allocation, then no new
* chunk is allocated.
*
* Text is assumed to be UTF-8 encoded. This becomes relevant when adding
* a string to the document and it won't all fit in the current allocation.
* In that case we ensure the first byte that goes in the next allocation
* matches 0xxxxxxx or 11xxxxxx., not 10xxxxxx.
*
* Undo/redo information is stored as a list of edits. Each edit
* changes either the start or the end of a 'chunk'. When a chunk becomes
* empty it is removed from the chunk list. The 'prev' pointer is preserved
* so when an undo makes it non-empty, it knows where to be added back.
*
* A text always has a least one allocation which is created with the text.
* If the text is empty, there will not be any chunks though, so all text refs
* will point to NULL. The NULL chunk is at the end of the text.
* The ->txt pointer of a chunk never changes. It is set when the chunk
* is created and then only start and end are changed.
*/
#define _GNU_SOURCE /* for asprintf */
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <memory.h>
#include <locale.h>
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <dirent.h>
/* A doc_ref is treated as a pointer to a chunk, and an offset
* from the start of 'txt'. So 'o' must be between c->start and
* c->end inclusive.
* A 'c' of NULL means end of file.
* The normalized form requires that 'o' does
* not point to the end of the chunk.
*/
#define PRIVATE_DOC_REF
struct doc_ref {
struct text_chunk *c;
unsigned int o;
};
struct text;
#define DOC_DATA_TYPE struct text
#define DOC_NEXT(d,m,r,b) text_next(d,r,b)
#define DOC_PREV(d,m,r,b) text_prev(d,r,b)
#include "core.h"
#include "misc.h"
/* text is allocated is large blocks - possibly a whole
* file or some other large unit being added to a document.
* For small additions (normal typing) the default allocation
* size is 4K.
* When more is allocated than needed, extra can be added on to
* the end - 'free' is the next index with free space.
*/
struct text_alloc {
struct text_alloc *prev;
int size;
int free;
char text[];
};
#define DEFAULT_SIZE ((int)(4096 - sizeof(struct text_alloc)))
#define MAX_SIZE ((int)((1<<20) - sizeof(struct text_alloc)))
/* The text document is a list of text_chunk.
* The 'txt' pointer is within the text[] of a text_alloc.
* 'start' and 'end' narrow that.
* Each alloc potentially is divided into multiple
* separate chunks which are never merged. The only
* chunk that can change size is the last one allocated,
* which may grow into the free space.
*/
struct text_chunk {
char *txt safe;
unsigned int start;
unsigned int end;
struct list_head lst;
struct attrset *attrs;
};
/* An 'edit' consists of one or more text_edit structs linked together.
* The 'first' text_edit in a group has 'first' set. So when popping
* off the 'undo' list, we pop until we find the 'first' one. When
* popping off the 'redo' list, we pop a first, then any following
* non-first entries.
* Each entry identifies a chunk. If 'at_start' is set, the 'len' is
* added to the 'start' pointer (subtracted for undo). Otherwise
* the len added to the end. If the resulting length is zero, the
* chunk is removed from the list.
*
* Each edit can have an altnext.
* For the undo list, this is an alternate redo to reflect a branching
* change history.
* For the redo list, this is a second change that happened from the
* same starting point. If there is a third change, we insert a no-op
* edit so as to get an extra altnext.
* In the undo list, altnext is an alternate forward path.
* if alt_is_second, then we are currently on the second path, and after
* undoing it, will go up the first.
* if !alt_is_second, we are currently on the first path, and
* don't want to go back up the second (until we undo all the way to the
* start and try again).
*/
struct text_edit {
struct text_chunk *target safe;
struct text_edit *next, *altnext;
bool first:1;
bool at_start:1;
bool alt_is_second:1;
signed int len:29; // bytes add, -ve for removed.
};
/* A text document is a document with allocations, a list
* of chunks, and some undo info.
*/
struct text {
struct doc doc;
struct text_alloc *alloc safe;
struct list_head text;
struct text_edit *undo, *redo;
/* If prev_edit is Redo then next edit is ->redo or ->undo->altnext
* or ->undo
* If prev_edit is Undo, then next edit is ->undo->altnext or ->undo
* If prev_edit is AltUndo, then next edit is ->undo
*/
enum { Redo, Undo, AltUndo } prev_edit;
bool revising_marks;
char file_changed; /* '2' means it has changed, but
* we are editing anyway
*/
char newfile; /* file doesn't exist yet */
bool autosave_exists;
struct stat stat;
const char *fname;
const char *autosave_name;
struct text_edit *saved;
struct auto_save {
int changes;
int timer_started;
time_t last_change;
} as;
};
#include "core-pane.h"
static int text_advance_towards(struct text *t safe, struct doc_ref *ref safe,
struct doc_ref *target safe);
static int text_retreat_towards(struct text *t safe, struct doc_ref *ref safe,
struct doc_ref *target safe);
static bool text_ref_same(struct text *t safe, struct doc_ref *r1 safe,
struct doc_ref *r2 safe);
static bool _text_ref_same(struct text *t safe, struct doc_ref *r1 safe,
struct doc_ref *r2 safe);
static int text_locate(struct text *t safe, struct doc_ref *r safe,
struct doc_ref *dest safe);
static void text_check_consistent(struct text *t safe);
static void text_normalize(struct text *t safe, struct doc_ref *r safe);
static void text_cleanout(struct text *t safe);
static void text_add_str(struct text *t safe, struct mark *pm safe,
const char *str safe, off_t size,
bool *first_edit safe);
static void text_check_autosave(struct pane *p safe);
static bool check_readonly(const struct cmd_info *ci safe);
static MEMPOOL(text);
static MEMPOOL(undo);
static struct map *text_map;
static struct text_alloc *safe
text_new_alloc(struct text *t safe, int size)
{
struct text_alloc *new;
if (size == 0)
size = DEFAULT_SIZE;
size += sizeof(struct text_alloc);
size = ((size-1) | 255) + 1;
new = alloc_buf(size, text);
new->prev = t->alloc;
t->alloc = new;
new->size = size - sizeof(struct text_alloc);
new->free = 0;
return new;
}
static bool check_file_changed(struct pane *p safe)
{
struct text *t = p->doc_data;
struct stat st;
if (t->file_changed)
/* '1' means it has changed, '2' means "but we don't care" */
return t->file_changed == 1;
if (!t->fname)
return False;
if (stat(t->fname, &st) != 0) {
memset(&st, 0, sizeof(st));
if (t->newfile)
return False;
}
if (st.st_ino != t->stat.st_ino ||
st.st_dev != t->stat.st_dev ||
st.st_mtime != t->stat.st_mtime ||
st.st_mtim.tv_nsec != t->stat.st_mtim.tv_nsec) {
t->file_changed = 1;
call("doc:notify:doc:status-changed", p);
return True;
}
return False;
}
DEF_CMD(text_readonly)
{
struct text *t = ci->home->doc_data;
if (t->file_changed && !t->doc.readonly && ci->num)
t->file_changed = 2;
/* Use default handling */
return Efallthrough;
}
static const char *safe autosave_name(const char *name safe)
{
char *tempname = malloc(strlen(name) + 3 + 10);
const char *base;
char *tbase;
strcpy(tempname, name);
base = strrchr(name, '/');
if (base)
base += 1;
else
base = name;
tbase = tempname + (base - name);
sprintf(tbase, "#%s#", base);
return tempname;
}
DEF_CMD(text_load_file)
{
int fd = ci->num2;
const char *name = ci->str;
off_t size;
struct text_alloc *a;
struct text_chunk *c = NULL;
int len;
struct text *t = ci->home->doc_data;
if (t->saved != t->undo)
return Einval;
if (fd < 0 && (ci->num & 6) && t->fname) {
/* re-open existing file name */
if (ci->num & 4)
fd = open(t->autosave_name, O_RDONLY);
else
fd = open(t->fname, O_RDONLY);
name = t->fname;
}
if (fd < 0) {
size = 0;
t->newfile = 1;
} else {
size = lseek(fd, 0, SEEK_END);
lseek(fd, 0, SEEK_SET);
}
if (size < 0)
goto err;
if ((ci->num & 1) && t->fname && fd >= 0) {
struct stat stb;
fstat(fd, &stb);
if (stb.st_ino == t->stat.st_ino &&
stb.st_dev == t->stat.st_dev &&
stb.st_size == t->stat.st_size &&
stb.st_mtime == t->stat.st_mtime) {
if (fd != ci->num2)
close(fd);
return Efalse;
}
}
if (size > 0) {
struct mark *m;
text_cleanout(t);
alloc(c, text);
a = text_new_alloc(t, size);
if (!a)
goto err;
while (a->free < size &&
(len = read(fd, a->text + a->free, size - a->free)) > 0)
a->free += len;
c->txt = a->text;
c->attrs = NULL;
c->start = 0;
c->end = a->free;
list_add(&c->lst, &t->text);
hlist_for_each_entry(m, &t->doc.marks, all) {
m->ref.c = c;
m->ref.o = 0;
}
}
if (name) {
struct stat stb;
if (fstat(fd, &t->stat) < 0) {
t->newfile = 1;
memset(&t->stat, 0, sizeof(t->stat));
}
if (name != t->fname) {
const char *dname;
free((void*)t->fname);
t->fname = strdup(name);
dname = strrchr(name, '/');
if (dname)
dname += 1;
else
dname = name;
call("doc:set-name", ci->home, 0, NULL, dname);
}
if (!t->autosave_name)
t->autosave_name = autosave_name(name);
if (stat(t->autosave_name, &stb) == 0 &&
stb.st_mtime > t->stat.st_mtime)
t->autosave_exists = True;
}
if (ci->num & 4) {
/* restored from autoload, so nothing matches saved version */
t->saved = (void*)1;
t->file_changed = 2;
} else {
/* Current state is 'saved' */
t->saved = t->undo;
t->file_changed = 0;
}
call("doc:notify:doc:status-changed", ci->home);
pane_notify("doc:replaced", ci->home);
if (fd != ci->num2)
close(fd);
return 1;
err:
unalloc(c, text);
if (fd != ci->num2)
close(fd);
return Efallthrough;
}
DEF_CMD(text_insert_file)
{
struct text *t = ci->home->doc_data;
struct mark *pm = ci->mark, *early;
struct text_alloc *a;
int len;
int fd = ci->num;
off_t size, start;
bool first = True;
bool status_changes = (t->undo == t->saved);
if (check_readonly(ci))
return Efail;
if (!pm || fd < 0 || fd == NO_NUMERIC)
return Enoarg;
size = lseek(fd, 0, SEEK_END);
lseek(fd, 0, SEEK_SET);
if (size < 0)
return Efail;
a = t->alloc;
if (a->size - a->free < size)
a = text_new_alloc(t, size);
if (!a)
return Efail;
early = mark_dup(pm);
mark_step(early, 0);
start = a->free;
while (a->free < start + size &&
(len = read(fd, a->text + a->free, start + size - a->free)) > 0)
a->free += len;
text_add_str(t, pm, a->text + start, size, &first);
text_check_consistent(t);
text_check_autosave(ci->home);
if (status_changes)
call("doc:notify:doc:status-changed", ci->home);
pane_notify("doc:replaced", ci->home, 0, early, NULL,
0, pm);
mark_free(early);
return 1;
}
static bool do_text_output_file(struct pane *p safe, struct doc_ref *start,
struct doc_ref *end, int fd)
{
struct text *t = p->doc_data;
struct text_chunk *c;
int offset = 0;
if (start) {
c = start->c;
offset = start->o;
} else
c = list_first_entry_or_null(&t->text, struct text_chunk, lst);
list_for_each_entry_from(c, &t->text, lst) {
char *s = c->txt + c->start;
int ln = c->end - c->start;
if (end && end->c == c)
ln = end->o;
if (write(fd, s + offset, ln - offset) != ln - offset)
return False;
offset = 0;
if (end && end->c == c)
break;
}
if (fsync(fd) != 0)
return False;
return True;
}
static bool do_text_write_file(struct pane *p safe, struct doc_ref *start,
struct doc_ref *end,
const char *fname safe)
{
/* Don't worry about links for now
* Create a temp file with #basename#~, write to that,
* copy mode across, fsync and then rename
*/
struct text *t = p->doc_data;
char *tempname = malloc(strlen(fname) + 3 + 10);
const char *base;
char *tbase;
int cnt = 0;
int fd = -1;
struct stat stb;
strcpy(tempname, fname);
base = strrchr(fname, '/');
if (base)
base += 1;
else
base = fname;
tbase = tempname + (base - fname);
while (cnt < 20 && fd == -1) {
if (cnt)
sprintf(tbase, "#%s#~%d", base, cnt);
else
sprintf(tbase, "#%s#~", base);
fd = open(tempname, O_WRONLY|O_CREAT|O_EXCL, 0666);
if (fd < 0 && errno != EEXIST)
break;
cnt += 1;
}
if (fd < 0)
return False;
if (!do_text_output_file(p, start, end, fd))
goto error;
if (stat(fname, &stb) == 0 &&
S_ISREG(stb.st_mode))
/* Preserve modes, but not setuid */
fchmod(fd, stb.st_mode & 0777);
if (fname == t->fname && check_file_changed(p)) {
/* We are saving to a file which changed since we read it,
* so let's move that changed file to a backup
*/
int i;
for (i = 1 ; i < 1000; i++) {
char *new = NULL;
if (asprintf(&new, "%s~%d~", fname, i) < 0)
break;
if (link(fname, new) == 0) {
free(new);
break;
}
free(new);
if (errno != EEXIST)
break;
}
}
if (rename(tempname, fname) < 0)
goto error;
fstat(fd, &t->stat);
close(fd);
free(tempname);
return True;
error:
close(fd);
unlink(tempname);
free(tempname);
return False;
}
static void autosaves_record(struct pane *p safe, const char *path safe,
bool create)
{
DIR *d;
char *home = getenv("HOME");
char *dirname = getenv("EDLIB_AUTOSAVE");
int num;
bool changed = False;
if (!home)
home = "/tmp";
if (!dirname)
dirname = strconcat(p, home, "/.edlib_autosave");
d = opendir(dirname);
if (!d) {
if (!create)
return;
if (mkdir(dirname, 0770) < 0)
return;
d = opendir(dirname);
if (!d)
return;
num = 1;
} else {
struct dirent *de;
num = 1;
while ((de = readdir(d)) != NULL) {
char *ep = NULL;
long n;
int len;
char current[PATH_MAX];
if (de->d_name[0] == '.')
continue;
n = strtoul(de->d_name, &ep, 10);
if (!ep || ep == de->d_name || *ep != '\0')
continue;
if (n >= num)
num = n + 1;
len = readlinkat(dirfd(d), de->d_name,
current, sizeof(current));
if (len <= 0 || len >= (int)sizeof(current))
continue;
current[len] = 0;
if (strcmp(current, path) == 0) {
if (!create) {
unlinkat(dirfd(d), de->d_name, 0);
changed = True;
}
create = False;
break;
}
}
}
if (create) {
char nbuf[20];
snprintf(nbuf, sizeof(nbuf), "%d", num);
symlinkat(path, dirfd(d), nbuf);
}
if (changed) {
struct pane *doc;
doc = call_ret(pane, "doc:open", p, -1, NULL, dirname);
if (doc)
pane_call(doc, "doc:notify:doc:revisit", p);
}
closedir(d);
}
static void do_text_autosave(struct pane *p safe)
{
struct text *t = p->doc_data;
int fd = -1;
if (!t->fname)
return;
check_file_changed(p);
if (!t->autosave_name)
t->autosave_name = autosave_name(t->fname);
if (t->as.changes == 0) {
unlink(t->autosave_name);
t->autosave_exists = False;
autosaves_record(p, t->fname, False);
return;
}
fd = open(t->autosave_name, O_WRONLY|O_CREAT|O_TRUNC, 0666);
if (fd < 0)
return;
if (!do_text_output_file(p, NULL, NULL, fd)) {
close(fd);
unlink(t->autosave_name);
return;
}
t->as.changes = 0;
close(fd);
autosaves_record(p, t->fname, True);
}
DEF_CMD(text_autosave_delete)
{
struct pane *home = ci->home;
struct text *t = home->doc_data;
const char *name = ci->str;
int ret = 1;
if (!t->fname || !name)
return Enoarg;
if (!t->autosave_name)
t->autosave_name = autosave_name(t->fname);
if (strcmp(name, t->autosave_name) != 0 ||
unlink(t->autosave_name) < 0)
ret = Efail;
t->autosave_exists = False;
autosaves_record(home, t->fname, False);
return ret;
}
DEF_CMD(text_autosave_tick)
{
struct pane *home = ci->home;
struct text *t = home->doc_data;
t->as.timer_started = 0;
if (!t->fname)
return Efalse;
if (t->as.changes == 0)
/* This will delete the file */
do_text_autosave(home);
if (time(NULL) - t->as.last_change >= 30)
do_text_autosave(home);
else {
t->as.timer_started = 1;
call_comm("event:timer", home, &text_autosave_tick,
(t->as.last_change + 30 - time(NULL)) * 1000);
}
return Efalse;
}
static void text_check_autosave(struct pane *p safe)
{
struct text *t = p->doc_data;
if (t->undo == t->saved)
t->as.changes = 0;
else
t->as.changes += 1;
t->as.last_change = time(NULL);
if (!t->fname)
return;
if (t->as.changes > 300 || t->as.changes == 0)
do_text_autosave(p);
else if (!t->as.timer_started) {
t->as.timer_started = 1;
call_comm("event:timer", p, &text_autosave_tick,
30 * 1000);
}
}
DEF_CMD(text_save_file)
{
struct text *t = ci->home->doc_data;
int ret;
char *msg;
int change_status = 0;
if (!t->fname) {
asprintf(&msg, "** No file name known for %s ***", t->doc.name);
ret = Efail;
} else {
ret = do_text_write_file(ci->home, NULL, NULL, t->fname);
if (ret) {
asprintf(&msg, "Successfully wrote %s", t->fname);
t->saved = t->undo;
change_status = 1;
t->file_changed = 0;
t->newfile = 0;
} else
asprintf(&msg, "*** Failed to write %s ***", t->fname);
}
call("Message", ci->focus, 0, NULL, msg);
free(msg);
if (change_status)
call("doc:notify:doc:status-changed", ci->home);
text_check_autosave(ci->home);
if (ret == 0)
return 1;
return Efail;
}
DEF_CMD(text_write_file)
{
int ret;
bool use_marks = ci->mark && ci->mark2;
if (ci->str) {
ret = do_text_write_file(ci->home,
use_marks ? &ci->mark->ref: NULL,
use_marks ? &ci->mark2->ref: NULL,
ci->str);
return ret ? 1 : Efail;
}
if (ci->num >= 0 && ci->num != NO_NUMERIC) {
ret = do_text_output_file(ci->home,
use_marks ? &ci->mark->ref: NULL,
use_marks ? &ci->mark2->ref: NULL,
ci->num);
return ret ? 1 : Efail;
}
return Enoarg;
}
DEF_CMD(text_same_file)
{
struct text *t = ci->home->doc_data;
struct stat stb, stb2;
int fd = ci->num2;
if (t->fname == NULL)
return Efallthrough;
if (ci->str && strcmp(ci->str, t->fname) == 0)
return 1;
if (fd >= 0) {
if (fstat(fd, &stb) != 0)
return Efallthrough;
} else if (ci->str) {
if (stat(ci->str, &stb) != 0)
return Efallthrough;
} else
return Efallthrough;
if (t->stat.st_ino != stb.st_ino ||
t->stat.st_dev != stb.st_dev)
return Efallthrough;
/* Must check file hasn't changed beneath us */
if (stat(t->fname, &stb2) != 0)
stb2.st_ino = 0;
if (stb2.st_ino == stb.st_ino &&
stb2.st_dev == stb.st_dev)
return 1;
return Efallthrough;
}
static void text_add_edit(struct text *t safe, struct text_chunk *target safe,
bool *first safe, int at_start, int len)
{
struct text_edit *e;
if (len == 0)
return;
if (t->saved == t->undo)
/* Must never merge undo entries across a save point */
*first = 1;
if (t->redo) {
/* Cannot add an edit before some redo edits, as they
* will get confused. We need to record the redo history
* here in the undo history, possibly allocating
* a nop edit (len == 0)
*/
if (t->undo == NULL || t->undo->altnext != NULL) {
alloc(e, undo);
e->target = target; /* ignored */
e->first = 0;
e->at_start = 0;
e->len = 0; /* This is a no-op */
e->next = t->undo;
t->undo = e;
}
t->undo->altnext = t->redo;
t->undo->alt_is_second = 0;
t->redo = NULL;
}
/* factoring out t->undo here avoids a bug in smatch. */
e = t->undo;
if (e && e->len != 0 && e->len + len != 0 && !*first &&
e->target == target && e->at_start == at_start) {
/* This new edit can be merged with the previous one */
e->len += len;
} else {
alloc(e, undo);
e->target = target;
e->first = *first;
e->at_start = at_start;
e->len = len;
*first = 0;
e->next = t->undo;
e->altnext = NULL;
e->alt_is_second = 0;
t->undo = e;
}
}
static void _text_add_str(struct text *t safe, struct doc_ref *pos safe,
const char *str safe, off_t len,
struct doc_ref *start, bool *first_edit safe)
{
/* Text is added to the end of the referenced chunk, or
* in new chunks which are added afterwards. This allows
* the caller to reliably updated any pointers to accommodate
* changes.
* The added text has no attributes.
*
* 'pos' is moved to point to the end of the inserted text.
* 'start' is set to point to the start which may be the
* original 'pos', or may not if a chunk was inserted.
*/
/* easy/common case first: pos is at the end of a chunk,
* which is the last chunk in the current allocation.
*/
struct text_alloc *a = t->alloc;
off_t len2;
off_t orig_len;
if (len < 0)
len = strlen(str);
orig_len = len;
if (start)
*start = *pos;
len2 = len;
if (pos->c && pos->o == pos->c->end &&
pos->c->txt + pos->o == a->text + a->free &&
str != a->text + a->free &&
(a->size - a->free >= len ||
(len2 = utf8_round_len(str, a->size - a->free)) > 0)) {
/* Some of this ('len2') can be added to the current chunk */
memcpy(a->text+a->free, str, len2);
a->free += len2;
pos->c->end += len2;
pos->o += len2;
str += len2;
text_add_edit(t, pos->c, first_edit, 0, len2);
len -= len2;
}
if (!len)
return;
/* Need a new chunk. Might need to split the current chunk first.
* Old chunk must be first to simplify updating of pointers */
if (pos->c == NULL || pos->o < pos->c->end) {
struct text_chunk *c;
alloc(c, text);
if (pos->c == NULL || pos->o == pos->c->start) {
/* At the start of a chunk, so create a new one here */
c->txt = safe_cast NULL;
c->start = c->end = 0;
c->attrs = NULL;
if (pos->c)
list_add_tail(&c->lst, &pos->c->lst);
else
list_add_tail(&c->lst, &t->text);
if (start && start->c == pos->c && start->o == pos->o) {
start->c = c;
start->o = c->start;
}
pos->c = c;
pos->o = c->start;
} else {
/* Not at the start, so we need to split at pos->o */
c->txt = pos->c->txt;
c->start = pos->o;
c->end = pos->c->end;
c->attrs = attr_copy_tail(pos->c->attrs, c->start);
pos->c->end = pos->o;
attr_trim(&pos->c->attrs, pos->c->end);
list_add(&c->lst, &pos->c->lst);
text_add_edit(t, c, first_edit, 0, c->end - c->start);
/* this implicitly truncates pos->c, so don't need
* to record that. */
}
}
while (len > 0) {
/* Make sure we have an empty chunk */
if (pos->c->end > pos->c->start) {
struct text_chunk *c;
alloc(c, text);
c->start = c->end = 0;
c->attrs = NULL;
list_add(&c->lst, &pos->c->lst);
if (start && start->c == pos->c && start->o == pos->o) {
start->c = c;
start->o = 0;
}
pos->c = c;
pos->o = c->start;
}
/* Make sure we have some space in 'a' */
len2 = len;
if (a->size - a->free < len &&
(len2 = utf8_round_len(str, a->size - a->free)) == 0) {
if (orig_len < 128 ||
t->alloc->size < DEFAULT_SIZE)
a = text_new_alloc(t, DEFAULT_SIZE);
else if (len > DEFAULT_SIZE && len > t->alloc->size)
a = text_new_alloc(t, ((len +256) | 4095) + 1 - 256);
else if (t->alloc->size * 2 < MAX_SIZE)
a = text_new_alloc(t, t->alloc->size * 2);
else
a = text_new_alloc(t, MAX_SIZE);
len2 = len;
if (len2 > a->size)
len2 = utf8_round_len(str, a->size);
}
pos->c->txt = a->text + a->free;
pos->c->end = len2;
pos->o = len2;
if (str != pos->c->txt)
memcpy(pos->c->txt, str, len2);
text_add_edit(t, pos->c, first_edit, 0, len2);
a->free += len2;
str += len2;
len -= len2;
}
}
/* Text insertion, deletion, and undo can modify chunks which various
* marks point to - so those marks will need to be updated.
* Modification include splitting a chunk, inserting chunks,
* or deleting chunks and recombining chunks (for undo).
* Also reducing or increasing the range of a chunk.
* When a chunk is split, the original becomes the first part.
* So any mark pointing past the end of that original must be moved
* to the new chunk.
* When a chunk is deleted, any mark pointing to a deleted chunk
* must be redirected to the (new) point of deletion.
* When a chunk is inserted, marks before the insertion mark must remain
* before the inserted chunk, marks after must remain after the insertion
* point.
* When two chunks are recombined it will appear that the second chunk
* was deleted. In this case though, references to the second chunk need
* to be repositioned in the first.
* When range is reduced, offset must be moved back into range.
* When range is increased, and this mark is after change, offset in this mark
* need to line up with changed point.
*
* So text_update_prior_after_change() is called on marks before the
* mark-of-change in reverse order until the function returns zero.
* If it finds a mark pointing to a deleted chunk, that mark changes to
* point the same place as the mark-of-change.
* If it finds a mark at, or immediately after, the mark-of-change,
* that mark is moved to point to the start of insert.
*
* Then text_update_following_after_change() is called on marks after
* the mark-of-change in order until that function returns zero.
* If a mark points outside the range of a chunk, the other half of the
* chunk is found (by walking forward) and the pointer is updated.
* If a deleted chunk is found, that mark is redirected to the mark-of-change.
* If a location at the start is found, it is move to the end.
*/
static int text_update_prior_after_change(struct text *t safe,
struct doc_ref *pos safe,
struct doc_ref *spos safe,
struct doc_ref *epos safe)
{
int ret = 1;
if (pos->c == NULL)