forked from lastpass/lastpass-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathterminal.c
More file actions
61 lines (54 loc) · 1.07 KB
/
Copy pathterminal.c
File metadata and controls
61 lines (54 loc) · 1.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*
* Copyright (c) 2014 LastPass. All Rights Reserved.
*
*
*/
#include "terminal.h"
#include "util.h"
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include <stdarg.h>
#include <stdio.h>
static void filter_ansi(FILE *file, const char *fmt, va_list args)
{
_cleanup_free_ char *str = NULL;
size_t len, i, j;
if (isatty(fileno(file))) {
vfprintf(file, fmt, args);
return;
}
len = xvasprintf(&str, fmt, args);
for (i = 0; i < len - 2; ++i) {
if (str[i] == '\x1b' && str[i + 1] == '[') {
str[i] = str[i + 1] = '\0';
for (j = i + 2; j < len; ++j) {
if (isalpha(str[j]))
break;
str[j] = '\0';
}
str[j] = '\0';
}
}
for (i = 0; i < len; i = j) {
fputs(&str[i], file);
for (j = i + strlen(&str[i]); j < len; ++j) {
if (str[j] != '\0')
break;
}
}
}
void terminal_printf(const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
filter_ansi(stdout, fmt, args);
va_end(args);
}
void terminal_fprintf(FILE *file, const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
filter_ansi(file, fmt, args);
va_end(args);
}