dte test coverage


Directory: ./
File: src/main.c
Date: 2025-07-01 18:22:46
Exec Total Coverage
Lines: 176 307 57.3%
Functions: 11 15 73.3%
Branches: 83 195 42.6%

Line Branch Exec Source
1 #include <errno.h>
2 #include <fcntl.h>
3 #include <stdbool.h>
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <string.h>
7 #include <sys/stat.h>
8 #include <sys/utsname.h>
9 #include <unistd.h>
10 #include "block.h"
11 #include "command/cache.h"
12 #include "command/error.h"
13 #include "commands.h"
14 #include "compat.h"
15 #include "compiler.h"
16 #include "config.h"
17 #include "editor.h"
18 #include "encoding.h"
19 #include "file-history.h"
20 #include "frame.h"
21 #include "history.h"
22 #include "load-save.h"
23 #include "move.h"
24 #include "palette.h"
25 #include "search.h"
26 #include "showkey.h"
27 #include "signals.h"
28 #include "syntax/state.h"
29 #include "syntax/syntax.h"
30 #include "tag.h"
31 #include "terminal/input.h"
32 #include "terminal/ioctl.h"
33 #include "terminal/key.h"
34 #include "terminal/mode.h"
35 #include "terminal/output.h"
36 #include "terminal/paste.h"
37 #include "terminal/terminal.h"
38 #include "trace.h"
39 #include "ui.h"
40 #include "util/debug.h"
41 #include "util/exitcode.h"
42 #include "util/fd.h"
43 #include "util/log.h"
44 #include "util/macros.h"
45 #include "util/path.h"
46 #include "util/progname.h"
47 #include "util/strtonum.h"
48 #include "util/xmalloc.h"
49 #include "util/xreadwrite.h"
50 #include "util/xsnprintf.h"
51 #include "version.h"
52 #include "view.h"
53 #include "window.h"
54
55 static void cleanup_handler(void *userdata)
56 {
57 EditorState *e = userdata;
58 set_fatal_error_cleanup_handler(NULL, NULL);
59 if (!e->child_controls_terminal) {
60 ui_end(e, true);
61 term_cooked();
62 }
63 }
64
65 1 static ExitCode list_builtin_configs(void)
66 {
67 1 String str = dump_builtin_configs();
68 1 BUG_ON(!str.buffer);
69 1 ExitCode e = ec_write_stdout(str.buffer, str.len);
70 1 string_free(&str);
71 1 return e;
72 }
73
74 2 static ExitCode dump_builtin_config(const char *name)
75 {
76 2 const BuiltinConfig *cfg = get_builtin_config(name);
77
2/2
✓ Branch 0 (2→3) taken 1 times.
✓ Branch 1 (2→4) taken 1 times.
2 if (!cfg) {
78 1 return ec_usage_error("no built-in config with name '%s'", name);
79 }
80 1 return ec_write_stdout(cfg->text.data, cfg->text.length);
81 }
82
83 2 static ExitCode lint_syntax(const char *filename, bool extra_lint)
84 {
85 2 EditorState *e = init_editor_state(getenv("HOME"), getenv("DTE_HOME"));
86 2 e->err.print_to_stderr = true;
87 2 BUG_ON(e->status != EDITOR_INITIALIZING);
88
89
1/2
✓ Branch 0 (7→8) taken 2 times.
✗ Branch 1 (7→9) not taken.
2 SyntaxLoadFlags flags = SYN_MUST_EXIST | (extra_lint ? SYN_LINT : 0);
90 2 const Syntax *syntax = load_syntax_file(e, filename, flags);
91
3/4
✓ Branch 0 (10→11) taken 1 times.
✓ Branch 1 (10→15) taken 1 times.
✓ Branch 2 (11→12) taken 1 times.
✗ Branch 3 (11→15) not taken.
2 bool ok = syntax && e->err.nr_errors == 0;
92
93 1 if (ok) {
94 1 const size_t n = syntax->states.count;
95
1/2
✓ Branch 0 (12→13) taken 1 times.
✗ Branch 1 (12→14) not taken.
1 const char *plural = (n == 1) ? "" : "s";
96 1 const char *name = syntax->name;
97 1 printf("OK: loaded syntax '%s' with %zu state%s\n", name, n, plural);
98 }
99
100 2 free_editor_state(e);
101
2/2
✓ Branch 0 (16→17) taken 1 times.
✓ Branch 1 (16→18) taken 1 times.
2 return ok ? EC_OK : EC_DATA_ERROR;
102 }
103
104 1 static ExitCode init_std_fds(int std_fds[2])
105 {
106 1 FILE *streams[3] = {stdin, stdout, stderr};
107
1/2
✓ Branch 0 (27→3) taken 1 times.
✗ Branch 1 (27→28) not taken.
1 for (int i = 0; i < ARRAYLEN(streams); i++) {
108
1/2
✗ Branch 0 (4→5) not taken.
✓ Branch 1 (4→6) taken 1 times.
1 if (is_controlling_tty(i)) {
109 continue;
110 }
111
112
1/2
✗ Branch 0 (6→7) not taken.
✓ Branch 1 (6→8) taken 1 times.
1 if (i < STDERR_FILENO) {
113 // Try to create a duplicate fd for redirected stdin/stdout; to
114 // allow reading/writing after freopen(3) closes the original
115 1 int fd = fcntl(i, F_DUPFD_CLOEXEC, 3);
116
1/4
✗ Branch 0 (9→10) not taken.
✓ Branch 1 (9→12) taken 1 times.
✗ Branch 2 (10→11) not taken.
✗ Branch 3 (10→12) not taken.
1 if (fd == -1 && errno != EBADF) {
117 return ec_error("fcntl", EC_OS_ERROR);
118 }
119 1 std_fds[i] = fd;
120 }
121
122 // Ensure standard streams are connected to the terminal during
123 // editor operation, regardless of how they were redirected
124
2/4
✓ Branch 0 (12→13) taken 1 times.
✗ Branch 1 (12→14) not taken.
✓ Branch 2 (15→16) taken 1 times.
✗ Branch 3 (15→19) not taken.
2 if (unlikely(!freopen("/dev/tty", i ? "w" : "r", streams[i]))) {
125 1 const char *err = strerror(errno);
126 1 fprintf(stderr, "Failed to open /dev/tty for fd %d: %s\n", i, err);
127 1 return EC_IO_ERROR;
128 }
129
130 int new_fd = fileno(streams[i]);
131 if (unlikely(new_fd != i)) {
132 // This should never happen in a single-threaded program.
133 // freopen() should call fclose() followed by open() and
134 // POSIX requires a successful call to open() to return the
135 // lowest available file descriptor.
136 fprintf(stderr, "freopen() changed fd from %d to %d\n", i, new_fd);
137 return EC_OS_ERROR;
138 }
139
140 if (unlikely(!is_controlling_tty(new_fd))) {
141 return ec_error("tcgetpgrp", EC_OS_ERROR);
142 }
143 }
144
145 return EC_OK;
146 }
147
148 8 static ExitCode init_std_fds_headless(int std_fds[2])
149 {
150 8 FILE *streams[] = {stdin, stdout};
151
2/2
✓ Branch 0 (16→3) taken 16 times.
✓ Branch 1 (16→17) taken 8 times.
24 for (int i = 0; i < ARRAYLEN(streams); i++) {
152
1/2
✓ Branch 0 (4→5) taken 16 times.
✗ Branch 1 (4→10) not taken.
16 if (!isatty(i)) {
153 // Try to duplicate redirected stdin/stdout, as described
154 // in init_std_fds()
155 16 int fd = fcntl(i, F_DUPFD_CLOEXEC, 3);
156
1/4
✗ Branch 0 (6→7) not taken.
✓ Branch 1 (6→9) taken 16 times.
✗ Branch 2 (7→8) not taken.
✗ Branch 3 (7→9) not taken.
16 if (fd == -1 && errno != EBADF) {
157 return ec_error("fcntl", EC_OS_ERROR);
158 }
159 16 std_fds[i] = fd;
160 }
161 // Always reopen stdin and stdout as /dev/null, regardless of
162 // whether they were duplicated above
163
3/4
✓ Branch 0 (10→11) taken 8 times.
✓ Branch 1 (10→12) taken 8 times.
✗ Branch 2 (13→14) not taken.
✓ Branch 3 (13→15) taken 16 times.
24 if (!freopen("/dev/null", i ? "w" : "r", streams[i])) {
164 return ec_error("freopen", EC_IO_ERROR);
165 }
166 }
167
168
1/2
✗ Branch 0 (18→19) not taken.
✓ Branch 1 (18→22) taken 8 times.
8 if (!fd_is_valid(STDERR_FILENO)) {
169 // If FD 2 isn't valid (e.g. because it was closed), point it
170 // to /dev/null to ensure open(3) doesn't allocate it to other
171 // opened files
172 if (!freopen("/dev/null", "w", stderr)) {
173 return ec_error("freopen", EC_IO_ERROR);
174 }
175 }
176
177 return EC_OK;
178 }
179
180 // Open special Buffers for duplicated stdin and/or stdout FDs, as created
181 // by init_std_fds()
182 8 static Buffer *init_std_buffer(EditorState *e, int fds[2])
183 {
184 8 const char *name = NULL;
185 8 Buffer *buffer = NULL;
186
187
1/2
✓ Branch 0 (2→3) taken 8 times.
✗ Branch 1 (2→10) not taken.
8 if (fds[STDIN_FILENO] >= 3) {
188 8 buffer = buffer_new(&e->buffers, &e->options, encoding_from_type(UTF8));
189
1/2
✓ Branch 0 (6→7) taken 8 times.
✗ Branch 1 (6→8) not taken.
8 if (read_blocks(buffer, fds[STDIN_FILENO], false)) {
190 8 name = "(stdin)";
191 8 buffer->temporary = true;
192 } else {
193 error_msg(&e->err, "Unable to read redirected stdin");
194 buffer_remove_unlock_and_free(&e->buffers, buffer, &e->err, &e->locks_ctx);
195 buffer = NULL;
196 }
197 }
198
199
1/2
✓ Branch 0 (10→11) taken 8 times.
✗ Branch 1 (10→14) not taken.
8 if (fds[STDOUT_FILENO] >= 3) {
200
1/2
✗ Branch 0 (11→12) not taken.
✓ Branch 1 (11→13) taken 8 times.
8 if (!buffer) {
201 buffer = open_empty_buffer(&e->buffers, &e->options);
202 name = "(stdout)";
203 } else {
204 name = "(stdin|stdout)";
205 }
206 8 buffer->stdout_buffer = true;
207 8 buffer->temporary = true;
208 }
209
210 8 BUG_ON(!buffer != !name);
211
1/2
✓ Branch 0 (16→17) taken 8 times.
✗ Branch 1 (16→19) not taken.
8 if (name) {
212 8 buffer_set_display_filename(buffer, xstrdup(name));
213 }
214
215 8 return buffer;
216 }
217
218 // Write the contents of the special `stdout` Buffer (as created by
219 // init_std_buffer()) to `stdout` and free its remaining allocations
220 8 static int buffer_write_blocks_and_free(Buffer *buffer, int fd)
221 {
222 8 BUG_ON(!buffer->stdout_buffer);
223 8 const Block *blk;
224 8 int err = 0;
225
226
2/2
✓ Branch 0 (9→5) taken 8 times.
✓ Branch 1 (9→10) taken 8 times.
16 block_for_each(blk, &buffer->blocks) {
227
1/2
✗ Branch 0 (6→7) not taken.
✓ Branch 1 (6→8) taken 8 times.
8 if (xwrite_all(fd, blk->data, blk->size) < 0) {
228 err = errno;
229 break;
230 }
231 }
232
233 // Other allocations for `buffer` should have already been freed
234 // by buffer_unlock_and_free()
235 8 free_blocks(buffer);
236 8 free(buffer);
237 8 return err;
238 }
239
240 static void init_trace_logging(LogLevel level)
241 {
242 if (!TRACE_LOGGING_ENABLED || level < LOG_LEVEL_TRACE) {
243 return;
244 }
245
246 const char *flagstr = xgetenv("DTE_LOG_TRACE");
247 if (!flagstr) {
248 LOG_NOTICE("DTE_LOG_LEVEL=trace used with no effect; DTE_LOG_TRACE also needed");
249 return;
250 }
251
252 TraceLoggingFlags flags = trace_flags_from_str(flagstr);
253 if (!flags) {
254 LOG_WARNING("no known flags in DTE_LOG_TRACE='%s'", flagstr);
255 return;
256 }
257
258 LOG_INFO("DTE_LOG_TRACE=%s", flagstr);
259 set_trace_logging_flags(flags);
260 }
261
262 8 static ExitCode init_logging(void)
263 {
264 8 const char *filename = xgetenv("DTE_LOG");
265
1/2
✗ Branch 0 (3→4) not taken.
✓ Branch 1 (3→23) taken 8 times.
8 if (!filename) {
266 return EC_OK;
267 }
268
269 const char *req_level_str = getenv("DTE_LOG_LEVEL");
270 LogLevel req_level = log_level_from_str(req_level_str);
271 if (req_level == LOG_LEVEL_NONE) {
272 return EC_OK;
273 }
274 if (req_level == LOG_LEVEL_INVALID) {
275 return ec_usage_error("invalid $DTE_LOG_LEVEL value: '%s'", req_level_str);
276 }
277
278 const char *no_color = xgetenv("NO_COLOR"); // https://no-color.org/
279 LogLevel got_level = log_open(filename, req_level, !no_color);
280 if (got_level == LOG_LEVEL_NONE) {
281 const char *err = strerror(errno);
282 fprintf(stderr, "Failed to open $DTE_LOG (%s): %s\n", filename, err);
283 return EC_IO_ERROR;
284 }
285
286 const char *got_level_str = log_level_to_str(got_level);
287 if (got_level != req_level) {
288 const char *r = req_level_str;
289 const char *g = got_level_str;
290 LOG_WARNING("log level '%s' unavailable; falling back to '%s'", r, g);
291 }
292
293 LOG_INFO("logging to '%s' (level: %s)", filename, got_level_str);
294
295 if (no_color) {
296 LOG_INFO("log colors disabled ($NO_COLOR)");
297 }
298
299 init_trace_logging(got_level);
300 return EC_OK;
301 }
302
303 static void read_history_files(EditorState *e, bool headless)
304 {
305 const char *dir = e->user_config_dir;
306 size_t size_limit = 64u << 20; // 64 MiB
307 file_history_load(&e->file_history, &e->err, path_join(dir, "file-history"), size_limit);
308 history_load(&e->command_history, &e->err, path_join(dir, "command-history"), size_limit);
309 history_load(&e->search_history, &e->err, path_join(dir, "search-history"), size_limit);
310
311 // There's not much sense in saving history for headless sessions, but we
312 // do still load it (above), to make it available to e.g. `exec -i command`
313 if (!headless) {
314 e->flags |= EFLAG_ALL_HIST;
315 }
316
317 if (e->search_history.last) {
318 search_set_regexp(&e->search, e->search_history.last->text);
319 }
320 }
321
322 8 static void write_history_files(EditorState *e)
323 {
324 8 EditorFlags flags = e->flags;
325
1/2
✗ Branch 0 (2→3) not taken.
✓ Branch 1 (2→4) taken 8 times.
8 if (flags & EFLAG_CMD_HIST) {
326 history_save(&e->command_history, &e->err);
327 }
328
1/2
✗ Branch 0 (4→5) not taken.
✓ Branch 1 (4→6) taken 8 times.
8 if (flags & EFLAG_SEARCH_HIST) {
329 history_save(&e->search_history, &e->err);
330 }
331
1/2
✗ Branch 0 (6→7) not taken.
✓ Branch 1 (6→8) taken 8 times.
8 if (flags & EFLAG_FILE_HIST) {
332 file_history_save(&e->file_history, &e->err);
333 }
334 8 }
335
336 static void lookup_tags (
337 EditorState *e,
338 const char *tags[],
339 size_t nr_tags,
340 View *closeable_default_view
341 ) {
342 if (nr_tags == 0 || !load_tag_file(&e->tagfile, &e->err)) {
343 return;
344 }
345
346 MessageList *msgs = &e->messages[e->options.msg_tag];
347 clear_messages(msgs);
348
349 for (size_t i = 0; i < nr_tags; i++) {
350 StringView tagname = strview_from_cstring(tags[i]);
351 tag_lookup(&e->tagfile, msgs, &e->err, &tagname, NULL);
352 }
353
354 if (
355 activate_current_message(msgs, e->window)
356 && closeable_default_view
357 && e->window->views.count >= 2
358 ) {
359 // Close the default/empty buffer, if another buffer is opened
360 // for a tag (and no commands were executed via `-c` or `-C`)
361 remove_view(closeable_default_view);
362 }
363 }
364
365 8 static View *open_initial_buffers (
366 EditorState *e,
367 Buffer *std_buffer,
368 char *args[],
369 size_t nr_args
370 ) {
371 // Open files specified as command-line arguments
372 8 Window *window = e->window;
373
1/2
✗ Branch 0 (15→3) not taken.
✓ Branch 1 (15→16) taken 8 times.
8 for (size_t i = 0, line = 0, col = 0; i < nr_args; i++) {
374 const char *str = args[i];
375 if (line == 0 && *str == '+' && str_to_filepos(str + 1, &line, &col)) {
376 continue;
377 }
378 View *view = window_open_buffer(window, str, false, NULL);
379 if (line == 0) {
380 continue;
381 }
382 set_view(view);
383 move_to_filepos(view, line, col);
384 line = 0;
385 }
386
387
1/2
✓ Branch 0 (16→17) taken 8 times.
✗ Branch 1 (16→18) not taken.
8 if (std_buffer) {
388 // Open special buffer for redirected stdin/stdout
389 8 window_add_buffer(window, std_buffer);
390 }
391
392 // Open default buffer, if none were opened above
393
1/2
✗ Branch 0 (18→19) not taken.
✓ Branch 1 (18→20) taken 8 times.
8 View *dview = window->views.count ? NULL : window_open_empty_buffer(window);
394
395 8 set_view(window_get_first_view(window));
396 8 return dview;
397 }
398
399 static const char copyright[] =
400 "dte " VERSION "\n"
401 "(C) 2013-2024 Craig Barnes\n"
402 "(C) 2010-2015 Timo Hirvonen\n"
403 "This program is free software; you can redistribute and/or modify\n"
404 "it under the terms of the GNU General Public License version 2\n"
405 "<https://www.gnu.org/licenses/old-licenses/gpl-2.0.html>.\n"
406 "There is NO WARRANTY, to the extent permitted by law.\n";
407
408 static const char usage[] =
409 "Usage: %s [OPTIONS] [[+LINE] FILE]...\n\n"
410 "Options:\n"
411 " -c COMMAND Run COMMAND after editor starts\n"
412 " -t CTAG Jump to source location of CTAG\n"
413 " -r RCFILE Read user config from RCFILE instead of ~/.dte/rc\n"
414 " -s FILE Validate dte-syntax commands in FILE and exit\n"
415 " -b NAME Print built-in config matching NAME and exit\n"
416 " -B Print list of built-in config names and exit\n"
417 " -H Don't load or save history files\n"
418 " -R Don't read user config file\n"
419 " -K Start editor in \"showkey\" mode\n"
420 " -h Display help summary and exit\n"
421 " -V Display version number and exit\n"
422 "\n";
423
424 23 int main(int argc, char *argv[])
425 {
426 23 static const char optstring[] = "hBHKPRVZC:Q:S:b:c:t:r:s:";
427 23 const char *rc = NULL;
428 23 const char *commands[8];
429 23 const char *tags[8];
430 23 size_t nr_commands = 0;
431 23 size_t nr_tags = 0;
432 23 bool headless = false;
433 23 bool read_rc = true;
434 23 bool load_and_save_history = true;
435 23 bool explicit_term_query_level = false;
436 23 unsigned int terminal_query_level = 1;
437
438
2/2
✓ Branch 0 (27→3) taken 60 times.
✓ Branch 1 (27→28) taken 9 times.
69 for (int ch; (ch = getopt(argc, argv, optstring)) != -1; ) {
439
15/17
✓ Branch 0 (3→4) taken 14 times.
✓ Branch 1 (3→5) taken 5 times.
✓ Branch 2 (3→8) taken 9 times.
✓ Branch 3 (3→11) taken 2 times.
✓ Branch 4 (3→14) taken 3 times.
✓ Branch 5 (3→15) taken 7 times.
✓ Branch 6 (3→16) taken 2 times.
✓ Branch 7 (3→17) taken 1 times.
✓ Branch 8 (3→18) taken 1 times.
✗ Branch 9 (3→19) not taken.
✓ Branch 10 (3→20) taken 1 times.
✓ Branch 11 (3→21) taken 2 times.
✗ Branch 12 (3→22) not taken.
✓ Branch 13 (3→23) taken 1 times.
✓ Branch 14 (3→24) taken 1 times.
✓ Branch 15 (3→25) taken 9 times.
✓ Branch 16 (3→123) taken 2 times.
60 switch (ch) {
440 14 case 'C':
441 14 headless = true;
442 // Fallthrough
443 19 case 'c':
444
2/2
✓ Branch 0 (5→6) taken 1 times.
✓ Branch 1 (5→7) taken 18 times.
19 if (unlikely(nr_commands >= ARRAYLEN(commands))) {
445 1 return ec_usage_error("too many -c or -C options used");
446 }
447 18 commands[nr_commands++] = optarg;
448 18 break;
449 9 case 't':
450
2/2
✓ Branch 0 (8→9) taken 1 times.
✓ Branch 1 (8→10) taken 8 times.
9 if (unlikely(nr_tags >= ARRAYLEN(tags))) {
451 1 return ec_usage_error("too many -t options used");
452 }
453 8 tags[nr_tags++] = optarg;
454 8 break;
455 2 case 'Q':
456
2/2
✓ Branch 0 (12→13) taken 1 times.
✓ Branch 1 (12→25) taken 1 times.
2 if (!str_to_uint(optarg, &terminal_query_level)) {
457 1 return ec_usage_error("invalid argument for -Q: '%s'", optarg);
458 }
459 explicit_term_query_level = true;
460 break;
461 case 'H': load_and_save_history = false; break;
462 3 case 'r': rc = optarg; break;
463 7 case 'R': read_rc = false; break;
464 2 case 'b': return dump_builtin_config(optarg);
465 1 case 'B': return list_builtin_configs();
466 1 case 'h': return ec_printf_ok(usage, progname(argc, argv, "dte"));
467 case 'K': return showkey_loop(terminal_query_level);
468 1 case 'P': return print_256_color_palette();
469 2 case 's': return lint_syntax(optarg, false);
470 case 'S': return lint_syntax(optarg, true);
471 1 case 'V': return ec_write_stdout(copyright, sizeof(copyright));
472 1 case 'Z': return ec_printf_ok("features:%s\n", buildvar_string);
473 default: return EC_USAGE_ERROR;
474 }
475 }
476
477 // stdio(3) fds must be handled before calling init_logging(), otherwise
478 // an invocation like e.g. `DTE_LOG=/dev/pts/2 dte 0<&-` could cause the
479 // logging fd to be opened as STDIN_FILENO
480 9 int std_fds[2] = {-1, -1};
481
2/2
✓ Branch 0 (28→29) taken 8 times.
✓ Branch 1 (28→30) taken 1 times.
9 ExitCode r = headless ? init_std_fds_headless(std_fds) : init_std_fds(std_fds);
482
2/2
✓ Branch 0 (31→32) taken 8 times.
✓ Branch 1 (31→34) taken 1 times.
9 r = r ? r : init_logging();
483
1/2
✗ Branch 0 (33→34) not taken.
✓ Branch 1 (33→35) taken 8 times.
8 if (unlikely(r)) {
484 1 return r;
485 }
486
487 8 struct utsname u;
488
1/2
✓ Branch 0 (36→37) taken 8 times.
✗ Branch 1 (36→42) not taken.
8 if (likely(uname(&u) >= 0)) {
489 8 LOG_INFO("system: %s/%s %s", u.sysname, u.machine, u.release);
490
1/2
✗ Branch 0 (38→39) not taken.
✓ Branch 1 (38→44) taken 8 times.
8 if (
491 !headless
492 && !explicit_term_query_level
493 && str_has_suffix(u.release, "-WSL2")
494 ) {
495 // There appears to be an issue on WSL2 where the DA1 query
496 // response is interpreted as pasted text and then inserted
497 // into the buffer at startup. For now, we simply disable
498 // querying entirely on that platform, until the problem
499 // can be investigated.
500 LOG_NOTICE("WSL2 detected; disabling all terminal queries");
501 terminal_query_level = 0;
502 }
503 } else {
504 LOG_ERRNO("uname");
505 }
506
507 8 LOG_INFO("dte version: " VERSION);
508 8 LOG_INFO("build vars:%s", buildvar_string);
509
510
1/2
✓ Branch 0 (46→47) taken 8 times.
✗ Branch 1 (46→48) not taken.
8 if (headless) {
511 8 set_signal_dispositions_headless();
512 } else {
513 set_basic_signal_dispositions();
514 }
515
516 // Note that we don't unset EFLAG_HEADLESS in e->flags until later
517 // (regardless of whether -C was used), because the terminal isn't
518 // properly initialized yet and we don't want commands running via
519 // -c or -C -interacting with it
520 8 EditorState *e = init_editor_state(getenv("HOME"), getenv("DTE_HOME"));
521
522 8 Terminal *term = &e->terminal;
523
1/2
✗ Branch 0 (52→53) not taken.
✓ Branch 1 (52→56) taken 8 times.
8 if (!headless) {
524 term_init(term, getenv("TERM"), getenv("COLORTERM"));
525 }
526
527 8 e->err.print_to_stderr = true;
528 8 Buffer *std_buffer = init_std_buffer(e, std_fds);
529
2/4
✓ Branch 0 (57→58) taken 8 times.
✗ Branch 1 (57→59) not taken.
✗ Branch 2 (58→59) not taken.
✓ Branch 3 (58→60) taken 8 times.
8 bool have_stdout_buffer = std_buffer && std_buffer->stdout_buffer;
530
531 // Create this early (needed if "lock-files" is true)
532 8 const char *cfgdir = e->user_config_dir;
533 8 BUG_ON(!cfgdir);
534
3/4
✓ Branch 0 (63→64) taken 7 times.
✓ Branch 1 (63→68) taken 1 times.
✗ Branch 2 (64→65) not taken.
✓ Branch 3 (64→68) taken 7 times.
8 if (mkdir(cfgdir, 0755) != 0 && errno != EEXIST) {
535 error_msg(&e->err, "Error creating %s: %s", cfgdir, strerror(errno));
536 load_and_save_history = false;
537 e->options.lock_files = false;
538 }
539
540 8 exec_rc_files(e, rc, read_rc);
541
542 8 e->window = new_window(e);
543 8 e->root_frame = new_root_frame(e->window);
544
545
1/2
✗ Branch 0 (71→72) not taken.
✓ Branch 1 (71→73) taken 8 times.
8 if (load_and_save_history) {
546 read_history_files(e, headless);
547 }
548
549 8 e->status = EDITOR_RUNNING;
550 8 e->err.print_to_stderr = headless;
551 8 View *dview = open_initial_buffers(e, std_buffer, argv + optind, argc - optind);
552 8 e->err.print_to_stderr = true;
553
554
1/2
✗ Branch 0 (74→75) not taken.
✓ Branch 1 (74→78) taken 8 times.
8 if (!headless) {
555 // This is done before executing `-c` commands, so that the
556 // `exec` command can set $LINES and $COLUMNS appropriately
557 update_screen_size(term, e->root_frame);
558 }
559
560
2/2
✓ Branch 0 (79→76) taken 8 times.
✓ Branch 1 (79→80) taken 8 times.
16 for (size_t i = 0; i < nr_commands; i++) {
561 8 handle_normal_command(e, commands[i], false);
562 }
563
564 8 bool fast_exit = e->status != EDITOR_RUNNING;
565
1/2
✓ Branch 0 (80→81) taken 8 times.
✗ Branch 1 (80→82) not taken.
8 if (headless || fast_exit) {
566 // Headless mode implicitly exits after commands have finished
567 // running. We may also exit here (without drawing the UI,
568 // emitting terminal queries or entering main_loop()) if a `-c`
569 // command has already quit the editor. This prevents commands
570 // like e.g. `dte -HR -cquit` from emitting terminal queries
571 // and exiting before the responses have been read (which would
572 // typically cause the parent shell process to read them
573 // instead).
574 8 goto exit;
575 }
576
577 e->err.print_to_stderr = false;
578 lookup_tags(e, tags, nr_tags, nr_commands ? NULL : dview);
579
580 set_fatal_error_cleanup_handler(cleanup_handler, e);
581 set_fatal_signal_handlers();
582 set_sigwinch_handler();
583
584 bool init = term_mode_init();
585 if (unlikely(!init || !term_raw())) {
586 e->status = ec_error(init ? "tcsetattr" : "tcgetattr", EC_IO_ERROR);
587 fast_exit = true;
588 goto exit;
589 }
590
591 if (e->err.stderr_errors_printed) {
592 // Display "press any key to continue" prompt for stderr errors
593 any_key(term, e->options.esc_timeout);
594 clear_error(&e->err);
595 }
596
597 // Enable main_loop() iteration timing if $DTE_LOG_TIMING is set
598 // and logging is enabled. In theory, this could be controlled by
599 // `TraceLoggingFlags`, but trace logging is only enabled in debug
600 // builds, whereas latency timing is most useful in release builds.
601 bool timing = log_level_enabled(LOG_LEVEL_INFO) && xgetenv("DTE_LOG_TIMING");
602
603 e->flags &= ~EFLAG_HEADLESS; // See comment for init_editor_state() call above
604 ui_first_start(e, terminal_query_level);
605 main_loop(e, timing);
606 term_restore_title(term);
607
608 /*
609 * This is normally followed immediately by term_cooked() in other
610 * contexts, but in this case we want to switch back to cooked mode
611 * as late as possible. On underpowered machines, unlocking files and
612 * writing history may take some time. If cooked mode were switched
613 * to here it'd leave a window of time where we've switched back to
614 * the normal screen buffer and reset the termios ECHO flag while
615 * still being the foreground process, which would cause any input
616 * to be echoed to the terminal (before the shell takes over again
617 * and prints its prompt).
618 */
619 ui_end(e, true);
620
621 8 exit:
622 8 e->err.print_to_stderr = true;
623 8 frame_remove(e, e->root_frame); // Unlock files and add to file history
624 8 write_history_files(e);
625 8 int exit_code = MAX(e->status, EDITOR_EXIT_OK);
626
627
1/2
✗ Branch 0 (110→111) not taken.
✓ Branch 1 (110→112) taken 8 times.
8 if (!headless && !fast_exit) {
628 // This must be done before calling buffer_write_blocks_and_free(),
629 // since output modes need to be restored to get proper line ending
630 // translation and std_fds[STDOUT_FILENO] may be a pipe to the
631 // terminal
632 term_cooked();
633 }
634
635
1/2
✓ Branch 0 (112→113) taken 8 times.
✗ Branch 1 (112→119) not taken.
8 if (have_stdout_buffer) {
636 8 int err = buffer_write_blocks_and_free(std_buffer, std_fds[STDOUT_FILENO]);
637
1/2
✗ Branch 0 (114→115) not taken.
✓ Branch 1 (114→119) taken 8 times.
8 if (err != 0) {
638 error_msg(&e->err, "failed to write (stdout) buffer: %s", strerror(err));
639 if (exit_code == EDITOR_EXIT_OK) {
640 exit_code = EC_IO_ERROR;
641 }
642 }
643 }
644
645 8 if (DEBUG >= 1 || ASAN_ENABLED || xgetenv(ld_preload_env_var())) {
646 // Only free EditorState in debug builds or when a library/tool is
647 // checking for leaks; otherwise it's pointless to do so immediately
648 // before exiting
649 8 free_editor_state(e);
650 }
651
652 8 LOG_INFO("exiting with status %d", exit_code);
653 8 log_close();
654 8 return exit_code;
655 }
656