2
0

example.c 2.4 KB

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