kilo.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  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, "~", 1);
  64. if (y < E.screenrows - 1) {
  65. write(STDOUT_FILENO, "\r\n", 2);
  66. }
  67. }
  68. }
  69. void editorRefreshScreen() {
  70. write(STDOUT_FILENO, "\x1b[2J", 4);
  71. write(STDOUT_FILENO, "\x1b[H", 3);
  72. editorDrawRows();
  73. write(STDOUT_FILENO, "\x1b[H", 3);
  74. }
  75. /*** input ***/
  76. void editorProcessKeypress() {
  77. char c = editorReadKey();
  78. switch (c) {
  79. case CTRL_KEY('q'):
  80. exit(0);
  81. break;
  82. }
  83. }
  84. /*** init ***/
  85. void initEditor() {
  86. if (getWindowSize(&E.screenrows, &E.screencols) == -1) die("getWindowSize");
  87. }
  88. int main() {
  89. enableRawMode();
  90. initEditor();
  91. while (1) {
  92. editorRefreshScreen();
  93. editorProcessKeypress();
  94. }
  95. return 0;
  96. }