history.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. #include "stdafx.h"
  2. #include <stdlib.h>
  3. #include <string.h>
  4. extern char *get_curr_cmd(void);
  5. extern void update_curr_cmd(char *);
  6. //extern char *get_cmd_str(int);
  7. #define N 21
  8. static char *buf[N];
  9. static int i, j, k;
  10. void
  11. update_cmd_history(char *s)
  12. {
  13. // reset history pointer
  14. k = i;
  15. // blank string?
  16. if (*s == 0)
  17. return;
  18. // no duplicates
  19. if (i != j && strcmp(s, buf[(i + N - 1) % N]) == 0)
  20. return;
  21. buf[i] = strdup(s);
  22. i = (i + 1) % N;
  23. if (i == j) {
  24. free(buf[j]);
  25. buf[j] = 0;
  26. j = (j + 1) % N;
  27. }
  28. k = i;
  29. }
  30. // k != i indicates curr cmd is historical
  31. void
  32. do_up_arrow(void)
  33. {
  34. char *s;
  35. // save curr cmd if new input or change to historical input
  36. s = get_curr_cmd();
  37. if (*s) {
  38. if (k == i || strcmp(s, buf[k]) != 0) {
  39. update_cmd_history(s);
  40. k = (i + N - 1) % N;
  41. }
  42. }
  43. free(s);
  44. // retard history pointer
  45. if (k != j)
  46. k = (k + N - 1) % N;
  47. if (buf[k])
  48. update_curr_cmd(buf[k]);
  49. else
  50. update_curr_cmd("");
  51. }
  52. void
  53. do_down_arrow(void)
  54. {
  55. char *s;
  56. // save curr cmd if new input or change to historical input
  57. s = get_curr_cmd();
  58. if (*s) {
  59. if (k == i || strcmp(s, buf[k]) != 0) {
  60. update_cmd_history(s);
  61. k = (i + N - 1) % N;
  62. }
  63. }
  64. free(s);
  65. // advance history pointer
  66. if (k != i)
  67. k = (k + 1) % N;
  68. if (buf[k])
  69. update_curr_cmd(buf[k]);
  70. else
  71. update_curr_cmd("");
  72. }
  73. char *
  74. get_cmd_history(void)
  75. {
  76. int k, n;
  77. char *s, *t;
  78. // measure
  79. n = 0;
  80. k = j;
  81. while (k != i) {
  82. n += (int) strlen(buf[k]) + 2;
  83. k = (k + 1) % N;
  84. }
  85. s = (char *) malloc(n + 1);
  86. if (s == NULL)
  87. return NULL;
  88. // copy
  89. t = s;
  90. k = j;
  91. while (k != i) {
  92. strcpy(t, buf[k]);
  93. k = (k + 1) % N;
  94. t += strlen(t);
  95. //*t++ = '\r';
  96. //*t++ = ' ';
  97. }
  98. *t = 0;
  99. return s;
  100. }