filecomplete.c revision 1.31
1/* $NetBSD: filecomplete.c,v 1.31 2011/09/16 16:13:16 plunky Exp $ */ 2 3/*- 4 * Copyright (c) 1997 The NetBSD Foundation, Inc. 5 * All rights reserved. 6 * 7 * This code is derived from software contributed to The NetBSD Foundation 8 * by Jaromir Dolecek. 9 * 10 * Redistribution and use in source and binary forms, with or without 11 * modification, are permitted provided that the following conditions 12 * are met: 13 * 1. Redistributions of source code must retain the above copyright 14 * notice, this list of conditions and the following disclaimer. 15 * 2. Redistributions in binary form must reproduce the above copyright 16 * notice, this list of conditions and the following disclaimer in the 17 * documentation and/or other materials provided with the distribution. 18 * 19 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS 20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 21 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 22 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS 23 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 29 * POSSIBILITY OF SUCH DAMAGE. 30 */ 31 32#include "config.h" 33#if !defined(lint) && !defined(SCCSID) 34__RCSID("$NetBSD: filecomplete.c,v 1.31 2011/09/16 16:13:16 plunky Exp $"); 35#endif /* not lint && not SCCSID */ 36 37#include <sys/types.h> 38#include <sys/stat.h> 39#include <stdio.h> 40#include <dirent.h> 41#include <string.h> 42#include <pwd.h> 43#include <ctype.h> 44#include <stdlib.h> 45#include <unistd.h> 46#include <limits.h> 47#include <errno.h> 48#include <fcntl.h> 49 50#include "el.h" 51#include "fcns.h" /* for EL_NUM_FCNS */ 52#include "histedit.h" 53#include "filecomplete.h" 54 55static const Char break_chars[] = { ' ', '\t', '\n', '"', '\\', '\'', '`', '@', 56 '$', '>', '<', '=', ';', '|', '&', '{', '(', '\0' }; 57 58 59/********************************/ 60/* completion functions */ 61 62/* 63 * does tilde expansion of strings of type ``~user/foo'' 64 * if ``user'' isn't valid user name or ``txt'' doesn't start 65 * w/ '~', returns pointer to strdup()ed copy of ``txt'' 66 * 67 * it's callers's responsibility to free() returned string 68 */ 69char * 70fn_tilde_expand(const char *txt) 71{ 72#if defined(HAVE_GETPW_R_POSIX) || defined(HAVE_GETPW_R_DRAFT) 73 struct passwd pwres; 74 char pwbuf[1024]; 75#endif 76 struct passwd *pass; 77 char *temp; 78 size_t len = 0; 79 80 if (txt[0] != '~') 81 return strdup(txt); 82 83 temp = strchr(txt + 1, '/'); 84 if (temp == NULL) { 85 temp = strdup(txt + 1); 86 if (temp == NULL) 87 return NULL; 88 } else { 89 /* text until string after slash */ 90 len = (size_t)(temp - txt + 1); 91 temp = el_malloc(len * sizeof(*temp)); 92 if (temp == NULL) 93 return NULL; 94 (void)strncpy(temp, txt + 1, len - 2); 95 temp[len - 2] = '\0'; 96 } 97 if (temp[0] == 0) { 98#ifdef HAVE_GETPW_R_POSIX 99 if (getpwuid_r(getuid(), &pwres, pwbuf, sizeof(pwbuf), 100 &pass) != 0) 101 pass = NULL; 102#elif HAVE_GETPW_R_DRAFT 103 pass = getpwuid_r(getuid(), &pwres, pwbuf, sizeof(pwbuf)); 104#else 105 pass = getpwuid(getuid()); 106#endif 107 } else { 108#ifdef HAVE_GETPW_R_POSIX 109 if (getpwnam_r(temp, &pwres, pwbuf, sizeof(pwbuf), &pass) != 0) 110 pass = NULL; 111#elif HAVE_GETPW_R_DRAFT 112 pass = getpwnam_r(temp, &pwres, pwbuf, sizeof(pwbuf)); 113#else 114 pass = getpwnam(temp); 115#endif 116 } 117 el_free(temp); /* value no more needed */ 118 if (pass == NULL) 119 return strdup(txt); 120 121 /* update pointer txt to point at string immedially following */ 122 /* first slash */ 123 txt += len; 124 125 len = strlen(pass->pw_dir) + 1 + strlen(txt) + 1; 126 temp = el_malloc(len * sizeof(*temp)); 127 if (temp == NULL) 128 return NULL; 129 (void)snprintf(temp, len, "%s/%s", pass->pw_dir, txt); 130 131 return temp; 132} 133 134 135/* 136 * return first found file name starting by the ``text'' or NULL if no 137 * such file can be found 138 * value of ``state'' is ignored 139 * 140 * it's caller's responsibility to free returned string 141 */ 142char * 143fn_filename_completion_function(const char *text, int state) 144{ 145 static DIR *dir = NULL; 146 static char *filename = NULL, *dirname = NULL, *dirpath = NULL; 147 static size_t filename_len = 0; 148 struct dirent *entry; 149 char *temp; 150 size_t len; 151 152 if (state == 0 || dir == NULL) { 153 temp = strrchr(text, '/'); 154 if (temp) { 155 char *nptr; 156 temp++; 157 nptr = el_realloc(filename, (strlen(temp) + 1) * 158 sizeof(*nptr)); 159 if (nptr == NULL) { 160 el_free(filename); 161 filename = NULL; 162 return NULL; 163 } 164 filename = nptr; 165 (void)strcpy(filename, temp); 166 len = (size_t)(temp - text); /* including last slash */ 167 168 nptr = el_realloc(dirname, (len + 1) * 169 sizeof(*nptr)); 170 if (nptr == NULL) { 171 el_free(dirname); 172 dirname = NULL; 173 return NULL; 174 } 175 dirname = nptr; 176 (void)strncpy(dirname, text, len); 177 dirname[len] = '\0'; 178 } else { 179 el_free(filename); 180 if (*text == 0) 181 filename = NULL; 182 else { 183 filename = strdup(text); 184 if (filename == NULL) 185 return NULL; 186 } 187 el_free(dirname); 188 dirname = NULL; 189 } 190 191 if (dir != NULL) { 192 (void)closedir(dir); 193 dir = NULL; 194 } 195 196 /* support for ``~user'' syntax */ 197 198 el_free(dirpath); 199 dirpath = NULL; 200 if (dirname == NULL) { 201 if ((dirname = strdup("")) == NULL) 202 return NULL; 203 dirpath = strdup("./"); 204 } else if (*dirname == '~') 205 dirpath = fn_tilde_expand(dirname); 206 else 207 dirpath = strdup(dirname); 208 209 if (dirpath == NULL) 210 return NULL; 211 212 dir = opendir(dirpath); 213 if (!dir) 214 return NULL; /* cannot open the directory */ 215 216 /* will be used in cycle */ 217 filename_len = filename ? strlen(filename) : 0; 218 } 219 220 /* find the match */ 221 while ((entry = readdir(dir)) != NULL) { 222 /* skip . and .. */ 223 if (entry->d_name[0] == '.' && (!entry->d_name[1] 224 || (entry->d_name[1] == '.' && !entry->d_name[2]))) 225 continue; 226 if (filename_len == 0) 227 break; 228 /* otherwise, get first entry where first */ 229 /* filename_len characters are equal */ 230 if (entry->d_name[0] == filename[0] 231#if HAVE_STRUCT_DIRENT_D_NAMLEN 232 && entry->d_namlen >= filename_len 233#else 234 && strlen(entry->d_name) >= filename_len 235#endif 236 && strncmp(entry->d_name, filename, 237 filename_len) == 0) 238 break; 239 } 240 241 if (entry) { /* match found */ 242 243#if HAVE_STRUCT_DIRENT_D_NAMLEN 244 len = entry->d_namlen; 245#else 246 len = strlen(entry->d_name); 247#endif 248 249 len = strlen(dirname) + len + 1; 250 temp = el_malloc(len * sizeof(*temp)); 251 if (temp == NULL) 252 return NULL; 253 (void)snprintf(temp, len, "%s%s", dirname, entry->d_name); 254 } else { 255 (void)closedir(dir); 256 dir = NULL; 257 temp = NULL; 258 } 259 260 return temp; 261} 262 263 264static const char * 265append_char_function(const char *name) 266{ 267 struct stat stbuf; 268 char *expname = *name == '~' ? fn_tilde_expand(name) : NULL; 269 const char *rs = " "; 270 271 if (stat(expname ? expname : name, &stbuf) == -1) 272 goto out; 273 if (S_ISDIR(stbuf.st_mode)) 274 rs = "/"; 275out: 276 if (expname) 277 el_free(expname); 278 return rs; 279} 280/* 281 * returns list of completions for text given 282 * non-static for readline. 283 */ 284char ** completion_matches(const char *, char *(*)(const char *, int)); 285char ** 286completion_matches(const char *text, char *(*genfunc)(const char *, int)) 287{ 288 char **match_list = NULL, *retstr, *prevstr; 289 size_t match_list_len, max_equal, which, i; 290 size_t matches; 291 292 matches = 0; 293 match_list_len = 1; 294 while ((retstr = (*genfunc) (text, (int)matches)) != NULL) { 295 /* allow for list terminator here */ 296 if (matches + 3 >= match_list_len) { 297 char **nmatch_list; 298 while (matches + 3 >= match_list_len) 299 match_list_len <<= 1; 300 nmatch_list = el_realloc(match_list, 301 match_list_len * sizeof(*nmatch_list)); 302 if (nmatch_list == NULL) { 303 el_free(match_list); 304 return NULL; 305 } 306 match_list = nmatch_list; 307 308 } 309 match_list[++matches] = retstr; 310 } 311 312 if (!match_list) 313 return NULL; /* nothing found */ 314 315 /* find least denominator and insert it to match_list[0] */ 316 which = 2; 317 prevstr = match_list[1]; 318 max_equal = strlen(prevstr); 319 for (; which <= matches; which++) { 320 for (i = 0; i < max_equal && 321 prevstr[i] == match_list[which][i]; i++) 322 continue; 323 max_equal = i; 324 } 325 326 retstr = el_malloc((max_equal + 1) * sizeof(*retstr)); 327 if (retstr == NULL) { 328 el_free(match_list); 329 return NULL; 330 } 331 (void)strncpy(retstr, match_list[1], max_equal); 332 retstr[max_equal] = '\0'; 333 match_list[0] = retstr; 334 335 /* add NULL as last pointer to the array */ 336 match_list[matches + 1] = NULL; 337 338 return match_list; 339} 340 341/* 342 * Sort function for qsort(). Just wrapper around strcasecmp(). 343 */ 344static int 345_fn_qsort_string_compare(const void *i1, const void *i2) 346{ 347 const char *s1 = ((const char * const *)i1)[0]; 348 const char *s2 = ((const char * const *)i2)[0]; 349 350 return strcasecmp(s1, s2); 351} 352 353/* 354 * Display list of strings in columnar format on readline's output stream. 355 * 'matches' is list of strings, 'num' is number of strings in 'matches', 356 * 'width' is maximum length of string in 'matches'. 357 * 358 * matches[0] is not one of the match strings, but it is counted in 359 * num, so the strings are matches[1] *through* matches[num-1]. 360 */ 361void 362fn_display_match_list (EditLine *el, char **matches, size_t num, size_t width) 363{ 364 size_t line, lines, col, cols, thisguy; 365 int screenwidth = el->el_terminal.t_size.h; 366 367 /* Ignore matches[0]. Avoid 1-based array logic below. */ 368 matches++; 369 num--; 370 371 /* 372 * Find out how many entries can be put on one line; count 373 * with one space between strings the same way it's printed. 374 */ 375 cols = (size_t)screenwidth / (width + 1); 376 if (cols == 0) 377 cols = 1; 378 379 /* how many lines of output, rounded up */ 380 lines = (num + cols - 1) / cols; 381 382 /* Sort the items. */ 383 qsort(matches, num, sizeof(char *), _fn_qsort_string_compare); 384 385 /* 386 * On the ith line print elements i, i+lines, i+lines*2, etc. 387 */ 388 for (line = 0; line < lines; line++) { 389 for (col = 0; col < cols; col++) { 390 thisguy = line + col * lines; 391 if (thisguy >= num) 392 break; 393 (void)fprintf(el->el_outfile, "%s%-*s", 394 col == 0 ? "" : " ", (int)width, matches[thisguy]); 395 } 396 (void)fprintf(el->el_outfile, "\n"); 397 } 398} 399 400/* 401 * Complete the word at or before point, 402 * 'what_to_do' says what to do with the completion. 403 * \t means do standard completion. 404 * `?' means list the possible completions. 405 * `*' means insert all of the possible completions. 406 * `!' means to do standard completion, and list all possible completions if 407 * there is more than one. 408 * 409 * Note: '*' support is not implemented 410 * '!' could never be invoked 411 */ 412int 413fn_complete(EditLine *el, 414 char *(*complet_func)(const char *, int), 415 char **(*attempted_completion_function)(const char *, int, int), 416 const Char *word_break, const Char *special_prefixes, 417 const char *(*app_func)(const char *), size_t query_items, 418 int *completion_type, int *over, int *point, int *end) 419{ 420 const TYPE(LineInfo) *li; 421 Char *temp; 422 char **matches; 423 const Char *ctemp; 424 size_t len; 425 int what_to_do = '\t'; 426 int retval = CC_NORM; 427 428 if (el->el_state.lastcmd == el->el_state.thiscmd) 429 what_to_do = '?'; 430 431 /* readline's rl_complete() has to be told what we did... */ 432 if (completion_type != NULL) 433 *completion_type = what_to_do; 434 435 if (!complet_func) 436 complet_func = fn_filename_completion_function; 437 if (!app_func) 438 app_func = append_char_function; 439 440 /* We now look backwards for the start of a filename/variable word */ 441 li = FUN(el,line)(el); 442 ctemp = li->cursor; 443 while (ctemp > li->buffer 444 && !Strchr(word_break, ctemp[-1]) 445 && (!special_prefixes || !Strchr(special_prefixes, ctemp[-1]) ) ) 446 ctemp--; 447 448 len = (size_t)(li->cursor - ctemp); 449 temp = el_malloc((len + 1) * sizeof(*temp)); 450 (void)Strncpy(temp, ctemp, len); 451 temp[len] = '\0'; 452 453 /* these can be used by function called in completion_matches() */ 454 /* or (*attempted_completion_function)() */ 455 if (point != 0) 456 *point = (int)(li->cursor - li->buffer); 457 if (end != NULL) 458 *end = (int)(li->lastchar - li->buffer); 459 460 if (attempted_completion_function) { 461 int cur_off = (int)(li->cursor - li->buffer); 462 matches = (*attempted_completion_function)( 463 ct_encode_string(temp, &el->el_scratch), 464 cur_off - (int)len, cur_off); 465 } else 466 matches = 0; 467 if (!attempted_completion_function || 468 (over != NULL && !*over && !matches)) 469 matches = completion_matches( 470 ct_encode_string(temp, &el->el_scratch), complet_func); 471 472 if (over != NULL) 473 *over = 0; 474 475 if (matches) { 476 int i; 477 size_t matches_num, maxlen, match_len, match_display=1; 478 479 retval = CC_REFRESH; 480 /* 481 * Only replace the completed string with common part of 482 * possible matches if there is possible completion. 483 */ 484 if (matches[0][0] != '\0') { 485 el_deletestr(el, (int) len); 486 FUN(el,insertstr)(el, 487 ct_decode_string(matches[0], &el->el_scratch)); 488 } 489 490 if (what_to_do == '?') 491 goto display_matches; 492 493 if (matches[2] == NULL && strcmp(matches[0], matches[1]) == 0) { 494 /* 495 * We found exact match. Add a space after 496 * it, unless we do filename completion and the 497 * object is a directory. 498 */ 499 FUN(el,insertstr)(el, 500 ct_decode_string((*app_func)(matches[0]), 501 &el->el_scratch)); 502 } else if (what_to_do == '!') { 503 display_matches: 504 /* 505 * More than one match and requested to list possible 506 * matches. 507 */ 508 509 for(i = 1, maxlen = 0; matches[i]; i++) { 510 match_len = strlen(matches[i]); 511 if (match_len > maxlen) 512 maxlen = match_len; 513 } 514 /* matches[1] through matches[i-1] are available */ 515 matches_num = (size_t)(i - 1); 516 517 /* newline to get on next line from command line */ 518 (void)fprintf(el->el_outfile, "\n"); 519 520 /* 521 * If there are too many items, ask user for display 522 * confirmation. 523 */ 524 if (matches_num > query_items) { 525 (void)fprintf(el->el_outfile, 526 "Display all %zu possibilities? (y or n) ", 527 matches_num); 528 (void)fflush(el->el_outfile); 529 if (getc(stdin) != 'y') 530 match_display = 0; 531 (void)fprintf(el->el_outfile, "\n"); 532 } 533 534 if (match_display) { 535 /* 536 * Interface of this function requires the 537 * strings be matches[1..num-1] for compat. 538 * We have matches_num strings not counting 539 * the prefix in matches[0], so we need to 540 * add 1 to matches_num for the call. 541 */ 542 fn_display_match_list(el, matches, 543 matches_num+1, maxlen); 544 } 545 retval = CC_REDISPLAY; 546 } else if (matches[0][0]) { 547 /* 548 * There was some common match, but the name was 549 * not complete enough. Next tab will print possible 550 * completions. 551 */ 552 el_beep(el); 553 } else { 554 /* lcd is not a valid object - further specification */ 555 /* is needed */ 556 el_beep(el); 557 retval = CC_NORM; 558 } 559 560 /* free elements of array and the array itself */ 561 for (i = 0; matches[i]; i++) 562 el_free(matches[i]); 563 el_free(matches); 564 matches = NULL; 565 } 566 el_free(temp); 567 return retval; 568} 569 570/* 571 * el-compatible wrapper around rl_complete; needed for key binding 572 */ 573/* ARGSUSED */ 574unsigned char 575_el_fn_complete(EditLine *el, int ch __attribute__((__unused__))) 576{ 577 return (unsigned char)fn_complete(el, NULL, NULL, 578 break_chars, NULL, NULL, (size_t)100, 579 NULL, NULL, NULL, NULL); 580} 581