/** * @file complete.c * @brief Finding what could complete the word under the cursor. * * Used by the built-in line editor for the Tab key. The kind of word * decides where candidates come from: * * - a word beginning with `$` completes to a variable name; * - the first word of a command, if it has no `/`, completes to an * alias, function, builtin or a program found in `PATH`; * - a word beginning with `//` completes to an MVS name, on z/OS (or * with a test catalog elsewhere. See sys_posix.c): * - `//'HLQ.PART` and `"//'HLQ.PART` complete one qualifier at a time * from the catalog (Catalog Search Interface), so `//'SYS1.MA` * offers `//'SYS1.MACLIB'` and `//'SYS1.MACROS.` (more below it); * - `//'DSN(MEM` completes a member of a PDS; * - `//DD:NA` completes an allocated DD name; * A bare `//NAME` is not an MVS name: it would mean guessing the * user's high-level qualifier, and zash does not guess. * - anything else completes to a file name. A directory candidate ends * in `/` so that the next Tab continues inside it. * * Candidates are whole replacements for the word, without shell quoting; * the editor adds backslashes when it inserts one. */ #include #include #include #include #include #include #include #include "exec.h" #include "interact.h" #include "sys.h" /** @brief A growing list of candidate strings. */ typedef struct candidates { char **list; int count; int cap; } candidates; /** * @brief Add a candidate made of two pieces. * @param c The list. * @param head First piece (for example a directory prefix). * @param tail Second piece. */ static void add(candidates *c, const char *head, const char *tail) { if (c->count == c->cap) { c->cap = c->cap ? c->cap * 2 : 32; c->list = xrealloc(c->list, (size_t)c->cap * sizeof *c->list); } size_t hl = strlen(head); size_t tl = strlen(tail); char *s = xmalloc(hl + tl + 2); memcpy(s, head, hl); memcpy(s + hl, tail, tl + 1); c->list[c->count++] = s; } /** @brief qsort() comparison of two strings. */ static int cmp_str(const void *a, const void *b) { return strcmp(*(char *const *)a, *(char *const *)b); } /** @brief Does `s` start with the first `n` bytes of `prefix`? */ static bool has_prefix(const char *s, const char *prefix, size_t n) { return !strncmp(s, prefix, n); } /** * @brief Add the entries of one directory that start with a prefix. * * @param c The list. * @param dir Directory to read ("" means the current directory). * @param shown The directory as the user typed it, prepended to each * candidate (it may be "~/..." while `dir` is expanded). * @param prefix What the file name must start with. * @param execs true to accept only executable regular files (command * completion from PATH) and to add bare names. */ static void add_files(candidates *c, const char *dir, const char *shown, const char *prefix, bool execs) { DIR *d = opendir(*dir ? dir : "."); if (!d) return; size_t plen = strlen(prefix); const struct dirent *e; while ((e = readdir(d)) != nullptr) { const char *name = e->d_name; if (!has_prefix(name, prefix, plen)) continue; if (name[0] == '.' && (plen == 0 || !strcmp(name, ".") || !strcmp(name, ".."))) continue; strbuf path; arena_marker mark = arena_mark(&scratch); sb_init(&path, &scratch); sb_puts(&path, dir); if (path.len && path.s[path.len - 1] != '/') sb_putc(&path, '/'); sb_puts(&path, name); struct stat st; bool ok = stat(sb_cstr(&path), &st) == 0; bool is_dir = ok && S_ISDIR(st.st_mode); if (execs) { if (ok && S_ISREG(st.st_mode) && access(sb_cstr(&path), X_OK) == 0) add(c, "", name); } else { add(c, shown, name); if (is_dir) { /* mark a directory with a trailing slash */ char *s = c->list[c->count - 1]; size_t n = strlen(s); s[n] = '/'; s[n + 1] = '\0'; } } arena_release(&scratch, mark); } closedir(d); } /** @brief Context for the name-collecting callbacks below. */ typedef struct name_ctx { candidates *c; const char *prefix; size_t plen; const char *head; /**< Prepended to each name ("$" for variables). */ } name_ctx; /** @brief Callback: add a name if it starts with the wanted prefix. */ static void add_name(const char *name, void *arg) { const name_ctx *x = arg; if (has_prefix(name, x->prefix, x->plen)) add(x->c, x->head, name); } /** * @brief Collect command names that start with a prefix. * @param c The list. * @param prefix What the name must start with. */ static void add_commands(candidates *c, const char *prefix) { name_ctx x = {c, prefix, strlen(prefix), ""}; for (size_t i = 0; i < nbuiltins; i++) add_name(builtins[i].name, &x); func_each(add_name, &x); alias_each(add_name, &x); const char *path = var_get("PATH"); for (const char *p = path ? path : "";;) { size_t len = strcspn(p, ":"); arena_marker mark = arena_mark(&scratch); add_files(c, len ? arena_strndup(&scratch, p, len) : ".", "", prefix, true); arena_release(&scratch, mark); if (!p[len]) break; p += len + 1; } } /* ---- MVS names ---------------------------------------------------------- */ /** @brief Most candidates one MVS listing may add (bounds memory). */ #define MVS_MAX_CANDIDATES 20000 /** * @brief Context for collecting MVS names (see mvs_add()). */ typedef struct mvs_ctx { candidates *c; const char *head; /**< prepended to each candidate: "//'" */ const char *prefix; /**< what the name must start with */ size_t plen; const char *tail; /**< appended to a final candidate: "'" or "" */ bool collapse; /**< cut catalog names after the next qualifier */ bool member; /**< names are members: "DSN(" is in head */ } mvs_ctx; /** * @brief Is this a high-level qualifier (A-Z, 0-9, @ # $ -)? * @param p Its first character (already folded to upper case). * @param len Its length. */ static bool hlq_ok(const char *p, size_t len) { if (len == 0 || len > 8) return false; for (size_t i = 0; i < len; i++) { char c = p[i]; if (!((c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '@' || c == '#' || c == '$' || c == '-')) return false; } return true; } /** * @brief Callback for the MVS listings: add one candidate. * * A catalog name longer than the next qualifier after the typed prefix * becomes that qualifier followed by `.`, so completion goes one level * at a time, as with directories. An alias (type X) is a level too. */ static void mvs_add(const char *name, char type, void *arg) { mvs_ctx *x = arg; if (x->c->count >= MVS_MAX_CANDIDATES) return; if (!has_prefix(name, x->prefix, x->plen)) return; char buf[MVS_DSN_MAX + 3]; size_t n = strlen(name); bool more = type == 'X'; if (x->collapse) { const char *dot = strchr(name + x->plen, '.'); if (dot) { n = (size_t)(dot - name); more = true; } } if (n > MVS_DSN_MAX) return; memcpy(buf, name, n); if (more) { buf[n++] = '.'; } else if (x->member) { buf[n++] = ')'; } buf[n] = '\0'; strbuf sb; arena_marker mark = arena_mark(&scratch); sb_init(&sb, &scratch); sb_puts(&sb, x->head); sb_puts(&sb, buf); if (!more) sb_puts(&sb, x->tail); add(x->c, "", sb_cstr(&sb)); arena_release(&scratch, mark); } /** * @brief Complete an MVS name: the typed word starts with `//`. * * Everything typed is folded to upper case before searching, as MVS * names are. The candidates replace the word whole. * * @param c Receives the candidates. * @param typed The word with its shell quoting removed. * @return false if there is no catalog to ask (not z/OS, no test * catalog), so that the word completes as a file name instead. */ static bool add_mvs(candidates *c, const char *typed) { if (!sys_has_catalog()) return false; char up[128]; size_t len = strlen(typed); if (len < 2) /* the caller checked for "//"; keep the contract visible */ return false; if (len >= sizeof up) return true; /* too long to be a name: no candidates */ for (size_t i = 0; i <= len; i++) up[i] = (char)toupper((unsigned char)typed[i]); const char *p = up + 2; mvs_ctx x = {.c = c, .tail = ""}; if (!strncmp(p, "DD:", 3)) { x.head = arena_strndup(&scratch, typed, 5); x.prefix = p + 3; x.plen = strlen(x.prefix); (void)sys_dd_names(mvs_add, &x); return true; } /* Only a quoted name is one: `//'SYS1.MA`. A bare `//NAME` would * need the user's high-level qualifier guessed, and zash does not. */ if (*p != '\'') return true; p++; if (*p == '\0') return true; /* nothing typed: every name in the catalog matches */ if (strlen(p) > MVS_DSN_MAX) return true; /* too long for a name: no candidates */ x.tail = "'"; const char *paren = strchr(p, '('); if (paren) { /* A member: list the PDS directory. */ const char *dsn = arena_strndup(&scratch, p, (size_t)(paren - p)); if (!mvs_dsn_ok(dsn)) return true; x.head = arena_strndup(&scratch, up, (size_t)(paren + 1 - up)); x.prefix = paren + 1; x.plen = strlen(x.prefix); x.member = true; (void)sys_pds_members(dsn, mvs_add, &x); return true; } /* * A data set name, one qualifier at a time. Two searches: names that * end in the qualifier being typed, and names below it. * * Nothing is searched until a high-level qualifier is complete: `SYS1.` * and no less. The filter we would build otherwise starts with a * generic qualifier (`SYS*`), and Catalog Management resolves aliases * with the first qualifier, which the manual warns can select several * catalogs at once -- not something a Tab key should ask of the * catalog address space. */ const char *dot = strchr(p, '.'); if (!dot || !hlq_ok(p, (size_t)(dot - p))) return true; x.head = "//'"; x.collapse = true; x.prefix = p; x.plen = strlen(p); char f1[MVS_DSN_MAX + 8]; char f2[MVS_DSN_MAX + 8]; snprintf(f1, sizeof f1, "%s*", p); snprintf(f2, sizeof f2, "%s*.**", p); /* A failed search just contributes nothing: Tab rings the bell. Once * the first has filled the list the second is pointless, and every * search asks the catalog for another page of names. */ (void)sys_catalog_list(f1, mvs_add, &x); if (x.c->count < MVS_MAX_CANDIDATES) (void)sys_catalog_list(f2, mvs_add, &x); return true; } /** * @brief Find the candidates for the word that ends at the cursor. * * The line is scanned from its start so that quotes and backslashes are * understood: the word begins after the last unquoted blank or operator. * * @param line The line being edited (need not be NUL-terminated). * @param cursor Offset of the cursor. * @param out Receives the sorted candidates, the offset where the * word starts and whether it starts inside quotes. Free * it with complete_free(). */ void complete_line(const char *line, size_t cursor, completion *out) { arena_marker mark = arena_mark(&scratch); strbuf typed; /* the word with its quoting removed */ sb_init(&typed, &scratch); size_t start = 0; char quote = 0; bool word_quoted = false; bool command = true; /* the typed is in command position */ bool next_command = true; /* ... and so would a typed starting now be */ for (size_t i = 0; i < cursor; i++) { char ch = line[i]; if (quote) { if (ch == quote) quote = 0; else sb_putc(&typed, ch); continue; } if (ch == '\\' && i + 1 < cursor) { sb_putc(&typed, line[++i]); continue; } if (ch == '\'' || ch == '"') { quote = ch; if (i == start) { word_quoted = true; start = i + 1; } continue; } if (strchr(" \t\n;&|()<>", ch)) { if (ch == ';' || ch == '&' || ch == '|' || ch == '(' || ch == '\n') next_command = true; else if (ch == '<' || ch == '>') next_command = false; else if (typed.len) next_command = false; /* a blank after a typed */ typed.len = 0; start = i + 1; word_quoted = false; command = next_command; continue; } if (!typed.len && !word_quoted) command = next_command; sb_putc(&typed, ch); } if (!quote) word_quoted = false; /* the quotes closed: treat as a plain typed */ const char *w = sb_cstr(&typed); candidates c = {0}; const char *slash = strrchr(w, '/'); /* Inside a quote only if it opened the word: "//'SYS1.MA, not //'SY. */ bool mvs = w[0] == '/' && w[1] == '/' && (!quote || word_quoted) && quote != '\'' && add_mvs(&c, w); if (mvs) { /* candidates added */ } else if (w[0] == '$' && !slash) { name_ctx x = {&c, w + 1, strlen(w + 1), "$"}; var_each(add_name, &x); } else if (command && !slash && w[0] != '~') { if (*w) add_commands(&c, w); } else { /* Split into the directory as word and the name prefix. */ size_t dlen = slash ? (size_t)(slash - w) + 1 : 0; const char *shown = arena_strndup(&scratch, w, dlen); const char *dir = shown; const char *home = var_get("HOME"); if (shown[0] == '~' && shown[1] == '/' && home) { strbuf sb; sb_init(&sb, &scratch); sb_puts(&sb, home); sb_puts(&sb, shown + 1); dir = sb_cstr(&sb); } add_files(&c, dir, shown, w + dlen, false); } if (c.count) { qsort(c.list, (size_t)c.count, sizeof *c.list, cmp_str); int k = 1; /* drop duplicates (a builtin that is also in PATH) */ for (int i = 1; i < c.count; i++) { if (strcmp(c.list[i], c.list[k - 1])) c.list[k++] = c.list[i]; else free(c.list[i]); } c.count = k; } *out = (completion){ c.list, c.count, start, word_quoted, word_quoted ? quote : 0, mvs}; arena_release(&scratch, mark); } /** * @brief Free the result of complete_line(). * @param c The completion. */ void complete_free(completion *c) { for (int i = 0; i < c->count; i++) free(c->list[i]); free(c->list); *c = (completion){0}; }