text: rename text_sigbus to text_mmaped
[vis.git] / text.c
blob291cc3a24bca3f264e31db9e1edf5df7fdd001da
1 #ifndef _GNU_SOURCE
2 #define _GNU_SOURCE /* memrchr(3) is non-standard */
3 #endif
4 #include <unistd.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8 #include <time.h>
9 #include <fcntl.h>
10 #include <errno.h>
11 #include <wchar.h>
12 #include <stdint.h>
13 #include <libgen.h>
14 #include <limits.h>
15 #include <sys/types.h>
16 #include <sys/stat.h>
17 #include <sys/mman.h>
18 #if CONFIG_ACL
19 #include <sys/acl.h>
20 #endif
21 #if CONFIG_SELINUX
22 #include <selinux/selinux.h>
23 #endif
25 #include "text.h"
26 #include "text-util.h"
27 #include "text-motions.h"
28 #include "util.h"
30 /* Allocate blocks holding the actual file content in junks of size: */
31 #ifndef BLOCK_SIZE
32 #define BLOCK_SIZE (1 << 20)
33 #endif
34 /* Files smaller than this value are copied on load, larger ones are mmap(2)-ed
35 * directely. Hence the former can be truncated, while doing so on the latter
36 * results in havoc. */
37 #define BLOCK_MMAP_SIZE (1 << 23)
39 /* Block holding the file content, either readonly mmap(2)-ed from the original
40 * file or heap allocated to store the modifications.
42 typedef struct Block Block;
43 struct Block {
44 size_t size; /* maximal capacity */
45 size_t len; /* current used length / insertion position */
46 char *data; /* actual data */
47 enum { /* type of allocation */
48 MMAP_ORIG, /* mmap(2)-ed from an external file */
49 MMAP, /* mmap(2)-ed from a temporary file only known to this process */
50 MALLOC, /* heap allocated block using malloc(3) */
51 } type;
52 Block *next; /* next junk */
55 /* A piece holds a reference (but doesn't itself store) a certain amount of data.
56 * All active pieces chained together form the whole content of the document.
57 * At the beginning there exists only one piece, spanning the whole document.
58 * Upon insertion/deletion new pieces will be created to represent the changes.
59 * Generally pieces are never destroyed, but kept around to peform undo/redo
60 * operations.
62 struct Piece {
63 Text *text; /* text to which this piece belongs */
64 Piece *prev, *next; /* pointers to the logical predecessor/successor */
65 Piece *global_prev; /* double linked list in order of allocation, */
66 Piece *global_next; /* used to free individual pieces */
67 const char *data; /* pointer into a Block holding the data */
68 size_t len; /* the length in number of bytes of the data */
71 /* used to transform a global position (byte offset starting from the beginning
72 * of the text) into an offset relative to a piece.
74 typedef struct {
75 Piece *piece; /* piece holding the location */
76 size_t off; /* offset into the piece in bytes */
77 } Location;
79 /* A Span holds a certain range of pieces. Changes to the document are always
80 * performed by swapping out an existing span with a new one.
82 typedef struct {
83 Piece *start, *end; /* start/end of the span */
84 size_t len; /* the sum of the lengths of the pieces which form this span */
85 } Span;
87 /* A Change keeps all needed information to redo/undo an insertion/deletion. */
88 typedef struct Change Change;
89 struct Change {
90 Span old; /* all pieces which are being modified/swapped out by the change */
91 Span new; /* all pieces which are introduced/swapped in by the change */
92 size_t pos; /* absolute position at which the change occured */
93 Change *next; /* next change which is part of the same revision */
94 Change *prev; /* previous change which is part of the same revision */
97 /* A Revision is a list of Changes which are used to undo/redo all modifications
98 * since the last snapshot operation. Revisions are stored in a directed graph structure.
100 typedef struct Revision Revision;
101 struct Revision {
102 Change *change; /* the most recent change */
103 Revision *next; /* the next (child) revision in the undo tree */
104 Revision *prev; /* the previous (parent) revision in the undo tree */
105 Revision *earlier; /* the previous Revision, chronologically */
106 Revision *later; /* the next Revision, chronologically */
107 time_t time; /* when the first change of this revision was performed */
108 size_t seq; /* a unique, strictly increasing identifier */
111 typedef struct {
112 size_t pos; /* position in bytes from start of file */
113 size_t lineno; /* line number in file i.e. number of '\n' in [0, pos) */
114 } LineCache;
116 /* The main struct holding all information of a given file */
117 struct Text {
118 Block *block; /* original file content at the time of load operation */
119 Block *blocks; /* all blocks which have been allocated to hold insertion data */
120 Piece *pieces; /* all pieces which have been allocated, used to free them */
121 Piece *cache; /* most recently modified piece */
122 Piece begin, end; /* sentinel nodes which always exists but don't hold any data */
123 Revision *history; /* undo tree */
124 Revision *current_revision; /* revision holding all file changes until a snapshot is performed */
125 Revision *last_revision; /* the last revision added to the tree, chronologically */
126 Revision *saved_revision; /* the last revision at the time of the save operation */
127 size_t size; /* current file content size in bytes */
128 struct stat info; /* stat as probed at load time */
129 LineCache lines; /* mapping between absolute pos in bytes and logical line breaks */
132 struct TextSave { /* used to hold context between text_save_{begin,commit} calls */
133 Text *txt; /* text to operate on */
134 char *filename; /* filename to save to as given to text_save_begin */
135 char *tmpname; /* temporary name used for atomic rename(2) */
136 int fd; /* file descriptor to write data to using text_save_write */
137 enum TextSaveMethod type; /* method used to save file */
140 /* block management */
141 static Block *block_alloc(Text*, size_t size);
142 static Block *block_read(Text*, size_t size, int fd);
143 static Block *block_mmap(Text*, size_t size, int fd, off_t offset);
144 static void block_free(Block*);
145 static bool block_capacity(Block*, size_t len);
146 static const char *block_append(Block*, const char *data, size_t len);
147 static bool block_insert(Block*, size_t pos, const char *data, size_t len);
148 static bool block_delete(Block*, size_t pos, size_t len);
149 static const char *block_store(Text*, const char *data, size_t len);
150 /* cache layer */
151 static void cache_piece(Text *txt, Piece *p);
152 static bool cache_contains(Text *txt, Piece *p);
153 static bool cache_insert(Text *txt, Piece *p, size_t off, const char *data, size_t len);
154 static bool cache_delete(Text *txt, Piece *p, size_t off, size_t len);
155 /* piece management */
156 static Piece *piece_alloc(Text *txt);
157 static void piece_free(Piece *p);
158 static void piece_init(Piece *p, Piece *prev, Piece *next, const char *data, size_t len);
159 static Location piece_get_intern(Text *txt, size_t pos);
160 static Location piece_get_extern(Text *txt, size_t pos);
161 /* span management */
162 static void span_init(Span *span, Piece *start, Piece *end);
163 static void span_swap(Text *txt, Span *old, Span *new);
164 /* change management */
165 static Change *change_alloc(Text *txt, size_t pos);
166 static void change_free(Change *c);
167 /* revision management */
168 static Revision *revision_alloc(Text *txt);
169 static void revision_free(Revision *rev);
170 /* logical line counting cache */
171 static void lineno_cache_invalidate(LineCache *cache);
172 static size_t lines_skip_forward(Text *txt, size_t pos, size_t lines, size_t *lines_skiped);
173 static size_t lines_count(Text *txt, size_t pos, size_t len);
175 static ssize_t write_all(int fd, const char *buf, size_t count) {
176 size_t rem = count;
177 while (rem > 0) {
178 ssize_t written = write(fd, buf, rem);
179 if (written < 0) {
180 if (errno == EAGAIN || errno == EINTR)
181 continue;
182 return -1;
183 } else if (written == 0) {
184 break;
186 rem -= written;
187 buf += written;
189 return count - rem;
192 /* allocate a new block of MAX(size, BLOCK_SIZE) bytes */
193 static Block *block_alloc(Text *txt, size_t size) {
194 Block *blk = calloc(1, sizeof *blk);
195 if (!blk)
196 return NULL;
197 if (BLOCK_SIZE > size)
198 size = BLOCK_SIZE;
199 if (!(blk->data = malloc(size))) {
200 free(blk);
201 return NULL;
203 blk->type = MALLOC;
204 blk->size = size;
205 blk->next = txt->blocks;
206 txt->blocks = blk;
207 return blk;
210 static Block *block_read(Text *txt, size_t size, int fd) {
211 Block *blk = block_alloc(txt, size);
212 if (!blk)
213 return NULL;
214 while (size > 0) {
215 char data[4096];
216 ssize_t len = read(fd, data, MIN(sizeof(data), size));
217 if (len == -1) {
218 txt->blocks = blk->next;
219 block_free(blk);
220 return NULL;
221 } else if (len == 0) {
222 break;
223 } else {
224 block_append(blk, data, len);
225 size -= len;
228 return blk;
231 static Block *block_mmap(Text *txt, size_t size, int fd, off_t offset) {
232 Block *blk = calloc(1, sizeof *blk);
233 if (!blk)
234 return NULL;
235 if (size) {
236 blk->data = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, offset);
237 if (blk->data == MAP_FAILED) {
238 free(blk);
239 return NULL;
242 blk->type = MMAP_ORIG;
243 blk->size = size;
244 blk->len = size;
245 blk->next = txt->blocks;
246 txt->blocks = blk;
247 return blk;
250 static void block_free(Block *blk) {
251 if (!blk)
252 return;
253 if (blk->type == MALLOC)
254 free(blk->data);
255 else if ((blk->type == MMAP_ORIG || blk->type == MMAP) && blk->data)
256 munmap(blk->data, blk->size);
257 free(blk);
260 /* check whether block has enough free space to store len bytes */
261 static bool block_capacity(Block *blk, size_t len) {
262 return blk->size - blk->len >= len;
265 /* append data to block, assumes there is enough space available */
266 static const char *block_append(Block *blk, const char *data, size_t len) {
267 char *dest = memcpy(blk->data + blk->len, data, len);
268 blk->len += len;
269 return dest;
272 /* stores the given data in a block, allocates a new one if necessary. returns
273 * a pointer to the storage location or NULL if allocation failed. */
274 static const char *block_store(Text *txt, const char *data, size_t len) {
275 Block *blk = txt->blocks;
276 if ((!blk || !block_capacity(blk, len)) && !(blk = block_alloc(txt, len)))
277 return NULL;
278 return block_append(blk, data, len);
281 /* insert data into block at an arbitrary position, this should only be used with
282 * data of the most recently created piece. */
283 static bool block_insert(Block *blk, size_t pos, const char *data, size_t len) {
284 if (pos > blk->len || !block_capacity(blk, len))
285 return false;
286 if (blk->len == pos)
287 return block_append(blk, data, len);
288 char *insert = blk->data + pos;
289 memmove(insert + len, insert, blk->len - pos);
290 memcpy(insert, data, len);
291 blk->len += len;
292 return true;
295 /* delete data from a block at an arbitrary position, this should only be used with
296 * data of the most recently created piece. */
297 static bool block_delete(Block *blk, size_t pos, size_t len) {
298 size_t end;
299 if (!addu(pos, len, &end) || end > blk->len)
300 return false;
301 if (blk->len == pos) {
302 blk->len -= len;
303 return true;
305 char *delete = blk->data + pos;
306 memmove(delete, delete + len, blk->len - pos - len);
307 blk->len -= len;
308 return true;
311 /* cache the given piece if it is the most recently changed one */
312 static void cache_piece(Text *txt, Piece *p) {
313 Block *blk = txt->blocks;
314 if (!blk || p->data < blk->data || p->data + p->len != blk->data + blk->len)
315 return;
316 txt->cache = p;
319 /* check whether the given piece was the most recently modified one */
320 static bool cache_contains(Text *txt, Piece *p) {
321 Block *blk = txt->blocks;
322 Revision *rev = txt->current_revision;
323 if (!blk || !txt->cache || txt->cache != p || !rev || !rev->change)
324 return false;
326 Piece *start = rev->change->new.start;
327 Piece *end = rev->change->new.end;
328 bool found = false;
329 for (Piece *cur = start; !found; cur = cur->next) {
330 if (cur == p)
331 found = true;
332 if (cur == end)
333 break;
336 return found && p->data + p->len == blk->data + blk->len;
339 /* try to insert a junk of data at a given piece offset. the insertion is only
340 * performed if the piece is the most recenetly changed one. the legnth of the
341 * piece, the span containing it and the whole text is adjusted accordingly */
342 static bool cache_insert(Text *txt, Piece *p, size_t off, const char *data, size_t len) {
343 if (!cache_contains(txt, p))
344 return false;
345 Block *blk = txt->blocks;
346 size_t bufpos = p->data + off - blk->data;
347 if (!block_insert(blk, bufpos, data, len))
348 return false;
349 p->len += len;
350 txt->current_revision->change->new.len += len;
351 txt->size += len;
352 return true;
355 /* try to delete a junk of data at a given piece offset. the deletion is only
356 * performed if the piece is the most recenetly changed one and the whole
357 * affected range lies within it. the legnth of the piece, the span containing it
358 * and the whole text is adjusted accordingly */
359 static bool cache_delete(Text *txt, Piece *p, size_t off, size_t len) {
360 if (!cache_contains(txt, p))
361 return false;
362 Block *blk = txt->blocks;
363 size_t end;
364 size_t bufpos = p->data + off - blk->data;
365 if (!addu(off, len, &end) || end > p->len || !block_delete(blk, bufpos, len))
366 return false;
367 p->len -= len;
368 txt->current_revision->change->new.len -= len;
369 txt->size -= len;
370 return true;
373 /* initialize a span and calculate its length */
374 static void span_init(Span *span, Piece *start, Piece *end) {
375 size_t len = 0;
376 span->start = start;
377 span->end = end;
378 for (Piece *p = start; p; p = p->next) {
379 len += p->len;
380 if (p == end)
381 break;
383 span->len = len;
386 /* swap out an old span and replace it with a new one.
388 * - if old is an empty span do not remove anything, just insert the new one
389 * - if new is an empty span do not insert anything, just remove the old one
391 * adjusts the document size accordingly.
393 static void span_swap(Text *txt, Span *old, Span *new) {
394 if (old->len == 0 && new->len == 0) {
395 return;
396 } else if (old->len == 0) {
397 /* insert new span */
398 new->start->prev->next = new->start;
399 new->end->next->prev = new->end;
400 } else if (new->len == 0) {
401 /* delete old span */
402 old->start->prev->next = old->end->next;
403 old->end->next->prev = old->start->prev;
404 } else {
405 /* replace old with new */
406 old->start->prev->next = new->start;
407 old->end->next->prev = new->end;
409 txt->size -= old->len;
410 txt->size += new->len;
413 /* Allocate a new revision and place it in the revision graph.
414 * All further changes will be associated with this revision. */
415 static Revision *revision_alloc(Text *txt) {
416 Revision *rev = calloc(1, sizeof *rev);
417 if (!rev)
418 return NULL;
419 rev->time = time(NULL);
420 txt->current_revision = rev;
422 /* set sequence number */
423 if (!txt->last_revision)
424 rev->seq = 0;
425 else
426 rev->seq = txt->last_revision->seq + 1;
428 /* set earlier, later pointers */
429 if (txt->last_revision)
430 txt->last_revision->later = rev;
431 rev->earlier = txt->last_revision;
433 if (!txt->history) {
434 txt->history = rev;
435 return rev;
438 /* set prev, next pointers */
439 rev->prev = txt->history;
440 txt->history->next = rev;
441 txt->history = rev;
442 return rev;
445 static void revision_free(Revision *rev) {
446 if (!rev)
447 return;
448 for (Change *next, *c = rev->change; c; c = next) {
449 next = c->next;
450 change_free(c);
452 free(rev);
455 static Piece *piece_alloc(Text *txt) {
456 Piece *p = calloc(1, sizeof *p);
457 if (!p)
458 return NULL;
459 p->text = txt;
460 p->global_next = txt->pieces;
461 if (txt->pieces)
462 txt->pieces->global_prev = p;
463 txt->pieces = p;
464 return p;
467 static void piece_free(Piece *p) {
468 if (!p)
469 return;
470 if (p->global_prev)
471 p->global_prev->global_next = p->global_next;
472 if (p->global_next)
473 p->global_next->global_prev = p->global_prev;
474 if (p->text->pieces == p)
475 p->text->pieces = p->global_next;
476 if (p->text->cache == p)
477 p->text->cache = NULL;
478 free(p);
481 static void piece_init(Piece *p, Piece *prev, Piece *next, const char *data, size_t len) {
482 p->prev = prev;
483 p->next = next;
484 p->data = data;
485 p->len = len;
488 /* returns the piece holding the text at byte offset pos. if pos happens to
489 * be at a piece boundry i.e. the first byte of a piece then the previous piece
490 * to the left is returned with an offset of piece->len. this is convenient for
491 * modifications to the piece chain where both pieces (the returned one and the
492 * one following it) are needed, but unsuitable as a public interface.
494 * in particular if pos is zero, the begin sentinel piece is returned.
496 static Location piece_get_intern(Text *txt, size_t pos) {
497 size_t cur = 0;
498 for (Piece *p = &txt->begin; p->next; p = p->next) {
499 if (cur <= pos && pos <= cur + p->len)
500 return (Location){ .piece = p, .off = pos - cur };
501 cur += p->len;
504 return (Location){ 0 };
507 /* similiar to piece_get_intern but usable as a public API. returns the piece
508 * holding the text at byte offset pos. never returns a sentinel piece.
509 * it pos is the end of file (== text_size()) and the file is not empty then
510 * the last piece holding data is returned.
512 static Location piece_get_extern(Text *txt, size_t pos) {
513 size_t cur = 0;
514 Piece *p;
516 for (p = txt->begin.next; p->next; p = p->next) {
517 if (cur <= pos && pos < cur + p->len)
518 return (Location){ .piece = p, .off = pos - cur };
519 cur += p->len;
522 if (cur == pos)
523 return (Location){ .piece = p->prev, .off = p->prev->len };
525 return (Location){ 0 };
528 /* allocate a new change, associate it with current revision or a newly
529 * allocated one if none exists. */
530 static Change *change_alloc(Text *txt, size_t pos) {
531 Revision *rev = txt->current_revision;
532 if (!rev) {
533 rev = revision_alloc(txt);
534 if (!rev)
535 return NULL;
537 Change *c = calloc(1, sizeof *c);
538 if (!c)
539 return NULL;
540 c->pos = pos;
541 c->next = rev->change;
542 if (rev->change)
543 rev->change->prev = c;
544 rev->change = c;
545 return c;
548 static void change_free(Change *c) {
549 if (!c)
550 return;
551 /* only free the new part of the span, the old one is still in use */
552 if (c->new.start != c->new.end)
553 piece_free(c->new.end);
554 piece_free(c->new.start);
555 free(c);
558 /* When inserting new data there are 2 cases to consider.
560 * - in the first the insertion point falls into the middle of an exisiting
561 * piece which is replaced by three new pieces:
563 * /-+ --> +---------------+ --> +-\
564 * | | | existing text | | |
565 * \-+ <-- +---------------+ <-- +-/
567 * Insertion point for "demo "
569 * /-+ --> +---------+ --> +-----+ --> +-----+ --> +-\
570 * | | | existing| |demo | |text | | |
571 * \-+ <-- +---------+ <-- +-----+ <-- +-----+ <-- +-/
573 * - the second case deals with an insertion point at a piece boundry:
575 * /-+ --> +---------------+ --> +-\
576 * | | | existing text | | |
577 * \-+ <-- +---------------+ <-- +-/
579 * Insertion point for "short"
581 * /-+ --> +-----+ --> +---------------+ --> +-\
582 * | | |short| | existing text | | |
583 * \-+ <-- +-----+ <-- +---------------+ <-- +-/
585 bool text_insert(Text *txt, size_t pos, const char *data, size_t len) {
586 if (len == 0)
587 return true;
588 if (pos > txt->size)
589 return false;
590 if (pos < txt->lines.pos)
591 lineno_cache_invalidate(&txt->lines);
593 Location loc = piece_get_intern(txt, pos);
594 Piece *p = loc.piece;
595 if (!p)
596 return false;
597 size_t off = loc.off;
598 if (cache_insert(txt, p, off, data, len))
599 return true;
601 Change *c = change_alloc(txt, pos);
602 if (!c)
603 return false;
605 if (!(data = block_store(txt, data, len)))
606 return false;
608 Piece *new = NULL;
610 if (off == p->len) {
611 /* insert between two existing pieces, hence there is nothing to
612 * remove, just add a new piece holding the extra text */
613 if (!(new = piece_alloc(txt)))
614 return false;
615 piece_init(new, p, p->next, data, len);
616 span_init(&c->new, new, new);
617 span_init(&c->old, NULL, NULL);
618 } else {
619 /* insert into middle of an existing piece, therfore split the old
620 * piece. that is we have 3 new pieces one containing the content
621 * before the insertion point then one holding the newly inserted
622 * text and one holding the content after the insertion point.
624 Piece *before = piece_alloc(txt);
625 new = piece_alloc(txt);
626 Piece *after = piece_alloc(txt);
627 if (!before || !new || !after)
628 return false;
629 piece_init(before, p->prev, new, p->data, off);
630 piece_init(new, before, after, data, len);
631 piece_init(after, new, p->next, p->data + off, p->len - off);
633 span_init(&c->new, before, after);
634 span_init(&c->old, p, p);
637 cache_piece(txt, new);
638 span_swap(txt, &c->old, &c->new);
639 return true;
642 static bool text_vprintf(Text *txt, size_t pos, const char *format, va_list ap) {
643 va_list ap_save;
644 va_copy(ap_save, ap);
645 int len = vsnprintf(NULL, 0, format, ap);
646 if (len == -1) {
647 va_end(ap_save);
648 return false;
650 char *buf = malloc(len+1);
651 bool ret = buf && (vsnprintf(buf, len+1, format, ap_save) == len) && text_insert(txt, pos, buf, len);
652 free(buf);
653 va_end(ap_save);
654 return ret;
657 bool text_appendf(Text *txt, const char *format, ...) {
658 va_list ap;
659 va_start(ap, format);
660 bool ret = text_vprintf(txt, text_size(txt), format, ap);
661 va_end(ap);
662 return ret;
665 bool text_printf(Text *txt, size_t pos, const char *format, ...) {
666 va_list ap;
667 va_start(ap, format);
668 bool ret = text_vprintf(txt, pos, format, ap);
669 va_end(ap);
670 return ret;
673 size_t text_insert_newline(Text *txt, size_t pos) {
674 return text_insert(txt, pos, "\n", 1) ? 1 : 0;
677 static size_t revision_undo(Text *txt, Revision *rev) {
678 size_t pos = EPOS;
679 for (Change *c = rev->change; c; c = c->next) {
680 span_swap(txt, &c->new, &c->old);
681 pos = c->pos;
683 return pos;
686 static size_t revision_redo(Text *txt, Revision *rev) {
687 size_t pos = EPOS;
688 Change *c = rev->change;
689 while (c->next)
690 c = c->next;
691 for ( ; c; c = c->prev) {
692 span_swap(txt, &c->old, &c->new);
693 pos = c->pos;
694 if (c->new.len > c->old.len)
695 pos += c->new.len - c->old.len;
697 return pos;
700 size_t text_undo(Text *txt) {
701 size_t pos = EPOS;
702 /* taking rev snapshot makes sure that txt->current_revision is reset */
703 text_snapshot(txt);
704 Revision *rev = txt->history->prev;
705 if (!rev)
706 return pos;
707 pos = revision_undo(txt, txt->history);
708 txt->history = rev;
709 lineno_cache_invalidate(&txt->lines);
710 return pos;
713 size_t text_redo(Text *txt) {
714 size_t pos = EPOS;
715 /* taking a snapshot makes sure that txt->current_revision is reset */
716 text_snapshot(txt);
717 Revision *rev = txt->history->next;
718 if (!rev)
719 return pos;
720 pos = revision_redo(txt, rev);
721 txt->history = rev;
722 lineno_cache_invalidate(&txt->lines);
723 return pos;
726 static bool history_change_branch(Revision *rev) {
727 bool changed = false;
728 while (rev->prev) {
729 if (rev->prev->next != rev) {
730 rev->prev->next = rev;
731 changed = true;
733 rev = rev->prev;
735 return changed;
738 static size_t history_traverse_to(Text *txt, Revision *rev) {
739 size_t pos = EPOS;
740 if (!rev)
741 return pos;
742 bool changed = history_change_branch(rev);
743 if (!changed) {
744 if (rev->seq == txt->history->seq) {
745 return txt->lines.pos;
746 } else if (rev->seq > txt->history->seq) {
747 while (txt->history != rev)
748 pos = text_redo(txt);
749 return pos;
750 } else if (rev->seq < txt->history->seq) {
751 while (txt->history != rev)
752 pos = text_undo(txt);
753 return pos;
755 } else {
756 while (txt->history->prev && txt->history->prev->next == txt->history)
757 text_undo(txt);
758 pos = text_undo(txt);
759 while (txt->history != rev)
760 pos = text_redo(txt);
761 return pos;
763 return pos;
766 size_t text_earlier(Text *txt, int count) {
767 Revision *rev = txt->history;
768 while (count-- > 0 && rev->earlier)
769 rev = rev->earlier;
770 return history_traverse_to(txt, rev);
773 size_t text_later(Text *txt, int count) {
774 Revision *rev = txt->history;
775 while (count-- > 0 && rev->later)
776 rev = rev->later;
777 return history_traverse_to(txt, rev);
780 size_t text_restore(Text *txt, time_t time) {
781 Revision *rev = txt->history;
782 while (time < rev->time && rev->earlier)
783 rev = rev->earlier;
784 while (time > rev->time && rev->later)
785 rev = rev->later;
786 time_t diff = labs(rev->time - time);
787 if (rev->earlier && rev->earlier != txt->history && labs(rev->earlier->time - time) < diff)
788 rev = rev->earlier;
789 if (rev->later && rev->later != txt->history && labs(rev->later->time - time) < diff)
790 rev = rev->later;
791 return history_traverse_to(txt, rev);
794 time_t text_state(Text *txt) {
795 return txt->history->time;
798 static bool preserve_acl(int src, int dest) {
799 #if CONFIG_ACL
800 acl_t acl = acl_get_fd(src);
801 if (!acl)
802 return errno == ENOTSUP ? true : false;
803 if (acl_set_fd(dest, acl) == -1) {
804 acl_free(acl);
805 return false;
807 acl_free(acl);
808 #endif /* CONFIG_ACL */
809 return true;
812 static bool preserve_selinux_context(int src, int dest) {
813 #if CONFIG_SELINUX
814 char *context = NULL;
815 if (!is_selinux_enabled())
816 return true;
817 if (fgetfilecon(src, &context) == -1)
818 return errno == ENOTSUP ? true : false;
819 if (fsetfilecon(dest, context) == -1) {
820 freecon(context);
821 return false;
823 freecon(context);
824 #endif /* CONFIG_SELINUX */
825 return true;
828 /* Create a new file named `filename~` and try to preserve all important
829 * meta data. After the file content has been written to this temporary
830 * file, text_save_commit_atomic will atomically move it to its final
831 * (possibly already existing) destination using rename(2).
833 * This approach does not work if:
835 * - the file is a symbolic link
836 * - the file is a hard link
837 * - file ownership can not be preserved
838 * - file group can not be preserved
839 * - directory permissions do not allow creation of a new file
840 * - POSXI ACL can not be preserved (if enabled)
841 * - SELinux security context can not be preserved (if enabled)
843 static bool text_save_begin_atomic(TextSave *ctx) {
844 int oldfd, saved_errno;
845 if ((oldfd = open(ctx->filename, O_RDONLY)) == -1 && errno != ENOENT)
846 goto err;
847 struct stat oldmeta = { 0 };
848 if (oldfd != -1 && lstat(ctx->filename, &oldmeta) == -1)
849 goto err;
850 if (oldfd != -1) {
851 if (S_ISLNK(oldmeta.st_mode)) /* symbolic link */
852 goto err;
853 if (oldmeta.st_nlink > 1) /* hard link */
854 goto err;
857 size_t namelen = strlen(ctx->filename) + 1 /* ~ */ + 1 /* \0 */;
858 if (!(ctx->tmpname = calloc(1, namelen)))
859 goto err;
860 snprintf(ctx->tmpname, namelen, "%s~", ctx->filename);
862 if ((ctx->fd = open(ctx->tmpname, O_CREAT|O_WRONLY|O_TRUNC, oldfd == -1 ? 0666 : oldmeta.st_mode)) == -1)
863 goto err;
864 if (oldfd != -1) {
865 if (!preserve_acl(oldfd, ctx->fd) || !preserve_selinux_context(oldfd, ctx->fd))
866 goto err;
867 /* change owner if necessary */
868 if (oldmeta.st_uid != getuid() && fchown(ctx->fd, oldmeta.st_uid, (uid_t)-1) == -1)
869 goto err;
870 /* change group if necessary, in case of failure some editors reset
871 * the group permissions to the same as for others */
872 if (oldmeta.st_gid != getgid() && fchown(ctx->fd, (uid_t)-1, oldmeta.st_gid) == -1)
873 goto err;
874 close(oldfd);
877 ctx->type = TEXT_SAVE_ATOMIC;
878 return true;
879 err:
880 saved_errno = errno;
881 if (oldfd != -1)
882 close(oldfd);
883 if (ctx->fd != -1)
884 close(ctx->fd);
885 ctx->fd = -1;
886 errno = saved_errno;
887 return false;
890 static bool text_save_commit_atomic(TextSave *ctx) {
891 if (fsync(ctx->fd) == -1)
892 return false;
894 struct stat meta = { 0 };
895 if (fstat(ctx->fd, &meta) == -1)
896 return false;
898 bool close_failed = (close(ctx->fd) == -1);
899 ctx->fd = -1;
900 if (close_failed)
901 return false;
903 if (rename(ctx->tmpname, ctx->filename) == -1)
904 return false;
906 free(ctx->tmpname);
907 ctx->tmpname = NULL;
909 int dir = open(dirname(ctx->filename), O_DIRECTORY|O_RDONLY);
910 if (dir == -1)
911 return false;
913 if (fsync(dir) == -1) {
914 close(dir);
915 return false;
918 if (close(dir) == -1)
919 return false;
921 if (meta.st_mtime)
922 ctx->txt->info = meta;
923 return true;
926 static bool text_save_begin_inplace(TextSave *ctx) {
927 Text *txt = ctx->txt;
928 struct stat meta = { 0 };
929 int newfd = -1, saved_errno;
930 if ((ctx->fd = open(ctx->filename, O_CREAT|O_WRONLY, 0666)) == -1)
931 goto err;
932 if (fstat(ctx->fd, &meta) == -1)
933 goto err;
934 if (meta.st_dev == txt->info.st_dev && meta.st_ino == txt->info.st_ino &&
935 txt->block && txt->block->type == MMAP_ORIG && txt->block->size) {
936 /* The file we are going to overwrite is currently mmap-ed from
937 * text_load, therefore we copy the mmap-ed block to a temporary
938 * file and remap it at the same position such that all pointers
939 * from the various pieces are still valid.
941 size_t size = txt->block->size;
942 char tmpname[32] = "/tmp/vis-XXXXXX";
943 newfd = mkstemp(tmpname);
944 if (newfd == -1)
945 goto err;
946 if (unlink(tmpname) == -1)
947 goto err;
948 ssize_t written = write_all(newfd, txt->block->data, size);
949 if (written == -1 || (size_t)written != size)
950 goto err;
951 if (munmap(txt->block->data, size) == -1)
952 goto err;
954 void *data = mmap(txt->block->data, size, PROT_READ, MAP_SHARED, newfd, 0);
955 if (data == MAP_FAILED)
956 goto err;
957 if (data != txt->block->data) {
958 munmap(data, size);
959 goto err;
961 bool close_failed = (close(newfd) == -1);
962 newfd = -1;
963 if (close_failed)
964 goto err;
965 txt->block->data = data;
966 txt->block->type = MMAP;
967 newfd = -1;
969 /* overwrite the existing file content, if something goes wrong
970 * here we are screwed, TODO: make a backup before? */
971 if (ftruncate(ctx->fd, 0) == -1)
972 goto err;
973 ctx->type = TEXT_SAVE_INPLACE;
974 return true;
975 err:
976 saved_errno = errno;
977 if (newfd != -1)
978 close(newfd);
979 if (ctx->fd != -1)
980 close(ctx->fd);
981 ctx->fd = -1;
982 errno = saved_errno;
983 return false;
986 static bool text_save_commit_inplace(TextSave *ctx) {
987 if (fsync(ctx->fd) == -1)
988 return false;
989 struct stat meta = { 0 };
990 if (fstat(ctx->fd, &meta) == -1)
991 return false;
992 if (close(ctx->fd) == -1)
993 return false;
994 ctx->txt->info = meta;
995 return true;
998 TextSave *text_save_begin(Text *txt, const char *filename, enum TextSaveMethod type) {
999 if (!filename)
1000 return NULL;
1001 TextSave *ctx = calloc(1, sizeof *ctx);
1002 if (!ctx)
1003 return NULL;
1004 ctx->txt = txt;
1005 ctx->fd = -1;
1006 if (!(ctx->filename = strdup(filename)))
1007 goto err;
1008 errno = 0;
1009 if ((type == TEXT_SAVE_AUTO || type == TEXT_SAVE_ATOMIC) && text_save_begin_atomic(ctx))
1010 return ctx;
1011 if (errno == ENOSPC)
1012 goto err;
1013 if ((type == TEXT_SAVE_AUTO || type == TEXT_SAVE_INPLACE) && text_save_begin_inplace(ctx))
1014 return ctx;
1015 err:
1016 text_save_cancel(ctx);
1017 return NULL;
1020 bool text_save_commit(TextSave *ctx) {
1021 if (!ctx)
1022 return true;
1023 bool ret;
1024 Text *txt = ctx->txt;
1025 switch (ctx->type) {
1026 case TEXT_SAVE_ATOMIC:
1027 ret = text_save_commit_atomic(ctx);
1028 break;
1029 case TEXT_SAVE_INPLACE:
1030 ret = text_save_commit_inplace(ctx);
1031 break;
1032 default:
1033 ret = false;
1034 break;
1037 if (ret) {
1038 txt->saved_revision = txt->history;
1039 text_snapshot(txt);
1041 text_save_cancel(ctx);
1042 return ret;
1045 void text_save_cancel(TextSave *ctx) {
1046 if (!ctx)
1047 return;
1048 int saved_errno = errno;
1049 if (ctx->fd != -1)
1050 close(ctx->fd);
1051 if (ctx->tmpname && ctx->tmpname[0])
1052 unlink(ctx->tmpname);
1053 free(ctx->tmpname);
1054 free(ctx->filename);
1055 free(ctx);
1056 errno = saved_errno;
1059 bool text_save(Text *txt, const char *filename) {
1060 Filerange r = (Filerange){ .start = 0, .end = text_size(txt) };
1061 return text_save_range(txt, &r, filename);
1064 /* First try to save the file atomically using rename(2) if this does not
1065 * work overwrite the file in place. However if something goes wrong during
1066 * this overwrite the original file is permanently damaged.
1068 bool text_save_range(Text *txt, Filerange *range, const char *filename) {
1069 if (!filename) {
1070 txt->saved_revision = txt->history;
1071 text_snapshot(txt);
1072 return true;
1074 TextSave *ctx = text_save_begin(txt, filename, TEXT_SAVE_AUTO);
1075 if (!ctx)
1076 return false;
1077 ssize_t written = text_write_range(txt, range, ctx->fd);
1078 if (written == -1 || (size_t)written != text_range_size(range)) {
1079 text_save_cancel(ctx);
1080 return false;
1082 return text_save_commit(ctx);
1085 ssize_t text_save_write_range(TextSave *ctx, Filerange *range) {
1086 return text_write_range(ctx->txt, range, ctx->fd);
1089 ssize_t text_write(Text *txt, int fd) {
1090 Filerange r = (Filerange){ .start = 0, .end = text_size(txt) };
1091 return text_write_range(txt, &r, fd);
1094 ssize_t text_write_range(Text *txt, Filerange *range, int fd) {
1095 size_t size = text_range_size(range), rem = size;
1096 for (Iterator it = text_iterator_get(txt, range->start);
1097 rem > 0 && text_iterator_valid(&it);
1098 text_iterator_next(&it)) {
1099 size_t prem = it.end - it.text;
1100 if (prem > rem)
1101 prem = rem;
1102 ssize_t written = write_all(fd, it.text, prem);
1103 if (written == -1)
1104 return -1;
1105 rem -= written;
1106 if ((size_t)written != prem)
1107 break;
1109 return size - rem;
1112 /* load the given file as starting point for further editing operations.
1113 * to start with an empty document, pass NULL as filename. */
1114 Text *text_load(const char *filename) {
1115 int fd = -1;
1116 size_t size = 0;
1117 Text *txt = calloc(1, sizeof *txt);
1118 if (!txt)
1119 return NULL;
1120 Piece *p = piece_alloc(txt);
1121 if (!p)
1122 goto out;
1123 lineno_cache_invalidate(&txt->lines);
1124 if (filename) {
1125 if ((fd = open(filename, O_RDONLY)) == -1)
1126 goto out;
1127 if (fstat(fd, &txt->info) == -1)
1128 goto out;
1129 if (!S_ISREG(txt->info.st_mode)) {
1130 errno = S_ISDIR(txt->info.st_mode) ? EISDIR : ENOTSUP;
1131 goto out;
1133 // XXX: use lseek(fd, 0, SEEK_END); instead?
1134 size = txt->info.st_size;
1135 if (size > 0) {
1136 if (size < BLOCK_MMAP_SIZE)
1137 txt->block = block_read(txt, size, fd);
1138 else
1139 txt->block = block_mmap(txt, size, fd, 0);
1140 if (!txt->block)
1141 goto out;
1142 piece_init(p, &txt->begin, &txt->end, txt->block->data, txt->block->len);
1146 if (size == 0)
1147 piece_init(p, &txt->begin, &txt->end, "\0", 0);
1149 piece_init(&txt->begin, NULL, p, NULL, 0);
1150 piece_init(&txt->end, p, NULL, NULL, 0);
1151 txt->size = p->len;
1152 /* write an empty revision */
1153 change_alloc(txt, EPOS);
1154 text_snapshot(txt);
1155 txt->saved_revision = txt->history;
1157 if (fd != -1)
1158 close(fd);
1159 return txt;
1160 out:
1161 if (fd != -1)
1162 close(fd);
1163 text_free(txt);
1164 return NULL;
1167 struct stat text_stat(Text *txt) {
1168 return txt->info;
1171 /* A delete operation can either start/stop midway through a piece or at
1172 * a boundry. In the former case a new piece is created to represent the
1173 * remaining text before/after the modification point.
1175 * /-+ --> +---------+ --> +-----+ --> +-----+ --> +-\
1176 * | | | existing| |demo | |text | | |
1177 * \-+ <-- +---------+ <-- +-----+ <-- +-----+ <-- +-/
1178 * ^ ^
1179 * |------ delete range -----|
1181 * /-+ --> +----+ --> +--+ --> +-\
1182 * | | | exi| |t | | |
1183 * \-+ <-- +----+ <-- +--+ <-- +-/
1185 bool text_delete(Text *txt, size_t pos, size_t len) {
1186 if (len == 0)
1187 return true;
1188 size_t pos_end;
1189 if (!addu(pos, len, &pos_end) || pos_end > txt->size)
1190 return false;
1191 if (pos < txt->lines.pos)
1192 lineno_cache_invalidate(&txt->lines);
1194 Location loc = piece_get_intern(txt, pos);
1195 Piece *p = loc.piece;
1196 if (!p)
1197 return false;
1198 size_t off = loc.off;
1199 if (cache_delete(txt, p, off, len))
1200 return true;
1201 Change *c = change_alloc(txt, pos);
1202 if (!c)
1203 return false;
1205 bool midway_start = false, midway_end = false; /* split pieces? */
1206 Piece *before, *after; /* unmodified pieces before/after deletion point */
1207 Piece *start, *end; /* span which is removed */
1208 size_t cur; /* how much has already been deleted */
1210 if (off == p->len) {
1211 /* deletion starts at a piece boundry */
1212 cur = 0;
1213 before = p;
1214 start = p->next;
1215 } else {
1216 /* deletion starts midway through a piece */
1217 midway_start = true;
1218 cur = p->len - off;
1219 start = p;
1220 before = piece_alloc(txt);
1221 if (!before)
1222 return false;
1225 /* skip all pieces which fall into deletion range */
1226 while (cur < len) {
1227 p = p->next;
1228 cur += p->len;
1231 if (cur == len) {
1232 /* deletion stops at a piece boundry */
1233 end = p;
1234 after = p->next;
1235 } else {
1236 /* cur > len: deletion stops midway through a piece */
1237 midway_end = true;
1238 end = p;
1239 after = piece_alloc(txt);
1240 if (!after)
1241 return false;
1242 piece_init(after, before, p->next, p->data + p->len - (cur - len), cur - len);
1245 if (midway_start) {
1246 /* we finally know which piece follows our newly allocated before piece */
1247 piece_init(before, start->prev, after, start->data, off);
1250 Piece *new_start = NULL, *new_end = NULL;
1251 if (midway_start) {
1252 new_start = before;
1253 if (!midway_end)
1254 new_end = before;
1256 if (midway_end) {
1257 if (!midway_start)
1258 new_start = after;
1259 new_end = after;
1262 span_init(&c->new, new_start, new_end);
1263 span_init(&c->old, start, end);
1264 span_swap(txt, &c->old, &c->new);
1265 return true;
1268 bool text_delete_range(Text *txt, Filerange *r) {
1269 if (!text_range_valid(r))
1270 return false;
1271 return text_delete(txt, r->start, text_range_size(r));
1274 /* preserve the current text content such that it can be restored by
1275 * means of undo/redo operations */
1276 void text_snapshot(Text *txt) {
1277 if (txt->current_revision)
1278 txt->last_revision = txt->current_revision;
1279 txt->current_revision = NULL;
1280 txt->cache = NULL;
1284 void text_free(Text *txt) {
1285 if (!txt)
1286 return;
1288 // free history
1289 Revision *hist = txt->history;
1290 while (hist && hist->prev)
1291 hist = hist->prev;
1292 while (hist) {
1293 Revision *later = hist->later;
1294 revision_free(hist);
1295 hist = later;
1298 for (Piece *next, *p = txt->pieces; p; p = next) {
1299 next = p->global_next;
1300 piece_free(p);
1303 for (Block *next, *blk = txt->blocks; blk; blk = next) {
1304 next = blk->next;
1305 block_free(blk);
1308 free(txt);
1311 bool text_modified(Text *txt) {
1312 return txt->saved_revision != txt->history;
1315 bool text_mmaped(Text *txt, const char *ptr) {
1316 uintptr_t addr = (uintptr_t)ptr;
1317 for (Block *blk = txt->blocks; blk; blk = blk->next) {
1318 if ((blk->type == MMAP_ORIG || blk->type == MMAP) &&
1319 (uintptr_t)(blk->data) <= addr && addr < (uintptr_t)(blk->data + blk->size))
1320 return true;
1322 return false;
1325 static bool text_iterator_init(Iterator *it, size_t pos, Piece *p, size_t off) {
1326 Iterator iter = (Iterator){
1327 .pos = pos,
1328 .piece = p,
1329 .start = p ? p->data : NULL,
1330 .end = p ? p->data + p->len : NULL,
1331 .text = p ? p->data + off : NULL,
1333 *it = iter;
1334 return text_iterator_valid(it);
1337 Iterator text_iterator_get(Text *txt, size_t pos) {
1338 Iterator it;
1339 Location loc = piece_get_extern(txt, pos);
1340 text_iterator_init(&it, pos, loc.piece, loc.off);
1341 return it;
1344 bool text_iterator_byte_get(Iterator *it, char *b) {
1345 if (text_iterator_valid(it)) {
1346 if (it->start <= it->text && it->text < it->end) {
1347 *b = *it->text;
1348 return true;
1349 } else if (it->pos == it->piece->text->size) { /* EOF */
1350 *b = '\0';
1351 return true;
1354 return false;
1357 bool text_iterator_next(Iterator *it) {
1358 size_t rem = it->end - it->text;
1359 return text_iterator_init(it, it->pos+rem, it->piece ? it->piece->next : NULL, 0);
1362 bool text_iterator_prev(Iterator *it) {
1363 size_t off = it->text - it->start;
1364 size_t len = it->piece && it->piece->prev ? it->piece->prev->len : 0;
1365 return text_iterator_init(it, it->pos-off, it->piece ? it->piece->prev : NULL, len);
1368 bool text_iterator_valid(const Iterator *it) {
1369 /* filter out sentinel nodes */
1370 return it->piece && it->piece->text;
1373 bool text_iterator_byte_next(Iterator *it, char *b) {
1374 if (!it->piece || !it->piece->next)
1375 return false;
1376 bool eof = true;
1377 if (it->text < it->end) {
1378 it->text++;
1379 it->pos++;
1380 eof = false;
1381 } else if (!it->piece->prev) {
1382 eof = false;
1385 while (it->text == it->end) {
1386 if (!text_iterator_next(it)) {
1387 if (eof)
1388 return false;
1389 if (b)
1390 *b = '\0';
1391 return text_iterator_prev(it);
1395 if (b)
1396 *b = *it->text;
1397 return true;
1400 bool text_iterator_byte_prev(Iterator *it, char *b) {
1401 if (!it->piece || !it->piece->prev)
1402 return false;
1403 bool eof = !it->piece->next;
1404 while (it->text == it->start) {
1405 if (!text_iterator_prev(it)) {
1406 if (!eof)
1407 return false;
1408 if (b)
1409 *b = '\0';
1410 return text_iterator_next(it);
1414 --it->text;
1415 --it->pos;
1417 if (b)
1418 *b = *it->text;
1419 return true;
1422 bool text_iterator_byte_find_prev(Iterator *it, char b) {
1423 while (it->text) {
1424 const char *match = memrchr(it->start, b, it->text - it->start);
1425 if (match) {
1426 it->pos -= it->text - match;
1427 it->text = match;
1428 return true;
1430 text_iterator_prev(it);
1432 text_iterator_next(it);
1433 return false;
1436 bool text_iterator_byte_find_next(Iterator *it, char b) {
1437 while (it->text) {
1438 const char *match = memchr(it->text, b, it->end - it->text);
1439 if (match) {
1440 it->pos += match - it->text;
1441 it->text = match;
1442 return true;
1444 text_iterator_next(it);
1446 text_iterator_prev(it);
1447 return false;
1450 bool text_iterator_codepoint_next(Iterator *it, char *c) {
1451 while (text_iterator_byte_next(it, NULL)) {
1452 if (ISUTF8(*it->text)) {
1453 if (c)
1454 *c = *it->text;
1455 return true;
1458 return false;
1461 bool text_iterator_codepoint_prev(Iterator *it, char *c) {
1462 while (text_iterator_byte_prev(it, NULL)) {
1463 if (ISUTF8(*it->text)) {
1464 if (c)
1465 *c = *it->text;
1466 return true;
1469 return false;
1472 bool text_iterator_char_next(Iterator *it, char *c) {
1473 if (!text_iterator_codepoint_next(it, c))
1474 return false;
1475 mbstate_t ps = { 0 };
1476 for (;;) {
1477 char buf[MB_LEN_MAX];
1478 size_t len = text_bytes_get(it->piece->text, it->pos, sizeof buf, buf);
1479 wchar_t wc;
1480 size_t wclen = mbrtowc(&wc, buf, len, &ps);
1481 if (wclen == (size_t)-1 && errno == EILSEQ) {
1482 return true;
1483 } else if (wclen == (size_t)-2) {
1484 return false;
1485 } else if (wclen == 0) {
1486 return true;
1487 } else {
1488 int width = wcwidth(wc);
1489 if (width != 0)
1490 return true;
1491 if (!text_iterator_codepoint_next(it, c))
1492 return false;
1495 return true;
1498 bool text_iterator_char_prev(Iterator *it, char *c) {
1499 if (!text_iterator_codepoint_prev(it, c))
1500 return false;
1501 for (;;) {
1502 char buf[MB_LEN_MAX];
1503 size_t len = text_bytes_get(it->piece->text, it->pos, sizeof buf, buf);
1504 wchar_t wc;
1505 mbstate_t ps = { 0 };
1506 size_t wclen = mbrtowc(&wc, buf, len, &ps);
1507 if (wclen == (size_t)-1 && errno == EILSEQ) {
1508 return true;
1509 } else if (wclen == (size_t)-2) {
1510 return false;
1511 } else if (wclen == 0) {
1512 return true;
1513 } else {
1514 int width = wcwidth(wc);
1515 if (width != 0)
1516 return true;
1517 if (!text_iterator_codepoint_prev(it, c))
1518 return false;
1521 return true;
1524 bool text_byte_get(Text *txt, size_t pos, char *byte) {
1525 return text_bytes_get(txt, pos, 1, byte);
1528 size_t text_bytes_get(Text *txt, size_t pos, size_t len, char *buf) {
1529 if (!buf)
1530 return 0;
1531 char *cur = buf;
1532 size_t rem = len;
1533 text_iterate(txt, it, pos) {
1534 if (rem == 0)
1535 break;
1536 size_t piece_len = it.end - it.text;
1537 if (piece_len > rem)
1538 piece_len = rem;
1539 if (piece_len) {
1540 memcpy(cur, it.text, piece_len);
1541 cur += piece_len;
1542 rem -= piece_len;
1545 return len - rem;
1548 char *text_bytes_alloc0(Text *txt, size_t pos, size_t len) {
1549 if (len == SIZE_MAX)
1550 return NULL;
1551 char *buf = malloc(len+1);
1552 if (!buf)
1553 return NULL;
1554 len = text_bytes_get(txt, pos, len, buf);
1555 buf[len] = '\0';
1556 return buf;
1559 size_t text_size(Text *txt) {
1560 return txt->size;
1563 /* count the number of new lines '\n' in range [pos, pos+len) */
1564 static size_t lines_count(Text *txt, size_t pos, size_t len) {
1565 size_t lines = 0;
1566 text_iterate(txt, it, pos) {
1567 const char *start = it.text;
1568 while (len > 0 && start < it.end) {
1569 size_t n = MIN(len, (size_t)(it.end - start));
1570 const char *end = memchr(start, '\n', n);
1571 if (!end) {
1572 len -= n;
1573 break;
1575 lines++;
1576 len -= end - start + 1;
1577 start = end + 1;
1580 if (len == 0)
1581 break;
1583 return lines;
1586 /* skip n lines forward and return position afterwards */
1587 static size_t lines_skip_forward(Text *txt, size_t pos, size_t lines, size_t *lines_skipped) {
1588 size_t lines_old = lines;
1589 text_iterate(txt, it, pos) {
1590 const char *start = it.text;
1591 while (lines > 0 && start < it.end) {
1592 size_t n = it.end - start;
1593 const char *end = memchr(start, '\n', n);
1594 if (!end) {
1595 pos += n;
1596 break;
1598 pos += end - start + 1;
1599 start = end + 1;
1600 lines--;
1603 if (lines == 0)
1604 break;
1606 if (lines_skipped)
1607 *lines_skipped = lines_old - lines;
1608 return pos;
1611 static void lineno_cache_invalidate(LineCache *cache) {
1612 cache->pos = 0;
1613 cache->lineno = 1;
1616 size_t text_pos_by_lineno(Text *txt, size_t lineno) {
1617 size_t lines_skipped;
1618 LineCache *cache = &txt->lines;
1619 if (lineno <= 1)
1620 return 0;
1621 if (lineno > cache->lineno) {
1622 cache->pos = lines_skip_forward(txt, cache->pos, lineno - cache->lineno, &lines_skipped);
1623 cache->lineno += lines_skipped;
1624 } else if (lineno < cache->lineno) {
1625 #if 0
1626 // TODO does it make sense to scan memory backwards here?
1627 size_t diff = cache->lineno - lineno;
1628 if (diff < lineno) {
1629 lines_skip_backward(txt, cache->pos, diff);
1630 } else
1631 #endif
1632 cache->pos = lines_skip_forward(txt, 0, lineno - 1, &lines_skipped);
1633 cache->lineno = lines_skipped + 1;
1635 return cache->lineno == lineno ? cache->pos : EPOS;
1638 size_t text_lineno_by_pos(Text *txt, size_t pos) {
1639 LineCache *cache = &txt->lines;
1640 if (pos > txt->size)
1641 pos = txt->size;
1642 if (pos < cache->pos) {
1643 size_t diff = cache->pos - pos;
1644 if (diff < pos)
1645 cache->lineno -= lines_count(txt, pos, diff);
1646 else
1647 cache->lineno = lines_count(txt, 0, pos) + 1;
1648 } else if (pos > cache->pos) {
1649 cache->lineno += lines_count(txt, cache->pos, pos - cache->pos);
1651 cache->pos = text_line_begin(txt, pos);
1652 return cache->lineno;
1655 Mark text_mark_set(Text *txt, size_t pos) {
1656 if (pos == txt->size)
1657 return (Mark)&txt->end;
1658 Location loc = piece_get_extern(txt, pos);
1659 if (!loc.piece)
1660 return EMARK;
1661 return (Mark)(loc.piece->data + loc.off);
1664 size_t text_mark_get(Text *txt, Mark mark) {
1665 size_t cur = 0;
1667 if (mark == EMARK)
1668 return EPOS;
1669 if (mark == (Mark)&txt->end)
1670 return txt->size;
1672 for (Piece *p = txt->begin.next; p->next; p = p->next) {
1673 Mark start = (Mark)(p->data);
1674 Mark end = start + p->len;
1675 if (start <= mark && mark < end)
1676 return cur + (mark - start);
1677 cur += p->len;
1680 return EPOS;
1683 size_t text_history_get(Text *txt, size_t index) {
1684 for (Revision *rev = txt->current_revision ? txt->current_revision : txt->history; rev; rev = rev->prev) {
1685 if (index-- == 0) {
1686 Change *c = rev->change;
1687 while (c && c->next)
1688 c = c->next;
1689 return c ? c->pos : EPOS;
1692 return EPOS;