Skip to content

Commit

Permalink
text: add text_{v,}printf function
Browse files Browse the repository at this point in the history
Convenient way to insert formated data into a Text.
  • Loading branch information
martanne committed Oct 5, 2015
1 parent a05c754 commit bc56631
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
18 changes: 18 additions & 0 deletions text.c
Original file line number Diff line number Diff line change
Expand Up @@ -634,6 +634,24 @@ bool text_insert(Text *txt, size_t pos, const char *data, size_t len) {
return true;
}

bool text_printf(Text *txt, size_t pos, const char *format, ...) {
va_list ap;
va_start(ap, format);
bool ret = text_vprintf(txt, pos, format, ap);
va_end(ap);
return ret;
}

bool text_vprintf(Text *txt, size_t pos, const char *format, va_list ap) {
int len = vsnprintf(NULL, 0, format, ap);
if (len == -1)
return false;
char *buf = malloc(len+1);
bool ret = buf && (vsnprintf(buf, len+1, format, ap) == len) && text_insert(txt, pos, buf, len);
free(buf);
return ret;
}

static size_t action_undo(Text *txt, Action *a) {
size_t pos = EPOS;
for (Change *c = a->change; c; c = c->next) {
Expand Down
3 changes: 3 additions & 0 deletions text.h
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
#include <stdbool.h>
#include <time.h>
#include <unistd.h>
#include <stdarg.h>
#include <sys/types.h>
#include <sys/stat.h>

Expand Down Expand Up @@ -36,6 +37,8 @@ typedef struct {
Text *text_load(const char *filename);
/* file information at time of load or last save */
struct stat text_stat(Text*);
bool text_printf(Text*, size_t pos, const char *format, ...);
bool text_vprintf(Text*, size_t pos, const char *format, va_list ap);
/* insert `len' bytes starting from `data' at `pos' which has to be
* in the interval [0, text_size(txt)] */
bool text_insert(Text*, size_t pos, const char *data, size_t len);
Expand Down

0 comments on commit bc56631

Please sign in to comment.