kilo.c 1.6 KB

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