1 /* $OpenBSD: edit.c,v 1.19 2009/06/07 13:29:50 ray Exp $ */
4 * Written by Raymond Lai <ray@cyth.net>.
11 #include <sys/types.h>
27 cleanup(const char *filename)
31 err(2, "could not delete: %s", filename);
36 * Execute an editor on the specified pathname, which is interpreted
37 * from the shell. This means flags may be included.
39 * Returns -1 on error, or the exit value on success.
42 editit(const char *pathname)
44 sig_t sighup, sigint, sigquit, sigchld;
46 int saved_errno, st, ret = -1;
49 ed = getenv("VISUAL");
51 ed = getenv("EDITOR");
55 sighup = signal(SIGHUP, SIG_IGN);
56 sigint = signal(SIGINT, SIG_IGN);
57 sigquit = signal(SIGQUIT, SIG_IGN);
58 sigchld = signal(SIGCHLD, SIG_DFL);
59 if ((pid = fork()) == -1)
62 execlp(ed, ed, pathname, (char *)NULL);
65 while (waitpid(pid, &st, 0) == -1)
71 ret = WEXITSTATUS(st);
75 (void)signal(SIGHUP, sighup);
76 (void)signal(SIGINT, sigint);
77 (void)signal(SIGQUIT, sigquit);
78 (void)signal(SIGCHLD, sigchld);
84 * Parse edit command. Returns 0 on success, -1 on error.
87 eparse(const char *cmd, const char *left, const char *right)
93 char buf[BUFSIZ], *text;
95 /* Skip whitespace. */
102 /* Edit empty file. */
112 /* Neither column is blank, so print both. */
113 if (asprintf(&text, "%s\n%s\n", left, right) == -1)
114 err(2, "could not allocate memory");
119 /* Skip if there is no left column. */
123 if (asprintf(&text, "%s\n", left) == -1)
124 err(2, "could not allocate memory");
130 /* Skip if there is no right column. */
134 if (asprintf(&text, "%s\n", right) == -1)
135 err(2, "could not allocate memory");
143 /* Create temp file. */
144 if (asprintf(&filename, "%s/sdiff.XXXXXXXXXX", tmpdir) == -1)
146 if ((fd = mkstemp(filename)) == -1)
153 if ((nwritten = write(fd, text, len)) == -1 ||
154 (size_t)nwritten != len) {
155 warn("error writing to temp file");
161 /* text is no longer used. */
164 /* Edit temp file. */
165 if (editit(filename) == -1) {
166 warn("error editing %s", filename);
170 /* Open temporary file. */
171 if (!(file = fopen(filename, "r"))) {
172 warn("could not open edited file: %s", filename);
176 /* Copy temporary file contents to output file. */
177 for (nread = sizeof(buf); nread == sizeof(buf);) {
180 nread = fread(buf, sizeof(*buf), sizeof(buf), file);
181 /* Test for error or end of file. */
182 if (nread != sizeof(buf) &&
183 (ferror(file) || !feof(file))) {
184 warnx("error reading edited file: %s", filename);
189 * If we have nothing to read, break out of loop
190 * instead of writing nothing.
195 /* Write data we just read. */
196 nwritten = fwrite(buf, sizeof(*buf), nread, outfp);
197 if (nwritten != nread) {
198 warnx("error writing to output file");
203 /* We've reached the end of the temporary file, so remove it. */
204 if (unlink(filename))
205 warn("could not delete: %s", filename);