kilo.c 1.4 KB

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