kilo.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. /*** includes ***/
  2. #include <ctype.h>
  3. #include <stdio.h>
  4. #include <sys/ioctl.h>
  5. #include <errno.h>
  6. #include <stdlib.h>
  7. #include <termios.h>
  8. #include <unistd.h>
  9. /*** defines ***/
  10. #define CTRL_KEY(k) ((k) & 0x1f)
  11. /*** data ***/
  12. struct editorConfig {
  13. int screenrows;
  14. int screencols;
  15. struct termios orig_termios;
  16. };
  17. struct editorConfig E;
  18. /*** terminal ***/
  19. void die(const char *s) {
  20. write(STDOUT_FILENO, "\x1b[2J", 4);
  21. write(STDOUT_FILENO, "\x1b[H", 3);
  22. perror(s);
  23. exit(1);
  24. }
  25. void disableRawMode() {
  26. if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &E.orig_termios) == -1)
  27. die("tcsetattr");
  28. }
  29. void enableRawMode() {
  30. if (tcgetattr(STDIN_FILENO, &E.orig_termios) == -1) die("tcgetattr");
  31. atexit(disableRawMode);
  32. struct termios raw = E.orig_termios;
  33. raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
  34. raw.c_oflag &= ~(OPOST);
  35. raw.c_cflag |= (CS8);
  36. raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
  37. raw.c_cc[VMIN] = 0;
  38. raw.c_cc[VTIME] = 1;
  39. if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw) == -1) die("tcsetattr");
  40. }
  41. char editorReadKey() {
  42. int nread;
  43. char c;
  44. while ((nread = read(STDIN_FILENO, &c, 1)) != 1) {
  45. if (nread == -1 && errno != EAGAIN) die("read");
  46. }
  47. return c;
  48. }
  49. int getWindowSize(int *rows, int *cols) {
  50. struct winsize ws;
  51. if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 || ws.ws_col == 0) {
  52. return -1;
  53. } else {
  54. *cols = ws.ws_col;
  55. *rows = ws.ws_row;
  56. return 0;
  57. }
  58. }
  59. /*** output ***/
  60. void editorDrawRows() {
  61. int y;
  62. for (y = 0; y < E.screenrows; y++) {
  63. write(STDOUT_FILENO, "~\r\n", 3);
  64. }
  65. }
  66. void editorRefreshScreen() {
  67. write(STDOUT_FILENO, "\x1b[2J", 4);
  68. write(STDOUT_FILENO, "\x1b[H", 3);
  69. editorDrawRows();
  70. write(STDOUT_FILENO, "\x1b[H", 3);
  71. }
  72. /*** input ***/
  73. void editorProcessKeypress() {
  74. char c = editorReadKey();
  75. switch (c) {
  76. case CTRL_KEY('q'):
  77. exit(0);
  78. break;
  79. }
  80. }
  81. /*** init ***/
  82. void initEditor() {
  83. if (getWindowSize(&E.screenrows, &E.screencols) == -1) die("getWindowSize");
  84. }
  85. int main() {
  86. enableRawMode();
  87. initEditor();
  88. while (1) {
  89. editorRefreshScreen();
  90. editorProcessKeypress();
  91. }
  92. return 0;
  93. }