kilo.c 1.9 KB

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