Vis Editor API Documentation
Text
The core text management data structure which supports efficient
modifications and provides a byte string interface. Text positions
are represented as size_t. Valid addresses are in range [0,
text_size(txt)]. An invalid position is denoted by EPOS. Access to
the non-contigiuos pieces is available by means of an iterator interface
or a copy mechanism. Text revisions are tracked in an history graph.
Note
The text is assumed to be encoded in UTF-8.
Load
-
enum TextLoadMethod
Method used to load existing file content.
Values:
-
enumerator TEXT_LOAD_AUTO
Automatically chose best option.
-
enumerator TEXT_LOAD_READ
Read file content and copy it to an in-memory buffer.
Subsequent changes to the underlying file will have no effect on this text instance.
Note
Load time is linear in the file size.
-
enumerator TEXT_LOAD_MMAP
Memory map the file from disk.
Use file system / virtual memory subsystem as a caching layer.
Note
Load time is (almost) independent of the file size.
Warning
Inplace modifications of the underlying file will be reflected in the current text content. In particular, truncation will raise
SIGBUSand result in data loss.
-
enumerator TEXT_LOAD_AUTO
-
Text *text_load(const char *filename)
Create a text instance populated with the given file content.
Note
Equivalent to
text_load_method(filename, TEXT_LOAD_AUTO).
-
Text *text_load_method(const char *filename, enum TextLoadMethod method)
Create a text instance populated with the given file content.
- Parameters:
filename – The name of the file to load, if
NULLan empty text is created.method – How the file content should be loaded.
- Returns:
The new Text object or
NULLin case of an error.Note
When attempting to load a non-regular file,
errnowill be set to:EISDIRfor a directory.ENOTSUPotherwise.
-
Text *text_loadat_method(int dirfd, const char *filename, enum TextLoadMethod)
-
void text_free(Text*)
Release all resources associated with this text instance.
State
-
size_t text_size(const Text*)
Return the size in bytes of the whole text.
-
struct stat text_stat(const Text*)
Get file information at time of load or last save, whichever happened more recently.
Note
If an empty text instance was created using
text_load(NULL)and it has not yet been saved, an all zerostruct statwill be returned.- Returns:
See
stat(2)for details.
-
bool text_modified(const Text*)
Query whether the text contains any unsaved modifications.
Modify
-
bool text_insert(Text *txt, size_t pos, const char *data, size_t len)
Insert data at the given byte position.
- Parameters:
txt – The text instance to modify.
pos – The absolute byte position.
data – The data to insert.
len – The length of the data in bytes.
- Returns:
Whether the insertion succeeded.
-
bool text_delete(Text *txt, size_t pos, size_t len)
Delete data at given byte position.
- Parameters:
txt – The text instance to modify.
pos – The absolute byte position.
len – The number of bytes to delete, starting from
pos.
- Returns:
Whether the deletion succeeded.
-
bool text_delete_range(Text *txt, const Filerange*)
-
bool text_printf(Text *txt, size_t pos, const char *format, ...)
-
bool text_appendf(Text *txt, const char *format, ...)
Access
The individual pieces of the text are not necessarily stored in a contiguous memory block. These functions perform a copy to such a region.
-
bool text_byte_get(const Text *txt, size_t pos, char *byte)
Get byte stored at
pos.- Parameters:
txt – The text instance to modify.
pos – The absolute position.
byte – Destination address to store the byte.
- Returns:
Whether
poswas valid andbyteupdated accordingly.Note
Unlike
text_iterator_byte_get()this function does not return an artificial NUL byte at EOF.
-
size_t text_bytes_get(const Text *txt, size_t pos, size_t len, char *buf)
Store at most
lenbytes starting fromposintobuf.- Parameters:
txt – The text instance to modify.
pos – The absolute starting position.
len – The length in bytes.
buf – The destination buffer.
- Returns:
The number of bytes (
<= len) stored atbuf.Warning
bufwill not be NUL terminated.
-
char *text_bytes_alloc0(const Text *txt, size_t pos, size_t len)
Fetch text range into newly allocate memory region.
- Parameters:
txt – The text instance to modify.
pos – The absolute starting position.
len – The length in bytes.
- Returns:
A contiguous NUL terminated buffer holding the requested range, or
NULLin error case.Warning
The returned pointer must be freed by the caller.
Iterator
An iterator points to a given text position and provides interfaces to
adjust said position or read the underlying byte value. Functions which
take a char pointer will generally assign the byte value after
the iterator was updated.
-
struct Iterator
Iterator used to navigate the buffer content.
Captures the position within a Piece.
Note
Should be treated as an opaque type.
Warning
Any change to the Text will invalidate the iterator state.
Byte
Note
For a read attempt at EOF (i.e. text_size) an artificial NUL
byte which is not actually part of the file is returned.
Codepoint
These functions advance to the next/previous leading byte of an UTF-8
encoded Unicode codepoint by skipping over all continuation bytes of
the form 10xxxxxx.
Grapheme Clusters
These functions advance to the next/previous grapheme cluster.
Note
The grapheme cluster boundaries are currently not implemented
according to UAX#29 rules.
Instead a base character followed by arbitrarily many combining
character as reported by wcwidth(3) are skipped.
Lines
Translate between 1 based line numbers and 0 based byte offsets.
-
size_t text_pos_by_lineno(Text*, size_t lineno)
-
size_t text_lineno_by_pos(Text*, size_t pos)
History
Interfaces to the history graph.
-
bool text_snapshot(Text*)
Create a text snapshot, that is a vertex in the history graph.
-
size_t text_undo(Text*)
Revert to previous snapshot along the main branch.
Note
Takes an implicit snapshot.
- Returns:
The position of the first change or
EPOS, if already at the oldest state i.e. there was nothing to undo.
-
size_t text_redo(Text*)
Reapply an older change along the main branch.
Note
Takes an implicit snapshot.
- Returns:
The position of the first change or
EPOS, if already at the newest state i.e. there was nothing to redo.
-
size_t text_earlier(Text*)
-
size_t text_later(Text*)
-
size_t text_restore(Text*, time_t)
Restore the text to the state closest to the time given.
-
time_t text_state(const Text*)
Get creation time of current state.
Note
TODO: This is currently not the same as the time of the last snapshot.
Marks
A mark keeps track of a text position. Subsequent text changes will update all marks placed after the modification point. Reverting to an older text state will hide all affected marks, redoing the changes will restore them.
Warning
Due to an optimization cached modifications (i.e. no text_snapshot
was performed between setting the mark and issuing the changes) might
not adjust mark positions accurately.
-
typedef uintptr_t Mark
A mark.
-
EMARK
An invalid mark, lookup of which will yield
EPOS.
Save
-
enum TextSaveMethod
Method used to save the text.
Values:
-
enumerator TEXT_SAVE_AUTO
Automatically chose best option.
-
enumerator TEXT_SAVE_ATOMIC
Save file atomically using
rename(2).Creates a temporary file, restores all important meta data, before moving it atomically to its final (possibly already existing) destination using
rename(2). For new files, permissions are set to0666 & ~umask.Warning
This approach does not work if:
The file is a symbolic link.
The file is a hard link.
File ownership can not be preserved.
File group can not be preserved.
Directory permissions do not allow creation of a new file.
POSIX ACL can not be preserved (if enabled).
SELinux security context can not be preserved (if enabled).
-
enumerator TEXT_SAVE_INPLACE
Overwrite file in place.
Warning
I/O failure might cause data loss.
-
enumerator TEXT_SAVE_AUTO
-
void text_mark_current_revision(Text*)
Marks the current text revision as saved.
-
bool text_save_begin(TextSave*)
Setup a sequence of write operations.
The returned
TextSavepointer can be used to write multiple, possibly non-contiguous, file ranges.Warning
For every call to
text_save_beginthere must be exactly one matching call to eithertext_save_commitortext_save_cancelto release the underlying resources.
-
ssize_t text_save_write_range(TextSave*, const Filerange*)
Write file range.
- Returns:
The number of bytes written or
-1in case of an error.
-
bool text_save_commit(TextSave*)
Commit changes to disk.
- Returns:
Whether changes have been saved.
Note
Releases the underlying resources and frees the given
TextSavepointer which must no longer be used.
-
void text_save_cancel(TextSave*)
Abort a save operation.
Note
Does not guarantee to undo the previous writes (they might have been performed in-place). However, it releases the underlying resources and frees the given
TextSavepointer which must no longer be used.
-
ssize_t text_write_range(const Text*, const Filerange*, int fd)
Write file range to file descriptor.
- Returns:
The number of bytes written or
-1in case of an error.
-
text_save_default(...)
-
struct TextSave
- #include <text.h>
Miscellaneous
-
bool text_mmaped(const Text*, const char *ptr)
Check whether
ptris part of a memory mapped region associated with this text instance.
-
ssize_t write_all(int fd, const char *buf, size_t count)
Write complete buffer to file descriptor.
- Returns:
The number of bytes written or
-1in case of an error.
View
Provides a viewport of a text instance and manages selections.
Lifecycle
-
bool view_init(struct Win*, Text*)
-
void view_free(View*)
-
void view_reload(View*, Text*)
Viewport
The cursor of the primary selection is always visible.
-
bool view_coord_get(View *view, size_t pos, Line **line, int *row, int *col)
Get window coordinate of text position.
- Parameters:
view – The view to manipulate.
pos – The position to query.
line – Will be updated with screen line on which
posresides.row – Will be updated with zero based window row on which
posresides.col – Will be updated with zero based window column on which
posresides.
- Returns:
Whether
posis visible. If not, the pointer arguments are left unmodified.
-
size_t view_screenline_goto(View*, int n)
Get position at the start of the
n-th window line, counting from 1.
-
size_t view_slide_up(View*, int lines)
-
size_t view_slide_down(View*, int lines)
-
size_t view_scroll_up(View*, int lines)
-
size_t view_scroll_down(View*, int lines)
-
size_t view_scroll_page_up(View*)
-
size_t view_scroll_page_down(View*)
-
size_t view_scroll_halfpage_up(View*)
-
size_t view_scroll_halfpage_down(View*)
-
void view_redraw_top(View*)
-
void view_redraw_center(View*)
-
void view_redraw_bottom(View*)
-
void view_scroll_to(View*, size_t pos)
-
VIEW_VIEWPORT_GET(v)
Get the currently displayed text range.
Dimension
-
bool view_resize(View*, int width, int height)
Draw
-
void view_draw(View*)
-
bool view_update(View*)
Selections
A selection is a non-empty, directed range with two endpoints called cursor and anchor. A selection can be anchored in which case the anchor remains fixed while only the position of the cursor is adjusted. For non-anchored selections both endpoints are updated. A singleton selection covers one character on which both cursor and anchor reside. There always exists a primary selection which remains visible (i.e. changes to its position will adjust the viewport).
Creation and Destruction
-
Selection *view_selections_new(View*, size_t pos)
Create a new singleton selection at the given position.
Note
New selections are created non-anchored.
Warning
Fails if position is already covered by a selection.
-
Selection *view_selections_new_force(View*, size_t pos)
Create a new selection even if position is already covered by an existing selection.
Note
This should only be used if the old selection is eventually disposed.
-
bool view_selections_dispose(Selection*)
Dispose an existing selection.
Warning
Not applicable for the last existing selection.
-
bool view_selections_dispose_force(Selection*)
Forcefully dispose an existing selection.
If called for the last existing selection, it will be reduced and marked for destruction. As soon as a new selection is created this one will be disposed.
-
Selection *view_selection_disposed(View*)
Query state of primary selection.
If the primary selection was marked for destruction, return it and clear destruction flag.
-
void view_selections_dispose_all(View*)
Dispose all but the primary selection.
-
void view_selections_normalize(View*)
Dispose all invalid and merge all overlapping selections.
Cover
-
Filerange view_selections_get(Selection*)
Get an inclusive range of the selection cover.
-
bool view_selections_set(Selection*, const Filerange*)
Set selection cover.
Updates both cursor and anchor.
-
void view_selection_clear(Selection*)
Reduce selection to character currently covered by the cursor.
Note
Sets selection to non-anchored mode.
-
void view_selections_clear_all(View*)
Reduce all currently active selections.
-
void view_selections_flip(Selection*)
Flip selection orientation.
Swap cursor and anchor.
Note
Has no effect on singleton selections.
Anchor
Warning
doxygengroup: Cannot find group “view_anchor” in doxygen xml output for project “vis” from directory: build/doxygen/xml
Cursor
Selection endpoint to which cursor motions apply.
Properties
-
size_t view_cursors_pos(Selection*)
Get position of selection cursor.
-
size_t view_cursors_line(Selection*)
Get 1-based line number of selection cursor.
-
size_t view_cursors_col(Selection*)
Get 1-based column of selection cursor.
Note
Counts the number of graphemes on the logical line up to the cursor position.
Placement
-
void view_cursors_to(Selection*, size_t pos)
Place cursor of selection at
pos.Note
If the selection is not anchored, both selection endpoints will be adjusted to form a singleton selection covering one character starting at pos. Otherwise only the selection cursor will be changed while the anchor remains fixed.
If primary position was not visible before, we attempt to show the surrounding context. The viewport will be adjusted such that the line holding the primary cursor is shown in the middle of the window.
-
void view_cursors_scroll_to(Selection*, size_t pos)
Adjusts window viewport until the requested position becomes visible.
Note
For all but the primary selection this is equivalent to
view_selection_to.Warning
Repeatedly redraws the window content. Should only be used for short distances between current cursor position and destination.
-
void view_cursors_place(Selection *s, size_t line, size_t col)
Place cursor on given (line, column) pair.
- Parameters:
s – the selection to manipulate
line – the 1-based line number
col – the 1 based column
Note
Except for the different addressing format this is equivalent to view_selection_to.
-
int view_cursors_cell_set(Selection*, int cell)
Place selection cursor on zero based window cell index.
Warning
Fails if the selection cursor is currently not visible.
Motions
These functions perform motions based on the current selection cursor position.
-
size_t view_line_down(Selection*)
-
size_t view_line_up(Selection*)
-
size_t view_screenline_down(Selection*)
-
size_t view_screenline_up(Selection*)
-
size_t view_screenline_begin(Selection*)
-
size_t view_screenline_middle(Selection*)
-
size_t view_screenline_end(Selection*)
Primary Selection
These are convenience function which operate on the primary selection.
-
size_t view_cursor_get(View*)
Get cursor position of primary selection.
Save and Restore
-
Filerange view_regions_restore(View*, SelectionRegion*)
-
bool view_regions_save(View*, Filerange*, SelectionRegion*)
Style
-
void win_options_set(struct Win*, enum UiOption)
-
bool view_breakat_set(View*, const char *breakat)
-
void view_tabwidth_set(View*, int tabwidth)
Set how many spaces are used to display a tab
\tcharacter.
-
void win_style(struct Win*, enum UiStyle, size_t start, size_t end, bool keep_non_default)
Apply a style to a text range.
Buffer
A dynamically growing buffer storing arbitrary data.
Note
Used for Register, not Text content.
Functions
-
bool buffer_put(Buffer*, const void *data, size_t len)
Set buffer content, growing the buffer as needed.
-
bool buffer_appendf(Buffer*, const char *fmt, ...)
Append formatted buffer content, ensures NUL termination on success.
-
struct Buffer
- #include <buffer.h>
A dynamically growing buffer storing arbitrary data.
Array
A dynamically growing array, there exist two typical ways to use it:
To hold pointers to externally allocated memory regions.
Use
array_initfor initialization, an element has the size of a pointer. Use the functions suffixed with_ptrto manage your pointers. The cleanup functionarray_release_fullmust only be used with this type of array.To hold arbitrary sized objects.
Use
array_init_sizedto specify the size of a single element. Use the regular (i.e. without the_ptrsuffix) functions to manage your objects. Functions likearray_addandarray_setwill copy the object into the array,array_getwill return a pointer to the object stored within the array.
Functions
-
void array_init(Array*)
Initialize an Array object to store pointers.
Note
Is equivalent to
array_init_sized(arr, sizeof(void*)).
-
void array_init_sized(Array*, size_t elem_size)
Initialize an Array object to store arbitrarily sized objects.
-
void array_init_from(Array*, const Array *from)
Initialize Array by using the same element size as in
from.
-
void array_release_full(Array*)
Release storage space and call
free(3)for each stored pointer.Warning
Assumes array elements to be pointers.
-
void *array_get(const Array*, size_t idx)
Get array element.
Warning
Returns a pointer to the allocated array region. Operations which might cause reallocations (e.g. the insertion of new elements) might invalidate the pointer.
-
bool array_set(Array*, size_t idx, void *item)
Set array element.
Note
Copies the
iteminto the Array. IfitemisNULLthe corresponding memory region will be cleared.
-
bool array_set_ptr(Array*, size_t idx, void *item)
Store the address to which
itempoints to into the array.
-
bool array_remove(Array*, size_t idx)
Remove an element by index.
Note
Might not shrink underlying memory region.
-
bool array_truncate(Array*, size_t length)
Remove all elements with index greater or equal to
length, keep allocated memory.
-
bool array_resize(Array*, size_t length)
Change length.
Note
Has to be less or equal than the capacity. Newly accessible elements preserve their previous values.
-
void array_sort(Array*, int (*compar)(const void*, const void*))
Sort array, the comparision function works as for
qsort(3).
-
bool array_push(Array*, void *item)
Push item onto the top of the stack.
Note
Is equivalent to
array_add(arr, item).
-
struct Array
- #include <array.h>
A dynamically growing array.
Map
Crit-bit tree based map which supports unique prefix queries and ordered iteration.
Functions
-
Map *map_new(void)
Allocate a new map.
-
void *map_get(const Map *map, const char *key)
Lookup a value, returns
NULLif not found.- Parameters:
map – The map to search within.
key – The key to look up.
-
void *map_first(const Map *map, const char **key)
Get first element of the map, or
NULLif empty.- Parameters:
map – The map to query.
key – Updated with the key of the first element.
-
void *map_closest(const Map *map, const char *prefix)
Lookup element by unique prefix match.
- Parameters:
map – The map to search within.
prefix – The prefix to search for.
- Returns:
The corresponding value, if the given prefix is unique. Otherwise
NULL. If no such prefix exists, thenerrnois set toENOENT.
-
bool map_contains(const Map *map, const char *prefix)
Check whether the map contains the given prefix, or whether it can be extended to match a key of a map element.
- Parameters:
map – The map to check.
prefix – The prefix to search for.
-
bool map_put(Map *map, const char *key, const void *value)
Store a key value pair in the map.
- Parameters:
map – The map to store the key-value pair in.
key – The key to store.
value – The value associated with the key.
- Returns:
False if we run out of memory (
errno = ENOMEM), or if the key already appears in the map (errno = EEXIST).
-
void *map_delete(Map *map, const char *key)
Remove a map element.
- Parameters:
map – The map to remove the element from.
key – The key of the element to remove.
- Returns:
The removed entry or
NULLif no such element exists.
-
bool map_copy(Map *dest, Map *src)
Copy all entries from
srcintodest, overwrites existing entries indest.- Parameters:
dest – The destination map.
src – The source map.
-
void map_iterate(const Map *map, bool (*handle)(const char *key, void *value, void *data), const void *data)
Ordered iteration over a map.
Invokes the passed callback for every map entry. If
handlereturns false, the iteration will stop.- Parameters:
map – The map to iterate over.
handle – A function invoked for every map element.
data – A context pointer, passed as last argument to
handle.
-
const Map *map_prefix(const Map *map, const char *prefix)
Get a sub map matching a prefix.
- Parameters:
map – The map to get the sub-map from.
prefix – The prefix to match.
Warning
This returns a pointer into the original map.
Do not alter the map while using the return value.
-
bool map_empty(const Map *map)
Test whether the map is empty (contains no elements).
- Parameters:
map – The map to check.
-
void map_clear(Map *map)
Empty the map.
- Parameters:
map – The map to clear.
-
void map_free(Map *map)
Release all memory associated with this map.
- Parameters:
map – The map to free.
-
void map_free_full(Map *map)
Call
free(3)for every map element, then free the map itself.- Parameters:
map – The map to free its elements and itself.
Warning
Assumes map elements to be pointers.