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 SIGBUS and result in data loss.

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 NULL an empty text is created.

  • method – How the file content should be loaded.

Returns:

The new Text object or NULL in case of an error.

Note

When attempting to load a non-regular file, errno will be set to:

  • EISDIR for a directory.

  • ENOTSUP otherwise.

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 zero struct stat will 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 pos was valid and byte updated 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 len bytes starting from pos into buf.

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 at buf.

Warning

buf will 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 NULL in 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.

Iterator text_iterator_get(const Text*, size_t pos)
bool text_iterator_init(const Text*, Iterator*, size_t pos)
const Text *text_iterator_text(const Iterator*)
bool text_iterator_valid(const Iterator*)
bool text_iterator_has_next(const Iterator*)
bool text_iterator_has_prev(const Iterator*)
bool text_iterator_next(Iterator*)
bool text_iterator_prev(Iterator*)

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.

bool text_iterator_byte_get(const Iterator*, char *b)
bool text_iterator_byte_prev(Iterator*, char *b)
bool text_iterator_byte_next(Iterator*, char *b)
bool text_iterator_byte_find_prev(Iterator*, char b)
bool text_iterator_byte_find_next(Iterator*, char b)

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.

bool text_iterator_codepoint_next(Iterator *it, char *c)
bool text_iterator_codepoint_prev(Iterator *it, char *c)

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.

bool text_iterator_char_next(Iterator*, char *c)
bool text_iterator_char_prev(Iterator*, char *c)

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.

Mark text_mark_set(Text *txt, size_t pos)

Set a mark.

Note

Setting a mark to text_size will always return the current text size upon lookup.

Parameters:
  • txt – The text instance to modify.

  • pos – The position at which to store the mark.

Returns:

The mark or EMARK if an invalid position was given.

size_t text_mark_get(const Text *txt, Mark mark)

Lookup a mark.

Parameters:
  • txt – The text instance to modify.

  • mark – The mark to look up.

Returns:

The byte position or EPOS for an invalid mark.

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 to 0666 & ~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.

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 TextSave pointer can be used to write multiple, possibly non-contiguous, file ranges.

Warning

For every call to text_save_begin there must be exactly one matching call to either text_save_commit or text_save_cancel to release the underlying resources.

ssize_t text_save_write_range(TextSave*, const Filerange*)

Write file range.

Returns:

The number of bytes written or -1 in 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 TextSave pointer 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 TextSave pointer 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 -1 in case of an error.

text_save_default(...)
struct TextSave
#include <text.h>

Miscellaneous

bool text_mmaped(const Text*, const char *ptr)

Check whether ptr is 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 -1 in 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 pos resides.

  • row – Will be updated with zero based window row on which pos resides.

  • col – Will be updated with zero based window column on which pos resides.

Returns:

Whether pos is 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.

void view_selections_set_all(View *view, Array *array, bool anchored)

Replace currently active selections.

Parameters:
  • view – The view to manipulate.

  • array – The array of Filerange objects.

  • anchored – Whether all selection should be anchored.

Array view_selections_get_all(View*)

Get array containing a Fileranges for each selection.

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 \t character.

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

void buffer_release(Buffer*)

Release all resources, reinitialize buffer.

bool buffer_reserve(Buffer*, size_t size)

Reserve space to store at least size bytes.

bool buffer_grow(Buffer*, size_t len)

Reserve space for at least len more bytes.

bool buffer_terminate(Buffer*)

If buffer is non-empty, make sure it is NUL terminated.

bool buffer_put(Buffer*, const void *data, size_t len)

Set buffer content, growing the buffer as needed.

bool buffer_put0(Buffer*, const char *data)

Set buffer content to NUL terminated data.

bool buffer_remove(Buffer*, size_t pos, size_t len)

Remove len bytes starting at pos.

bool buffer_insert0(Buffer*, size_t pos, const char *data)

Insert NUL-terminated data at pos.

bool buffer_append(Buffer*, const void *data, size_t len)

Append further content to the end.

bool buffer_append0(Buffer*, const char *data)

Append NUL-terminated data.

bool buffer_appendf(Buffer*, const char *fmt, ...)

Append formatted buffer content, ensures NUL termination on success.

size_t buffer_length0(Buffer*)

Return length of a buffer without trailing NUL byte.

const char *buffer_content0(Buffer*)

Get pointer to buffer data.

Guaranteed to return a NUL terminated string even if buffer is empty.

ssize_t read_into_buffer(void *context, char *data, size_t len)

read(3p) like interface for reading into a Buffer (context)

struct Buffer
#include <buffer.h>

A dynamically growing buffer storing arbitrary data.

Public Members

char *data

Data pointer, NULL if empty.

size_t len

Current length of data.

size_t size

Maximal capacity of the buffer.

Array

A dynamically growing array, there exist two typical ways to use it:

  1. To hold pointers to externally allocated memory regions.

    Use array_init for initialization, an element has the size of a pointer. Use the functions suffixed with _ptr to manage your pointers. The cleanup function array_release_full must only be used with this type of array.

  2. To hold arbitrary sized objects.

    Use array_init_sized to specify the size of a single element. Use the regular (i.e. without the _ptr suffix) functions to manage your objects. Functions like array_add and array_set will copy the object into the array, array_get will 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(Array*)

Release storage space.

Reinitializes Array object.

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_clear(Array*)

Empty array, keep allocated memory.

bool array_reserve(Array*, size_t count)

Reserve memory to store at least count elements.

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 item into the Array. If item is NULL the corresponding memory region will be cleared.

void *array_get_ptr(const Array*, size_t idx)

Dereference pointer stored in array element.

bool array_set_ptr(Array*, size_t idx, void *item)

Store the address to which item points to into the array.

bool array_add(Array*, void *item)

Add element to the end of the array.

bool array_add_ptr(Array*, void *item)

Add pointer to the end of 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).

void *array_pop(Array*)

Get and remove item at the top of the stack.

Warning

The same ownership rules as for array_get apply.

void *array_peek(const Array*)

Get item at the top of the stack without removing it.

Warning

The same ownership rules as for array_get apply.

struct Array
#include <array.h>

A dynamically growing array.

Public Members

char *items
size_t elem_size

Data pointer, NULL if empty.

size_t len

Size of one array element.

size_t count

Number of currently stored items.

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 NULL if 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 NULL if 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, then errno is set to ENOENT.

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 NULL if no such element exists.

bool map_copy(Map *dest, Map *src)

Copy all entries from src into dest, overwrites existing entries in dest.

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 handle returns 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.