1 /* $NetBSD: edit.c,v 1.1 2007/02/18 22:13:42 rmind Exp $ */
2 /* $OpenBSD: edit.c,v 1.14 2006/05/25 03:20:32 ray Exp $ */
5 * Written by Raymond Lai <ray@cyth.net>.
22 static void edit(const char *);
25 * Takes the name of a file and opens it with an editor.
28 edit(const char *filename
)
34 editor
= getenv("VISUAL");
36 editor
= getenv("EDITOR");
40 /* Start editor on temporary file. */
41 switch (pid
= fork()) {
44 execlp(editor
, editor
, filename
, (void *)NULL
);
45 warn("could not execute editor: %s", editor
);
48 warn("could not fork");
53 /* Wait for editor to exit. */
54 if (waitpid(pid
, &status
, 0) == -1) {
59 /* Check that editor terminated normally. */
60 if (!WIFEXITED(status
)) {
61 warn("%s terminated abnormally", editor
);
67 * Parse edit command. Returns 0 on success, -1 on error.
70 eparse(const char *cmd
, const char *left
, const char *right
)
73 size_t nread
, nwritten
;
76 char buf
[BUFSIZ
], *text
;
78 /* Skip whitespace. */
79 while (isspace((int)(*cmd
)))
85 /* Edit empty file. */
95 /* Neither column is blank, so print both. */
96 if (asprintf(&text
, "%s\n%s\n", left
, right
) == -1)
97 err(2, "could not allocate memory");
102 /* Skip if there is no left column. */
106 if (asprintf(&text
, "%s\n", left
) == -1)
107 err(2, "could not allocate memory");
113 /* Skip if there is no right column. */
117 if (asprintf(&text
, "%s\n", right
) == -1)
118 err(2, "could not allocate memory");
126 /* Create temp file. */
127 if (asprintf(&filename
, "%s/sdiff.XXXXXXXXXX", tmpdir
) == -1)
129 if ((fd
= mkstemp(filename
)) == -1)
135 if ((size_t)write(fd
, text
, len
) != len
) {
136 warn("error writing to temp file");
142 /* text is no longer used. */
145 /* Edit temp file. */
148 /* Open temporary file. */
149 if (!(file
= fopen(filename
, "r"))) {
150 warn("could not open edited file: %s", filename
);
154 /* Copy temporary file contents to output file. */
155 for (nread
= sizeof(buf
); nread
== sizeof(buf
);) {
156 nread
= fread(buf
, sizeof(*buf
), sizeof(buf
), file
);
157 /* Test for error or end of file. */
158 if (nread
!= sizeof(buf
) &&
159 (ferror(file
) || !feof(file
))) {
160 warnx("error reading edited file: %s", filename
);
165 * If we have nothing to read, break out of loop
166 * instead of writing nothing.
171 /* Write data we just read. */
172 nwritten
= fwrite(buf
, sizeof(*buf
), nread
, outfile
);
173 if (nwritten
!= nread
) {
174 warnx("error writing to output file");
179 /* We've reached the end of the temporary file, so remove it. */
180 if (unlink(filename
))
181 warn("could not delete: %s", filename
);