aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMarc André Tanner <mat@brain-dump.org>2015-09-22 16:32:41 +0200
committerMarc André Tanner <mat@brain-dump.org>2015-10-05 16:54:05 +0200
commitbc5663168d8fd42704d6a55af5a8c9992c75f6af (patch)
treebfe642efc4be3d796d6f45fa0c8e107cfdda7026
parenta05c75426f5fecd38007b2186b55153bb30a7f93 (diff)
downloadvis-bc5663168d8fd42704d6a55af5a8c9992c75f6af.tar.gz
vis-bc5663168d8fd42704d6a55af5a8c9992c75f6af.tar.xz
text: add text_{v,}printf function
Convenient way to insert formated data into a Text.
-rw-r--r--text.c18
-rw-r--r--text.h3
2 files changed, 21 insertions, 0 deletions
diff --git a/text.c b/text.c
index 8653cc0..94a32f9 100644
--- a/text.c
+++ b/text.c
@@ -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) {
diff --git a/text.h b/text.h
index 48b630f..8bbb32f 100644
--- a/text.h
+++ b/text.h
@@ -4,6 +4,7 @@
#include <stdbool.h>
#include <time.h>
#include <unistd.h>
+#include <stdarg.h>
#include <sys/types.h>
#include <sys/stat.h>
@@ -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);