kilo.c 1.7 KB

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