10 #include <sys/types.h>
17 #include <selinux/selinux.h>
21 #include "text-util.h"
24 /* Allocate buffers holding the actual file content in junks of size: */
25 #define BUFFER_SIZE (1 << 20)
26 /* Files smaller than this value are copied on load, larger ones are mmap(2)-ed
27 * directely. Hence the former can be truncated, while doing so on the latter
28 * results in havoc. */
29 #define BUFFER_MMAP_SIZE (1 << 23)
31 /* Buffer holding the file content, either readonly mmap(2)-ed from the original
32 * file or heap allocated to store the modifications.
34 typedef struct Buffer Buffer
;
36 size_t size
; /* maximal capacity */
37 size_t len
; /* current used length / insertion position */
38 char *data
; /* actual data */
39 enum { MMAP
, MALLOC
} type
; /* type of allocation */
40 Buffer
*next
; /* next junk */
43 /* A piece holds a reference (but doesn't itself store) a certain amount of data.
44 * All active pieces chained together form the whole content of the document.
45 * At the beginning there exists only one piece, spanning the whole document.
46 * Upon insertion/deletion new pieces will be created to represent the changes.
47 * Generally pieces are never destroyed, but kept around to peform undo/redo
51 Text
*text
; /* text to which this piece belongs */
52 Piece
*prev
, *next
; /* pointers to the logical predecessor/successor */
53 Piece
*global_prev
; /* double linked list in order of allocation, */
54 Piece
*global_next
; /* used to free individual pieces */
55 const char *data
; /* pointer into a Buffer holding the data */
56 size_t len
; /* the length in number of bytes of the data */
59 /* used to transform a global position (byte offset starting from the beginning
60 * of the text) into an offset relative to a piece.
63 Piece
*piece
; /* piece holding the location */
64 size_t off
; /* offset into the piece in bytes */
67 /* A Span holds a certain range of pieces. Changes to the document are always
68 * performed by swapping out an existing span with a new one.
71 Piece
*start
, *end
; /* start/end of the span */
72 size_t len
; /* the sum of the lengths of the pieces which form this span */
75 /* A Change keeps all needed information to redo/undo an insertion/deletion. */
76 typedef struct Change Change
;
78 Span old
; /* all pieces which are being modified/swapped out by the change */
79 Span
new; /* all pieces which are introduced/swapped in by the change */
80 size_t pos
; /* absolute position at which the change occured */
81 Change
*next
; /* next change which is part of the same action */
82 Change
*prev
; /* previous change which is part of the same action */
85 /* An Action is a list of Changes which are used to undo/redo all modifications
86 * since the last snapshot operation. Actions are stored in a directed graph structure.
88 typedef struct Action Action
;
90 Change
*change
; /* the most recent change */
91 Action
*next
; /* the next (child) action in the undo tree */
92 Action
*prev
; /* the previous (parent) operation in the undo tree */
93 Action
*earlier
; /* the previous Action, chronologically */
94 Action
*later
; /* the next Action, chronologically */
95 time_t time
; /* when the first change of this action was performed */
96 size_t seq
; /* a unique, strictly increasing identifier */
100 size_t pos
; /* position in bytes from start of file */
101 size_t lineno
; /* line number in file i.e. number of '\n' in [0, pos) */
104 /* The main struct holding all information of a given file */
106 Buffer
*buf
; /* original file content at the time of load operation */
107 Buffer
*buffers
; /* all buffers which have been allocated to hold insertion data */
108 Piece
*pieces
; /* all pieces which have been allocated, used to free them */
109 Piece
*cache
; /* most recently modified piece */
110 Piece begin
, end
; /* sentinel nodes which always exists but don't hold any data */
111 Action
*history
; /* undo tree */
112 Action
*current_action
; /* action holding all file changes until a snapshot is performed */
113 Action
*last_action
; /* the last action added to the tree, chronologically */
114 Action
*saved_action
; /* the last action at the time of the save operation */
115 size_t size
; /* current file content size in bytes */
116 struct stat info
; /* stat as probed at load time */
117 LineCache lines
; /* mapping between absolute pos in bytes and logical line breaks */
118 enum TextNewLine newlines
; /* which type of new lines does the file use */
121 /* buffer management */
122 static Buffer
*buffer_alloc(Text
*txt
, size_t size
);
123 static Buffer
*buffer_read(Text
*txt
, size_t size
, int fd
);
124 static Buffer
*buffer_mmap(Text
*txt
, size_t size
, int fd
, off_t offset
);
125 static void buffer_free(Buffer
*buf
);
126 static bool buffer_capacity(Buffer
*buf
, size_t len
);
127 static const char *buffer_append(Buffer
*buf
, const char *data
, size_t len
);
128 static bool buffer_insert(Buffer
*buf
, size_t pos
, const char *data
, size_t len
);
129 static bool buffer_delete(Buffer
*buf
, size_t pos
, size_t len
);
130 static const char *buffer_store(Text
*txt
, const char *data
, size_t len
);
132 static void cache_piece(Text
*txt
, Piece
*p
);
133 static bool cache_contains(Text
*txt
, Piece
*p
);
134 static bool cache_insert(Text
*txt
, Piece
*p
, size_t off
, const char *data
, size_t len
);
135 static bool cache_delete(Text
*txt
, Piece
*p
, size_t off
, size_t len
);
136 /* piece management */
137 static Piece
*piece_alloc(Text
*txt
);
138 static void piece_free(Piece
*p
);
139 static void piece_init(Piece
*p
, Piece
*prev
, Piece
*next
, const char *data
, size_t len
);
140 static Location
piece_get_intern(Text
*txt
, size_t pos
);
141 static Location
piece_get_extern(Text
*txt
, size_t pos
);
142 /* span management */
143 static void span_init(Span
*span
, Piece
*start
, Piece
*end
);
144 static void span_swap(Text
*txt
, Span
*old
, Span
*new);
145 /* change management */
146 static Change
*change_alloc(Text
*txt
, size_t pos
);
147 static void change_free(Change
*c
);
148 /* action management */
149 static Action
*action_alloc(Text
*txt
);
150 static void action_free(Action
*a
);
151 /* logical line counting cache */
152 static void lineno_cache_invalidate(LineCache
*cache
);
153 static size_t lines_skip_forward(Text
*txt
, size_t pos
, size_t lines
, size_t *lines_skiped
);
154 static size_t lines_count(Text
*txt
, size_t pos
, size_t len
);
156 static ssize_t
write_all(int fd
, const char *buf
, size_t count
) {
159 ssize_t written
= write(fd
, buf
, rem
);
161 if (errno
== EAGAIN
|| errno
== EINTR
)
164 } else if (written
== 0) {
173 /* allocate a new buffer of MAX(size, BUFFER_SIZE) bytes */
174 static Buffer
*buffer_alloc(Text
*txt
, size_t size
) {
175 Buffer
*buf
= calloc(1, sizeof(Buffer
));
178 if (BUFFER_SIZE
> size
)
180 if (!(buf
->data
= malloc(size
))) {
186 buf
->next
= txt
->buffers
;
191 static Buffer
*buffer_read(Text
*txt
, size_t size
, int fd
) {
192 Buffer
*buf
= buffer_alloc(txt
, size
);
197 ssize_t len
= read(fd
, data
, MIN(sizeof(data
), size
));
199 txt
->buffers
= buf
->next
;
202 } else if (len
== 0) {
205 buffer_append(buf
, data
, len
);
212 static Buffer
*buffer_mmap(Text
*txt
, size_t size
, int fd
, off_t offset
) {
213 Buffer
*buf
= calloc(1, sizeof(Buffer
));
217 buf
->data
= mmap(NULL
, size
, PROT_READ
, MAP_SHARED
, fd
, offset
);
218 if (buf
->data
== MAP_FAILED
) {
226 buf
->next
= txt
->buffers
;
231 static void buffer_free(Buffer
*buf
) {
234 if (buf
->type
== MALLOC
)
236 else if (buf
->type
== MMAP
&& buf
->data
)
237 munmap(buf
->data
, buf
->size
);
241 /* check whether buffer has enough free space to store len bytes */
242 static bool buffer_capacity(Buffer
*buf
, size_t len
) {
243 return buf
->size
- buf
->len
>= len
;
246 /* append data to buffer, assumes there is enough space available */
247 static const char *buffer_append(Buffer
*buf
, const char *data
, size_t len
) {
248 char *dest
= memcpy(buf
->data
+ buf
->len
, data
, len
);
253 /* stores the given data in a buffer, allocates a new one if necessary. returns
254 * a pointer to the storage location or NULL if allocation failed. */
255 static const char *buffer_store(Text
*txt
, const char *data
, size_t len
) {
256 Buffer
*buf
= txt
->buffers
;
257 if ((!buf
|| !buffer_capacity(buf
, len
)) && !(buf
= buffer_alloc(txt
, len
)))
259 return buffer_append(buf
, data
, len
);
262 /* insert data into buffer at an arbitrary position, this should only be used with
263 * data of the most recently created piece. */
264 static bool buffer_insert(Buffer
*buf
, size_t pos
, const char *data
, size_t len
) {
265 if (pos
> buf
->len
|| !buffer_capacity(buf
, len
))
268 return buffer_append(buf
, data
, len
);
269 char *insert
= buf
->data
+ pos
;
270 memmove(insert
+ len
, insert
, buf
->len
- pos
);
271 memcpy(insert
, data
, len
);
276 /* delete data from a buffer at an arbitrary position, this should only be used with
277 * data of the most recently created piece. */
278 static bool buffer_delete(Buffer
*buf
, size_t pos
, size_t len
) {
279 if (pos
+ len
> buf
->len
)
281 if (buf
->len
== pos
) {
285 char *delete = buf
->data
+ pos
;
286 memmove(delete, delete + len
, buf
->len
- pos
- len
);
291 /* cache the given piece if it is the most recently changed one */
292 static void cache_piece(Text
*txt
, Piece
*p
) {
293 Buffer
*buf
= txt
->buffers
;
294 if (!buf
|| p
->data
< buf
->data
|| p
->data
+ p
->len
!= buf
->data
+ buf
->len
)
299 /* check whether the given piece was the most recently modified one */
300 static bool cache_contains(Text
*txt
, Piece
*p
) {
301 Buffer
*buf
= txt
->buffers
;
302 Action
*a
= txt
->current_action
;
303 if (!buf
|| !txt
->cache
|| txt
->cache
!= p
|| !a
|| !a
->change
)
306 Piece
*start
= a
->change
->new.start
;
307 Piece
*end
= a
->change
->new.end
;
309 for (Piece
*cur
= start
; !found
; cur
= cur
->next
) {
316 return found
&& p
->data
+ p
->len
== buf
->data
+ buf
->len
;
319 /* try to insert a junk of data at a given piece offset. the insertion is only
320 * performed if the piece is the most recenetly changed one. the legnth of the
321 * piece, the span containing it and the whole text is adjusted accordingly */
322 static bool cache_insert(Text
*txt
, Piece
*p
, size_t off
, const char *data
, size_t len
) {
323 if (!cache_contains(txt
, p
))
325 Buffer
*buf
= txt
->buffers
;
326 size_t bufpos
= p
->data
+ off
- buf
->data
;
327 if (!buffer_insert(buf
, bufpos
, data
, len
))
330 txt
->current_action
->change
->new.len
+= len
;
335 /* try to delete a junk of data at a given piece offset. the deletion is only
336 * performed if the piece is the most recenetly changed one and the whole
337 * affected range lies within it. the legnth of the piece, the span containing it
338 * and the whole text is adjusted accordingly */
339 static bool cache_delete(Text
*txt
, Piece
*p
, size_t off
, size_t len
) {
340 if (!cache_contains(txt
, p
))
342 Buffer
*buf
= txt
->buffers
;
343 size_t bufpos
= p
->data
+ off
- buf
->data
;
344 if (off
+ len
> p
->len
|| !buffer_delete(buf
, bufpos
, len
))
347 txt
->current_action
->change
->new.len
-= len
;
352 /* initialize a span and calculate its length */
353 static void span_init(Span
*span
, Piece
*start
, Piece
*end
) {
357 for (Piece
*p
= start
; p
; p
= p
->next
) {
365 /* swap out an old span and replace it with a new one.
367 * - if old is an empty span do not remove anything, just insert the new one
368 * - if new is an empty span do not insert anything, just remove the old one
370 * adjusts the document size accordingly.
372 static void span_swap(Text
*txt
, Span
*old
, Span
*new) {
373 if (old
->len
== 0 && new->len
== 0) {
375 } else if (old
->len
== 0) {
376 /* insert new span */
377 new->start
->prev
->next
= new->start
;
378 new->end
->next
->prev
= new->end
;
379 } else if (new->len
== 0) {
380 /* delete old span */
381 old
->start
->prev
->next
= old
->end
->next
;
382 old
->end
->next
->prev
= old
->start
->prev
;
384 /* replace old with new */
385 old
->start
->prev
->next
= new->start
;
386 old
->end
->next
->prev
= new->end
;
388 txt
->size
-= old
->len
;
389 txt
->size
+= new->len
;
392 /* allocate a new action, set its pointers to the other actions in the history,
393 * and set it as txt->history. All further changes will be associated with this action. */
394 static Action
*action_alloc(Text
*txt
) {
395 Action
*new = calloc(1, sizeof(Action
));
398 new->time
= time(NULL
);
399 txt
->current_action
= new;
401 /* set sequence number */
402 if (!txt
->last_action
)
405 new->seq
= txt
->last_action
->seq
+ 1;
407 /* set earlier, later pointers */
408 if (txt
->last_action
)
409 txt
->last_action
->later
= new;
410 new->earlier
= txt
->last_action
;
417 /* set prev, next pointers */
418 new->prev
= txt
->history
;
419 txt
->history
->next
= new;
424 static void action_free(Action
*a
) {
427 for (Change
*next
, *c
= a
->change
; c
; c
= next
) {
434 static Piece
*piece_alloc(Text
*txt
) {
435 Piece
*p
= calloc(1, sizeof(Piece
));
439 p
->global_next
= txt
->pieces
;
441 txt
->pieces
->global_prev
= p
;
446 static void piece_free(Piece
*p
) {
450 p
->global_prev
->global_next
= p
->global_next
;
452 p
->global_next
->global_prev
= p
->global_prev
;
453 if (p
->text
->pieces
== p
)
454 p
->text
->pieces
= p
->global_next
;
455 if (p
->text
->cache
== p
)
456 p
->text
->cache
= NULL
;
460 static void piece_init(Piece
*p
, Piece
*prev
, Piece
*next
, const char *data
, size_t len
) {
467 /* returns the piece holding the text at byte offset pos. if pos happens to
468 * be at a piece boundry i.e. the first byte of a piece then the previous piece
469 * to the left is returned with an offset of piece->len. this is convenient for
470 * modifications to the piece chain where both pieces (the returned one and the
471 * one following it) are needed, but unsuitable as a public interface.
473 * in particular if pos is zero, the begin sentinel piece is returned.
475 static Location
piece_get_intern(Text
*txt
, size_t pos
) {
477 for (Piece
*p
= &txt
->begin
; p
->next
; p
= p
->next
) {
478 if (cur
<= pos
&& pos
<= cur
+ p
->len
)
479 return (Location
){ .piece
= p
, .off
= pos
- cur
};
483 return (Location
){ 0 };
486 /* similiar to piece_get_intern but usable as a public API. returns the piece
487 * holding the text at byte offset pos. never returns a sentinel piece.
488 * it pos is the end of file (== text_size()) and the file is not empty then
489 * the last piece holding data is returned.
491 static Location
piece_get_extern(Text
*txt
, size_t pos
) {
494 if (pos
> 0 && pos
== txt
->size
) {
495 Piece
*p
= txt
->begin
.next
;
496 while (p
->next
->next
)
498 return (Location
){ .piece
= p
, .off
= p
->len
};
501 for (Piece
*p
= txt
->begin
.next
; p
->next
; p
= p
->next
) {
502 if (cur
<= pos
&& pos
< cur
+ p
->len
)
503 return (Location
){ .piece
= p
, .off
= pos
- cur
};
507 return (Location
){ 0 };
510 /* allocate a new change, associate it with current action or a newly
511 * allocated one if none exists. */
512 static Change
*change_alloc(Text
*txt
, size_t pos
) {
513 Action
*a
= txt
->current_action
;
515 a
= action_alloc(txt
);
519 Change
*c
= calloc(1, sizeof(Change
));
530 static void change_free(Change
*c
) {
533 /* only free the new part of the span, the old one is still in use */
534 piece_free(c
->new.start
);
535 if (c
->new.start
!= c
->new.end
)
536 piece_free(c
->new.end
);
540 /* When inserting new data there are 2 cases to consider.
542 * - in the first the insertion point falls into the middle of an exisiting
543 * piece which is replaced by three new pieces:
545 * /-+ --> +---------------+ --> +-\
546 * | | | existing text | | |
547 * \-+ <-- +---------------+ <-- +-/
549 * Insertion point for "demo "
551 * /-+ --> +---------+ --> +-----+ --> +-----+ --> +-\
552 * | | | existing| |demo | |text | | |
553 * \-+ <-- +---------+ <-- +-----+ <-- +-----+ <-- +-/
555 * - the second case deals with an insertion point at a piece boundry:
557 * /-+ --> +---------------+ --> +-\
558 * | | | existing text | | |
559 * \-+ <-- +---------------+ <-- +-/
561 * Insertion point for "short"
563 * /-+ --> +-----+ --> +---------------+ --> +-\
564 * | | |short| | existing text | | |
565 * \-+ <-- +-----+ <-- +---------------+ <-- +-/
567 bool text_insert(Text
*txt
, size_t pos
, const char *data
, size_t len
) {
572 if (pos
< txt
->lines
.pos
)
573 lineno_cache_invalidate(&txt
->lines
);
575 Location loc
= piece_get_intern(txt
, pos
);
576 Piece
*p
= loc
.piece
;
579 size_t off
= loc
.off
;
580 if (cache_insert(txt
, p
, off
, data
, len
))
583 Change
*c
= change_alloc(txt
, pos
);
587 if (!(data
= buffer_store(txt
, data
, len
)))
593 /* insert between two existing pieces, hence there is nothing to
594 * remove, just add a new piece holding the extra text */
595 if (!(new = piece_alloc(txt
)))
597 piece_init(new, p
, p
->next
, data
, len
);
598 span_init(&c
->new, new, new);
599 span_init(&c
->old
, NULL
, NULL
);
601 /* insert into middle of an existing piece, therfore split the old
602 * piece. that is we have 3 new pieces one containing the content
603 * before the insertion point then one holding the newly inserted
604 * text and one holding the content after the insertion point.
606 Piece
*before
= piece_alloc(txt
);
607 new = piece_alloc(txt
);
608 Piece
*after
= piece_alloc(txt
);
609 if (!before
|| !new || !after
)
611 piece_init(before
, p
->prev
, new, p
->data
, off
);
612 piece_init(new, before
, after
, data
, len
);
613 piece_init(after
, new, p
->next
, p
->data
+ off
, p
->len
- off
);
615 span_init(&c
->new, before
, after
);
616 span_init(&c
->old
, p
, p
);
619 cache_piece(txt
, new);
620 span_swap(txt
, &c
->old
, &c
->new);
624 bool text_appendf(Text
*txt
, const char *format
, ...) {
626 va_start(ap
, format
);
627 bool ret
= text_vprintf(txt
, text_size(txt
), format
, ap
);
632 bool text_printf(Text
*txt
, size_t pos
, const char *format
, ...) {
634 va_start(ap
, format
);
635 bool ret
= text_vprintf(txt
, pos
, format
, ap
);
640 bool text_vprintf(Text
*txt
, size_t pos
, const char *format
, va_list ap
) {
642 va_copy(ap_save
, ap
);
643 int len
= vsnprintf(NULL
, 0, format
, ap
);
646 char *buf
= malloc(len
+1);
647 bool ret
= buf
&& (vsnprintf(buf
, len
+1, format
, ap_save
) == len
) && text_insert(txt
, pos
, buf
, len
);
653 size_t text_insert_newline(Text
*txt
, size_t pos
) {
654 const char *data
= text_newline_char(txt
);
655 size_t len
= strlen(data
);
656 return text_insert(txt
, pos
, data
, len
) ? len
: 0;
659 static size_t action_undo(Text
*txt
, Action
*a
) {
661 for (Change
*c
= a
->change
; c
; c
= c
->next
) {
662 span_swap(txt
, &c
->new, &c
->old
);
668 static size_t action_redo(Text
*txt
, Action
*a
) {
670 Change
*c
= a
->change
;
673 for ( ; c
; c
= c
->prev
) {
674 span_swap(txt
, &c
->old
, &c
->new);
676 if (c
->new.len
> c
->old
.len
)
677 pos
+= c
->new.len
- c
->old
.len
;
682 size_t text_undo(Text
*txt
) {
684 /* taking a snapshot makes sure that txt->current_action is reset */
686 Action
*a
= txt
->history
->prev
;
689 pos
= action_undo(txt
, txt
->history
);
691 lineno_cache_invalidate(&txt
->lines
);
695 size_t text_redo(Text
*txt
) {
697 /* taking a snapshot makes sure that txt->current_action is reset */
699 Action
*a
= txt
->history
->next
;
702 pos
= action_redo(txt
, a
);
704 lineno_cache_invalidate(&txt
->lines
);
708 static bool history_change_branch(Action
*a
) {
709 bool changed
= false;
711 if (a
->prev
->next
!= a
) {
720 static size_t history_traverse_to(Text
*txt
, Action
*a
) {
724 bool changed
= history_change_branch(a
);
726 if (a
->seq
== txt
->history
->seq
) {
727 return txt
->lines
.pos
;
728 } else if (a
->seq
> txt
->history
->seq
) {
729 while (txt
->history
!= a
)
730 pos
= text_redo(txt
);
732 } else if (a
->seq
< txt
->history
->seq
) {
733 while (txt
->history
!= a
)
734 pos
= text_undo(txt
);
738 while (txt
->history
->prev
&& txt
->history
->prev
->next
== txt
->history
)
740 pos
= text_undo(txt
);
741 while (txt
->history
!= a
)
742 pos
= text_redo(txt
);
748 size_t text_earlier(Text
*txt
, int count
) {
749 Action
*a
= txt
->history
;
750 while (count
-- > 0 && a
->earlier
)
752 return history_traverse_to(txt
, a
);
755 size_t text_later(Text
*txt
, int count
) {
756 Action
*a
= txt
->history
;
757 while (count
-- > 0 && a
->later
)
759 return history_traverse_to(txt
, a
);
762 size_t text_restore(Text
*txt
, time_t time
) {
763 Action
*a
= txt
->history
;
764 while (time
< a
->time
&& a
->earlier
)
766 while (time
> a
->time
&& a
->later
)
768 time_t diff
= labs(a
->time
- time
);
769 if (a
->earlier
&& a
->earlier
!= txt
->history
&& labs(a
->earlier
->time
- time
) < diff
)
771 if (a
->later
&& a
->later
!= txt
->history
&& labs(a
->later
->time
- time
) < diff
)
773 return history_traverse_to(txt
, a
);
776 time_t text_state(Text
*txt
) {
777 return txt
->history
->time
;
780 static bool preserve_acl(int src
, int dest
) {
782 acl_t acl
= acl_get_fd(src
);
784 return errno
== ENOTSUP
? true : false;
785 if (acl_set_fd(dest
, acl
) == -1) {
790 #endif /* CONFIG_ACL */
794 static bool preserve_selinux_context(int src
, int dest
) {
796 char *context
= NULL
;
797 if (!is_selinux_enabled())
799 if (fgetfilecon(src
, &context
) == -1)
800 return errno
== ENOTSUP
? true : false;
801 if (fsetfilecon(dest
, context
) == -1) {
806 #endif /* CONFIG_SELINUX */
810 /* Save current content to given filename. The data is first saved to `filename~`
811 * and then atomically moved to its final (possibly alredy existing) destination
812 * using rename(2). This approach does not work if:
814 * - the file is a symbolic link
815 * - the file is a hard link
816 * - file ownership can not be preserved
817 * - file group can not be preserved
818 * - directory permissions do not allow creation of a new file
819 * - POSXI ACL can not be preserved (if enabled)
820 * - SELinux security context can not be preserved (if enabled)
822 static bool text_save_atomic_range(Text
*txt
, Filerange
*range
, const char *filename
) {
823 struct stat meta
= { 0 }, oldmeta
= { 0 };
824 int fd
= -1, oldfd
= -1, saved_errno
;
825 char *tmpname
= NULL
;
826 size_t size
= text_range_size(range
);
827 size_t namelen
= strlen(filename
) + 1 /* ~ */ + 1 /* \0 */;
829 if ((oldfd
= open(filename
, O_RDONLY
)) == -1 && errno
!= ENOENT
)
831 if (oldfd
!= -1 && lstat(filename
, &oldmeta
) == -1)
834 if (S_ISLNK(oldmeta
.st_mode
)) /* symbolic link */
836 if (oldmeta
.st_nlink
> 1) /* hard link */
839 if (!(tmpname
= calloc(1, namelen
)))
841 snprintf(tmpname
, namelen
, "%s~", filename
);
843 /* O_RDWR is needed because otherwise we can't map with MAP_SHARED */
844 if ((fd
= open(tmpname
, O_CREAT
|O_RDWR
|O_TRUNC
, oldfd
== -1 ? S_IRUSR
|S_IWUSR
: oldmeta
.st_mode
)) == -1)
846 if (ftruncate(fd
, size
) == -1)
849 if (!preserve_acl(oldfd
, fd
) || !preserve_selinux_context(oldfd
, fd
))
851 /* change owner if necessary */
852 if (oldmeta
.st_uid
!= getuid() && fchown(fd
, oldmeta
.st_uid
, (uid_t
)-1) == -1)
854 /* change group if necessary, in case of failure some editors reset
855 * the group permissions to the same as for others */
856 if (oldmeta
.st_gid
!= getgid() && fchown(fd
, (uid_t
)-1, oldmeta
.st_gid
) == -1)
861 void *buf
= mmap(NULL
, size
, PROT_WRITE
, MAP_SHARED
, fd
, 0);
862 if (buf
== MAP_FAILED
)
868 for (Iterator it
= text_iterator_get(txt
, range
->start
);
869 rem
> 0 && text_iterator_valid(&it
);
870 text_iterator_next(&it
)) {
871 size_t len
= it
.end
- it
.text
;
874 memcpy(cur
, it
.text
, len
);
879 if (munmap(buf
, size
) == -1)
891 if (fstat(fd
, &meta
) == -1)
894 if (close(fd
) == -1) {
900 if (rename(tmpname
, filename
) == -1)
913 if (tmpname
&& *tmpname
)
920 bool text_save(Text
*txt
, const char *filename
) {
921 Filerange r
= (Filerange
){ .start
= 0, .end
= text_size(txt
) };
922 return text_save_range(txt
, &r
, filename
);
925 /* First try to save the file atomically using rename(2) if this does not
926 * work overwrite the file in place. However if something goes wrong during
927 * this overwrite the original file is permanently damaged.
929 bool text_save_range(Text
*txt
, Filerange
*range
, const char *filename
) {
931 int fd
= -1, newfd
= -1;
933 if (!filename
|| text_save_atomic_range(txt
, range
, filename
))
937 if ((fd
= open(filename
, O_CREAT
|O_WRONLY
, S_IRUSR
|S_IWUSR
)) == -1)
939 if (fstat(fd
, &meta
) == -1)
941 if (meta
.st_dev
== txt
->info
.st_dev
&& meta
.st_ino
== txt
->info
.st_ino
&&
942 txt
->buf
&& txt
->buf
->type
== MMAP
&& txt
->buf
->size
) {
943 /* The file we are going to overwrite is currently mmap-ed from
944 * text_load, therefore we copy the mmap-ed buffer to a temporary
945 * file and remap it at the same position such that all pointers
946 * from the various pieces are still valid.
948 size_t size
= txt
->buf
->size
;
949 char tmpname
[32] = "/tmp/vis-XXXXXX";
950 mode_t mask
= umask(S_IXUSR
| S_IRWXG
| S_IRWXO
);
951 newfd
= mkstemp(tmpname
);
955 if (unlink(tmpname
) == -1)
957 ssize_t written
= write_all(newfd
, txt
->buf
->data
, size
);
958 if (written
== -1 || (size_t)written
!= size
)
960 if (munmap(txt
->buf
->data
, size
) == -1)
963 void *data
= mmap(txt
->buf
->data
, size
, PROT_READ
, MAP_SHARED
, newfd
, 0);
964 if (data
== MAP_FAILED
)
966 if (data
!= txt
->buf
->data
) {
970 if (close(newfd
) == -1) {
974 txt
->buf
->data
= data
;
977 /* overwrite the exisiting file content, if somehting goes wrong
978 * here we are screwed, TODO: make a backup before? */
979 if (ftruncate(fd
, 0) == -1)
981 ssize_t written
= text_write_range(txt
, range
, fd
);
982 if (written
== -1 || (size_t)written
!= text_range_size(range
))
987 if (fstat(fd
, &meta
) == -1)
993 txt
->saved_action
= txt
->history
;
1004 ssize_t
text_write(Text
*txt
, int fd
) {
1005 Filerange r
= (Filerange
){ .start
= 0, .end
= text_size(txt
) };
1006 return text_write_range(txt
, &r
, fd
);
1009 ssize_t
text_write_range(Text
*txt
, Filerange
*range
, int fd
) {
1010 size_t size
= text_range_size(range
), rem
= size
;
1011 for (Iterator it
= text_iterator_get(txt
, range
->start
);
1012 rem
> 0 && text_iterator_valid(&it
);
1013 text_iterator_next(&it
)) {
1014 size_t prem
= it
.end
- it
.text
;
1017 ssize_t written
= write_all(fd
, it
.text
, prem
);
1021 if ((size_t)written
!= prem
)
1027 /* load the given file as starting point for further editing operations.
1028 * to start with an empty document, pass NULL as filename. */
1029 Text
*text_load(const char *filename
) {
1030 Text
*txt
= calloc(1, sizeof(Text
));
1034 piece_init(&txt
->begin
, NULL
, &txt
->end
, NULL
, 0);
1035 piece_init(&txt
->end
, &txt
->begin
, NULL
, NULL
, 0);
1036 lineno_cache_invalidate(&txt
->lines
);
1038 if ((fd
= open(filename
, O_RDONLY
)) == -1)
1040 if (fstat(fd
, &txt
->info
) == -1)
1042 if (!S_ISREG(txt
->info
.st_mode
)) {
1043 errno
= S_ISDIR(txt
->info
.st_mode
) ? EISDIR
: ENOTSUP
;
1046 // XXX: use lseek(fd, 0, SEEK_END); instead?
1047 size_t size
= txt
->info
.st_size
;
1048 if (size
< BUFFER_MMAP_SIZE
)
1049 txt
->buf
= buffer_read(txt
, size
, fd
);
1051 txt
->buf
= buffer_mmap(txt
, size
, fd
, 0);
1054 Piece
*p
= piece_alloc(txt
);
1057 piece_init(&txt
->begin
, NULL
, p
, NULL
, 0);
1058 piece_init(p
, &txt
->begin
, &txt
->end
, txt
->buf
->data
, txt
->buf
->len
);
1059 piece_init(&txt
->end
, p
, NULL
, NULL
, 0);
1060 txt
->size
= txt
->buf
->len
;
1062 /* write an empty action */
1063 change_alloc(txt
, EPOS
);
1065 txt
->saved_action
= txt
->history
;
1077 struct stat
text_stat(Text
*txt
) {
1081 /* A delete operation can either start/stop midway through a piece or at
1082 * a boundry. In the former case a new piece is created to represent the
1083 * remaining text before/after the modification point.
1085 * /-+ --> +---------+ --> +-----+ --> +-----+ --> +-\
1086 * | | | existing| |demo | |text | | |
1087 * \-+ <-- +---------+ <-- +-----+ <-- +-----+ <-- +-/
1089 * |------ delete range -----|
1091 * /-+ --> +----+ --> +--+ --> +-\
1092 * | | | exi| |t | | |
1093 * \-+ <-- +----+ <-- +--+ <-- +-/
1095 bool text_delete(Text
*txt
, size_t pos
, size_t len
) {
1098 if (pos
+ len
> txt
->size
)
1100 if (pos
< txt
->lines
.pos
)
1101 lineno_cache_invalidate(&txt
->lines
);
1103 Location loc
= piece_get_intern(txt
, pos
);
1104 Piece
*p
= loc
.piece
;
1107 size_t off
= loc
.off
;
1108 if (cache_delete(txt
, p
, off
, len
))
1110 Change
*c
= change_alloc(txt
, pos
);
1114 bool midway_start
= false, midway_end
= false; /* split pieces? */
1115 Piece
*before
, *after
; /* unmodified pieces before/after deletion point */
1116 Piece
*start
, *end
; /* span which is removed */
1117 size_t cur
; /* how much has already been deleted */
1119 if (off
== p
->len
) {
1120 /* deletion starts at a piece boundry */
1125 /* deletion starts midway through a piece */
1126 midway_start
= true;
1129 before
= piece_alloc(txt
);
1134 /* skip all pieces which fall into deletion range */
1141 /* deletion stops at a piece boundry */
1145 /* cur > len: deletion stops midway through a piece */
1148 after
= piece_alloc(txt
);
1151 piece_init(after
, before
, p
->next
, p
->data
+ p
->len
- (cur
- len
), cur
- len
);
1155 /* we finally know which piece follows our newly allocated before piece */
1156 piece_init(before
, start
->prev
, after
, start
->data
, off
);
1159 Piece
*new_start
= NULL
, *new_end
= NULL
;
1171 span_init(&c
->new, new_start
, new_end
);
1172 span_init(&c
->old
, start
, end
);
1173 span_swap(txt
, &c
->old
, &c
->new);
1177 bool text_delete_range(Text
*txt
, Filerange
*r
) {
1178 if (!text_range_valid(r
))
1180 return text_delete(txt
, r
->start
, text_range_size(r
));
1183 /* preserve the current text content such that it can be restored by
1184 * means of undo/redo operations */
1185 void text_snapshot(Text
*txt
) {
1186 if (txt
->current_action
)
1187 txt
->last_action
= txt
->current_action
;
1188 txt
->current_action
= NULL
;
1193 void text_free(Text
*txt
) {
1198 Action
*hist
= txt
->history
;
1199 while (hist
&& hist
->prev
)
1202 Action
*later
= hist
->later
;
1207 for (Piece
*next
, *p
= txt
->pieces
; p
; p
= next
) {
1208 next
= p
->global_next
;
1212 for (Buffer
*next
, *buf
= txt
->buffers
; buf
; buf
= next
) {
1220 bool text_modified(Text
*txt
) {
1221 return txt
->saved_action
!= txt
->history
;
1224 bool text_sigbus(Text
*txt
, const char *addr
) {
1225 for (Buffer
*buf
= txt
->buffers
; buf
; buf
= buf
->next
) {
1226 if (buf
->type
== MMAP
&& buf
->data
<= addr
&& addr
< buf
->data
+ buf
->size
)
1232 enum TextNewLine
text_newline_type(Text
*txt
){
1233 if (!txt
->newlines
) {
1234 txt
->newlines
= TEXT_NEWLINE_NL
; /* default to UNIX style \n new lines */
1235 const char *start
= txt
->buf
? txt
->buf
->data
: NULL
;
1237 const char *nl
= memchr(start
, '\n', txt
->buf
->len
);
1238 if (nl
> start
&& nl
[-1] == '\r')
1239 txt
->newlines
= TEXT_NEWLINE_CRNL
;
1242 size_t nl
= lines_skip_forward(txt
, 0, 1, NULL
);
1243 if (nl
> 1 && text_byte_get(txt
, nl
-2, &c
) && c
== '\r')
1244 txt
->newlines
= TEXT_NEWLINE_CRNL
;
1248 return txt
->newlines
;
1251 const char *text_newline_char(Text
*txt
) {
1252 static const char *types
[] = {
1253 [TEXT_NEWLINE_NL
] = "\n",
1254 [TEXT_NEWLINE_CRNL
] = "\r\n",
1256 return types
[text_newline_type(txt
)];
1259 static bool text_iterator_init(Iterator
*it
, size_t pos
, Piece
*p
, size_t off
) {
1263 .start
= p
? p
->data
: NULL
,
1264 .end
= p
? p
->data
+ p
->len
: NULL
,
1265 .text
= p
? p
->data
+ off
: NULL
,
1267 return text_iterator_valid(it
);
1270 Iterator
text_iterator_get(Text
*txt
, size_t pos
) {
1272 Location loc
= piece_get_extern(txt
, pos
);
1273 text_iterator_init(&it
, pos
, loc
.piece
, loc
.off
);
1277 bool text_iterator_byte_get(Iterator
*it
, char *b
) {
1278 if (text_iterator_valid(it
)) {
1279 if (it
->start
<= it
->text
&& it
->text
< it
->end
) {
1282 } else if (it
->pos
== it
->piece
->text
->size
) { /* EOF */
1290 bool text_iterator_next(Iterator
*it
) {
1291 return text_iterator_init(it
, it
->pos
, it
->piece
? it
->piece
->next
: NULL
, 0);
1294 bool text_iterator_prev(Iterator
*it
) {
1295 return text_iterator_init(it
, it
->pos
, it
->piece
? it
->piece
->prev
: NULL
, 0);
1298 bool text_iterator_valid(const Iterator
*it
) {
1299 /* filter out sentinel nodes */
1300 return it
->piece
&& it
->piece
->text
;
1303 bool text_iterator_byte_next(Iterator
*it
, char *b
) {
1304 if (!text_iterator_valid(it
))
1307 /* special case for advancement to EOF */
1308 if (it
->text
== it
->end
&& !it
->piece
->next
->text
) {
1314 while (it
->text
>= it
->end
) {
1315 if (!text_iterator_next(it
))
1317 it
->text
= it
->start
;
1325 bool text_iterator_byte_prev(Iterator
*it
, char *b
) {
1326 if (!text_iterator_valid(it
))
1328 while (it
->text
== it
->start
) {
1329 if (!text_iterator_prev(it
))
1340 bool text_iterator_codepoint_next(Iterator
*it
, char *c
) {
1341 while (text_iterator_byte_next(it
, NULL
)) {
1342 if (ISUTF8(*it
->text
)) {
1351 bool text_iterator_codepoint_prev(Iterator
*it
, char *c
) {
1352 while (text_iterator_byte_prev(it
, NULL
)) {
1353 if (ISUTF8(*it
->text
)) {
1362 bool text_iterator_char_next(Iterator
*it
, char *c
) {
1363 if (!text_iterator_codepoint_next(it
, c
))
1365 mbstate_t ps
= { 0 };
1367 char buf
[MB_CUR_MAX
];
1368 size_t len
= text_bytes_get(it
->piece
->text
, it
->pos
, sizeof buf
, buf
);
1370 size_t wclen
= mbrtowc(&wc
, buf
, len
, &ps
);
1371 if (wclen
== (size_t)-1 && errno
== EILSEQ
) {
1373 } else if (wclen
== (size_t)-2) {
1375 } else if (wclen
== 0) {
1378 int width
= wcwidth(wc
);
1381 if (!text_iterator_codepoint_next(it
, c
))
1388 bool text_iterator_char_prev(Iterator
*it
, char *c
) {
1389 if (!text_iterator_codepoint_prev(it
, c
))
1392 char buf
[MB_CUR_MAX
];
1393 size_t len
= text_bytes_get(it
->piece
->text
, it
->pos
, sizeof buf
, buf
);
1395 mbstate_t ps
= { 0 };
1396 size_t wclen
= mbrtowc(&wc
, buf
, len
, &ps
);
1397 if (wclen
== (size_t)-1 && errno
== EILSEQ
) {
1399 } else if (wclen
== (size_t)-2) {
1401 } else if (wclen
== 0) {
1404 int width
= wcwidth(wc
);
1407 if (!text_iterator_codepoint_prev(it
, c
))
1414 bool text_byte_get(Text
*txt
, size_t pos
, char *buf
) {
1415 return text_bytes_get(txt
, pos
, 1, buf
);
1418 size_t text_bytes_get(Text
*txt
, size_t pos
, size_t len
, char *buf
) {
1423 text_iterate(txt
, it
, pos
) {
1426 size_t piece_len
= it
.end
- it
.text
;
1427 if (piece_len
> rem
)
1429 memcpy(cur
, it
.text
, piece_len
);
1436 char *text_bytes_alloc0(Text
*txt
, size_t pos
, size_t len
) {
1437 if (len
== SIZE_MAX
)
1439 char *buf
= malloc(len
+1);
1442 len
= text_bytes_get(txt
, pos
, len
, buf
);
1447 size_t text_size(Text
*txt
) {
1451 /* count the number of new lines '\n' in range [pos, pos+len) */
1452 static size_t lines_count(Text
*txt
, size_t pos
, size_t len
) {
1454 text_iterate(txt
, it
, pos
) {
1455 const char *start
= it
.text
;
1456 while (len
> 0 && start
< it
.end
) {
1457 size_t n
= MIN(len
, (size_t)(it
.end
- start
));
1458 const char *end
= memchr(start
, '\n', n
);
1464 len
-= end
- start
+ 1;
1474 /* skip n lines forward and return position afterwards */
1475 static size_t lines_skip_forward(Text
*txt
, size_t pos
, size_t lines
, size_t *lines_skipped
) {
1476 size_t lines_old
= lines
;
1477 text_iterate(txt
, it
, pos
) {
1478 const char *start
= it
.text
;
1479 while (lines
> 0 && start
< it
.end
) {
1480 size_t n
= it
.end
- start
;
1481 const char *end
= memchr(start
, '\n', n
);
1486 pos
+= end
- start
+ 1;
1495 *lines_skipped
= lines_old
- lines
;
1499 static void lineno_cache_invalidate(LineCache
*cache
) {
1504 size_t text_pos_by_lineno(Text
*txt
, size_t lineno
) {
1505 size_t lines_skipped
;
1506 LineCache
*cache
= &txt
->lines
;
1509 if (lineno
> cache
->lineno
) {
1510 cache
->pos
= lines_skip_forward(txt
, cache
->pos
, lineno
- cache
->lineno
, &lines_skipped
);
1511 cache
->lineno
+= lines_skipped
;
1512 } else if (lineno
< cache
->lineno
) {
1514 // TODO does it make sense to scan memory backwards here?
1515 size_t diff
= cache
->lineno
- lineno
;
1516 if (diff
< lineno
) {
1517 lines_skip_backward(txt
, cache
->pos
, diff
);
1520 cache
->pos
= lines_skip_forward(txt
, 0, lineno
- 1, &lines_skipped
);
1521 cache
->lineno
= lines_skipped
+ 1;
1523 return cache
->lineno
== lineno
? cache
->pos
: EPOS
;
1526 size_t text_lineno_by_pos(Text
*txt
, size_t pos
) {
1527 LineCache
*cache
= &txt
->lines
;
1528 if (pos
> txt
->size
)
1530 if (pos
< cache
->pos
) {
1531 size_t diff
= cache
->pos
- pos
;
1533 cache
->lineno
-= lines_count(txt
, pos
, diff
);
1535 cache
->lineno
= lines_count(txt
, 0, pos
) + 1;
1536 } else if (pos
> cache
->pos
) {
1537 cache
->lineno
+= lines_count(txt
, cache
->pos
, pos
- cache
->pos
);
1540 return cache
->lineno
;
1543 Mark
text_mark_set(Text
*txt
, size_t pos
) {
1545 return (Mark
)&txt
->begin
;
1546 if (pos
== txt
->size
)
1547 return (Mark
)&txt
->end
;
1548 Location loc
= piece_get_extern(txt
, pos
);
1551 return loc
.piece
->data
+ loc
.off
;
1554 size_t text_mark_get(Text
*txt
, Mark mark
) {
1559 if (mark
== (Mark
)&txt
->begin
)
1561 if (mark
== (Mark
)&txt
->end
)
1564 for (Piece
*p
= txt
->begin
.next
; p
->next
; p
= p
->next
) {
1565 if (p
->data
<= mark
&& mark
< p
->data
+ p
->len
)
1566 return cur
+ (mark
- p
->data
);
1573 size_t text_history_get(Text
*txt
, size_t index
) {
1574 for (Action
*a
= txt
->current_action
? txt
->current_action
: txt
->history
; a
; a
= a
->prev
) {
1576 Change
*c
= a
->change
;
1577 while (c
&& c
->next
)
1579 return c
? c
->pos
: EPOS
;