shell_help.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /*
  2. * shell_help.c
  3. */
  4. #include "private.h"
  5. #include "clish/private.h"
  6. #include "lub/string.h"
  7. #include <stdio.h>
  8. #include <string.h>
  9. #include <ctype.h>
  10. /*--------------------------------------------------------- */
  11. /*
  12. * Provide a detailed list of the possible command completions
  13. */
  14. static int available_commands(clish_shell_t * this,
  15. help_argv_t *help, const char *line)
  16. {
  17. size_t max_width = 0;
  18. const clish_command_t *cmd;
  19. clish_shell_iterator_t iter;
  20. /* Search for COMMAND completions */
  21. clish_shell_iterator_init(&iter, CLISH_NSPACE_HELP);
  22. while ((cmd = clish_shell_find_next_completion(this, line, &iter))) {
  23. size_t width;
  24. const char *name = clish_command__get_suffix(cmd);
  25. width = strlen(name);
  26. if (width > max_width)
  27. max_width = width;
  28. lub_argv_add(help->matches, name);
  29. lub_argv_add(help->help, clish_command__get_text(cmd));
  30. lub_argv_add(help->detail, clish_command__get_detail(cmd));
  31. }
  32. return max_width;
  33. }
  34. /*--------------------------------------------------------- */
  35. void clish_shell_help(clish_shell_t *this, const char *line)
  36. {
  37. help_argv_t help;
  38. size_t max_width = 0;
  39. const clish_command_t *cmd;
  40. int i;
  41. help.matches = lub_argv_new(NULL, 0);
  42. help.help = lub_argv_new(NULL, 0);
  43. help.detail = lub_argv_new(NULL, 0);
  44. /* Get COMMAND completions */
  45. max_width = available_commands(this, &help, line);
  46. /* Resolve a command */
  47. cmd = clish_shell_resolve_command(this, line);
  48. /* Search for PARAM completion */
  49. if (cmd) {
  50. size_t width = 0;
  51. width = clish_command_help(cmd, &help, this->viewid, line);
  52. if (width > max_width)
  53. max_width = width;
  54. }
  55. if (lub_argv__get_count(help.matches) == 0)
  56. goto end;
  57. /* Print help messages */
  58. for (i = 0; i < lub_argv__get_count(help.matches); i++) {
  59. fprintf(stderr, " %-*s %s\n", (int)max_width,
  60. lub_argv__get_arg(help.matches, i),
  61. lub_argv__get_arg(help.help, i));
  62. }
  63. /* Print details */
  64. if ((lub_argv__get_count(help.matches) == 1) &&
  65. (SHELL_STATE_HELPING == this->state)) {
  66. const char *detail = lub_argv__get_arg(help.detail, 0);
  67. if (detail)
  68. fprintf(stderr, "%s\n", detail);
  69. }
  70. /* update the state */
  71. if (this->state == SHELL_STATE_HELPING)
  72. this->state = SHELL_STATE_OK;
  73. else
  74. this->state = SHELL_STATE_HELPING;
  75. end:
  76. lub_argv_delete(help.matches);
  77. lub_argv_delete(help.help);
  78. lub_argv_delete(help.detail);
  79. }
  80. /*--------------------------------------------------------- */