shell_help.c 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /*
  2. * shell_help.c
  3. */
  4. #include "private.h"
  5. #include "clish/types.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. clish_help_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->name, 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. clish_help_t help;
  38. size_t max_width = 0;
  39. const clish_command_t *cmd;
  40. int i;
  41. help.name = 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.name) == 0)
  56. goto end;
  57. /* Print help messages */
  58. for (i = 0; i < lub_argv__get_count(help.name); i++) {
  59. fprintf(stderr, " %-*s %s\n", (int)max_width,
  60. lub_argv__get_arg(help.name, i),
  61. lub_argv__get_arg(help.help, i) ?
  62. lub_argv__get_arg(help.help, i) : "");
  63. }
  64. /* Print details */
  65. if ((lub_argv__get_count(help.name) == 1) &&
  66. (SHELL_STATE_HELPING == this->state)) {
  67. const char *detail = lub_argv__get_arg(help.detail, 0);
  68. if (detail)
  69. fprintf(stderr, "%s\n", detail);
  70. }
  71. /* update the state */
  72. if (this->state == SHELL_STATE_HELPING)
  73. this->state = SHELL_STATE_OK;
  74. else
  75. this->state = SHELL_STATE_HELPING;
  76. end:
  77. lub_argv_delete(help.name);
  78. lub_argv_delete(help.help);
  79. lub_argv_delete(help.detail);
  80. }
  81. /*--------------------------------------------------------- */