example.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include "linenoise.h"
  5. void completion(const char *buf, linenoiseCompletions *lc) {
  6. if (buf[0] == 'h') {
  7. linenoiseAddCompletion(lc,"hello");
  8. linenoiseAddCompletion(lc,"hello there");
  9. }
  10. }
  11. int main(int argc, char **argv) {
  12. char *line;
  13. char *prgname = argv[0];
  14. /* Parse options, with --multiline we enable multi line editing. */
  15. while(argc > 1) {
  16. argc--;
  17. argv++;
  18. if (!strcmp(*argv,"--multiline")) {
  19. linenoiseSetMultiLine(1);
  20. printf("Multi-line mode enabled.\n");
  21. } else if (!strcmp(*argv,"--keycodes")) {
  22. linenoisePrintKeyCodes();
  23. exit(0);
  24. } else {
  25. fprintf(stderr, "Usage: %s [--multiline] [--keycodes]\n", prgname);
  26. exit(1);
  27. }
  28. }
  29. /* Set the completion callback. This will be called every time the
  30. * user uses the <tab> key. */
  31. linenoiseSetCompletionCallback(completion);
  32. /* Load history from file. The history file is just a plain text file
  33. * where entries are separated by newlines. */
  34. linenoiseHistoryLoad("history.txt"); /* Load the history at startup */
  35. /* Now this is the main loop of the typical linenoise-based application.
  36. * The call to linenoise() will block as long as the user types something
  37. * and presses enter.
  38. *
  39. * The typed string is returned as a malloc() allocated string by
  40. * linenoise, so the user needs to free() it. */
  41. while((line = linenoise("hello> ")) != NULL) {
  42. /* Do something with the string. */
  43. if (line[0] != '\0' && line[0] != '/') {
  44. printf("echo: '%s'\n", line);
  45. linenoiseHistoryAdd(line); /* Add to the history. */
  46. linenoiseHistorySave("history.txt"); /* Save the history on disk. */
  47. } else if (!strncmp(line,"/historylen",11)) {
  48. /* The "/historylen" command will change the history len. */
  49. int len = atoi(line+11);
  50. linenoiseHistorySetMaxLen(len);
  51. } else if (line[0] == '/') {
  52. printf("Unreconized command: %s\n", line);
  53. }
  54. free(line);
  55. }
  56. return 0;
  57. }