less.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. /*
  2. * Copyright (c) 2021, Peter Elliott <pelliott@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Format.h>
  7. #include <AK/LexicalPath.h>
  8. #include <AK/String.h>
  9. #include <AK/StringBuilder.h>
  10. #include <AK/Utf8View.h>
  11. #include <AK/Vector.h>
  12. #include <LibCore/ArgsParser.h>
  13. #include <ctype.h>
  14. #include <fcntl.h>
  15. #include <stdio.h>
  16. #include <sys/ioctl.h>
  17. #include <termios.h>
  18. #include <unistd.h>
  19. static struct termios g_save;
  20. static struct winsize g_wsize;
  21. static void setup_tty(bool switch_buffer)
  22. {
  23. // Save previous tty settings.
  24. if (tcgetattr(STDOUT_FILENO, &g_save) == -1) {
  25. perror("tcgetattr(3)");
  26. }
  27. // Get the window size.
  28. if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &g_wsize) == -1) {
  29. perror("ioctl(2)");
  30. }
  31. struct termios raw = g_save;
  32. raw.c_lflag &= ~(ECHO | ICANON);
  33. // Disable echo and line buffering
  34. if (tcsetattr(STDOUT_FILENO, TCSAFLUSH, &raw) == -1) {
  35. perror("tcsetattr(3)");
  36. }
  37. if (switch_buffer) {
  38. // Save cursor and switch to alternate buffer.
  39. out("\e[s\e[?1047h");
  40. }
  41. }
  42. static void teardown_tty(bool switch_buffer)
  43. {
  44. if (tcsetattr(STDOUT_FILENO, TCSAFLUSH, &g_save) == -1) {
  45. perror("tcsetattr(3)");
  46. }
  47. if (switch_buffer) {
  48. out("\e[?1047l\e[u");
  49. }
  50. }
  51. static Vector<String> wrap_line(Utf8View const& string, size_t width)
  52. {
  53. Vector<String> lines;
  54. StringBuilder builder;
  55. size_t offset = 0;
  56. bool in_ansi = false;
  57. for (auto codepoint : string) {
  58. if (offset >= width) {
  59. builder.append('\n');
  60. lines.append(builder.build());
  61. builder.clear();
  62. offset = 0;
  63. }
  64. builder.append(codepoint);
  65. if (codepoint == '\e')
  66. in_ansi = true;
  67. if (!in_ansi)
  68. // FIXME: calcuate the printed width of the character.
  69. offset++;
  70. if (isalpha(codepoint))
  71. in_ansi = false;
  72. }
  73. if (builder.length() > 0)
  74. lines.append(builder.build());
  75. return lines;
  76. }
  77. class Pager {
  78. public:
  79. Pager(FILE* file, FILE* tty, size_t width, size_t height)
  80. : m_file(file)
  81. , m_tty(tty)
  82. , m_width(width)
  83. , m_height(height)
  84. {
  85. }
  86. void up()
  87. {
  88. up_n(1);
  89. }
  90. void down()
  91. {
  92. down_n(1);
  93. }
  94. void up_page()
  95. {
  96. up_n(m_height - 1);
  97. }
  98. void down_page()
  99. {
  100. down_n(m_height - 1);
  101. }
  102. void up_n(size_t n)
  103. {
  104. if (m_line == 0)
  105. return;
  106. m_line = (m_line > n) ? m_line - n : 0;
  107. // Clear screen and reset cursor position.
  108. out("\e[2J\e[0G\e[0d");
  109. write_range(m_line, m_height - 1);
  110. status_line();
  111. fflush(m_tty);
  112. }
  113. void down_n(size_t n)
  114. {
  115. clear_status();
  116. while (n - (m_lines.size() - m_line) + m_height - 1 > 0) {
  117. if (!read_line())
  118. break;
  119. }
  120. m_line += write_range(min(m_line + m_height - 1, m_line + (m_lines.size() - m_line)), n);
  121. status_line();
  122. fflush(m_tty);
  123. }
  124. void top()
  125. {
  126. up_n(m_line);
  127. }
  128. void bottom()
  129. {
  130. while (read_line())
  131. ;
  132. down_n(m_lines.size() - m_line);
  133. }
  134. void up_half_page()
  135. {
  136. up_n(m_height / 2);
  137. }
  138. void down_half_page()
  139. {
  140. down_n(m_height / 2);
  141. }
  142. void go_to_line(size_t line_num)
  143. {
  144. if (line_num < m_line) {
  145. up_n(m_line - line_num);
  146. } else {
  147. down_n(line_num - m_line);
  148. }
  149. }
  150. void init()
  151. {
  152. while (m_lines.size() < m_height) {
  153. if (!read_line())
  154. break;
  155. }
  156. write_range(0, m_height - 1);
  157. status_line();
  158. m_line = 0;
  159. fflush(m_tty);
  160. }
  161. size_t write_range(size_t start, size_t length)
  162. {
  163. size_t lines = min(length, m_lines.size() - start);
  164. for (size_t i = 0; i < lines; ++i) {
  165. out(m_tty, "{}", m_lines[start + i]);
  166. }
  167. return lines;
  168. }
  169. void clear_status()
  170. {
  171. out(m_tty, "\e[2K\r");
  172. }
  173. void status_line()
  174. {
  175. out(m_tty, "\e[7m ");
  176. render_status_line(m_prompt);
  177. out(m_tty, " \e[27m");
  178. }
  179. void set_filename(StringView const& filename)
  180. {
  181. m_filename = filename;
  182. }
  183. void set_prompt(StringView const& prompt)
  184. {
  185. m_prompt = prompt;
  186. }
  187. bool read_line()
  188. {
  189. char* line = nullptr;
  190. size_t n = 0;
  191. ssize_t size = getline(&line, &n, m_file);
  192. if (size == -1)
  193. return false;
  194. m_lines.extend(wrap_line(Utf8View(line), m_width));
  195. free(line);
  196. return true;
  197. }
  198. bool at_end()
  199. {
  200. return (m_line + m_height - 1) >= m_lines.size() && feof(m_file);
  201. }
  202. private:
  203. size_t render_status_line(StringView const& prompt, size_t off = 0, char end = '\0', bool ignored = false)
  204. {
  205. for (; prompt[off] != end && off < prompt.length(); ++off) {
  206. if (ignored)
  207. continue;
  208. if (off + 1 >= prompt.length()) {
  209. // Don't parse any multi-character sequences if we are at the end of input.
  210. out(m_tty, "{}", prompt[off]);
  211. continue;
  212. }
  213. switch (prompt[off]) {
  214. case '?':
  215. switch (prompt[++off]) {
  216. case 'f':
  217. off = render_status_line(prompt, off + 1, ':', m_file == stdin);
  218. off = render_status_line(prompt, off + 1, '.', m_file != stdin);
  219. break;
  220. case 'e':
  221. off = render_status_line(prompt, off + 1, ':', !at_end());
  222. off = render_status_line(prompt, off + 1, '.', at_end());
  223. break;
  224. default:
  225. // Unknown flags are never true.
  226. off = render_status_line(prompt, off + 1, ':', true);
  227. off = render_status_line(prompt, off + 1, '.', false);
  228. }
  229. break;
  230. case '%':
  231. switch (prompt[++off]) {
  232. case 'f':
  233. out(m_tty, "{}", m_filename);
  234. break;
  235. case 'l':
  236. out(m_tty, "{}", m_line);
  237. break;
  238. default:
  239. out(m_tty, "?");
  240. }
  241. break;
  242. case '\\':
  243. ++off;
  244. [[fallthrough]];
  245. default:
  246. out(m_tty, "{}", prompt[off]);
  247. }
  248. }
  249. return off;
  250. }
  251. // FIXME: Don't save scrollback when emulating more.
  252. Vector<String> m_lines;
  253. size_t m_line { 0 };
  254. FILE* m_file;
  255. FILE* m_tty;
  256. size_t m_width;
  257. size_t m_height;
  258. String m_filename;
  259. String m_prompt;
  260. };
  261. static String get_key_sequence()
  262. {
  263. // We need a buffer to handle ansi sequences.
  264. char buff[8];
  265. ssize_t n = read(STDOUT_FILENO, buff, sizeof(buff));
  266. return String(buff, n);
  267. }
  268. static void cat_file(FILE* file)
  269. {
  270. ByteBuffer buffer = ByteBuffer::create_uninitialized(4096);
  271. while (!feof(file)) {
  272. size_t n = fread(buffer.data(), 1, buffer.size(), file);
  273. if (n == 0 && ferror(file)) {
  274. perror("fread");
  275. exit(1);
  276. }
  277. n = fwrite(buffer.data(), 1, n, stdout);
  278. if (n == 0 && ferror(stdout)) {
  279. perror("fwrite");
  280. exit(1);
  281. }
  282. }
  283. }
  284. int main(int argc, char** argv)
  285. {
  286. if (pledge("stdio rpath tty", nullptr) < 0) {
  287. perror("pledge");
  288. return 1;
  289. }
  290. char const* filename = "-";
  291. char const* prompt = "?f%f :.(line %l)?e (END):.";
  292. bool dont_switch_buffer = false;
  293. bool quit_at_eof = false;
  294. bool emulate_more = false;
  295. if (LexicalPath::basename(argv[0]) == "more"sv)
  296. emulate_more = true;
  297. Core::ArgsParser args_parser;
  298. args_parser.add_positional_argument(filename, "The paged file", "file", Core::ArgsParser::Required::No);
  299. args_parser.add_option(prompt, "Prompt line", "prompt", 'P', "Prompt");
  300. args_parser.add_option(dont_switch_buffer, "Don't use xterm alternate buffer", "no-init", 'X');
  301. args_parser.add_option(quit_at_eof, "Exit when the end of the file is reached", "quit-at-eof", 'e');
  302. args_parser.add_option(emulate_more, "Pretend that we are more(1)", "emulate-more", 'm');
  303. args_parser.parse(argc, argv);
  304. FILE* file;
  305. if (String("-") == filename) {
  306. file = stdin;
  307. } else if ((file = fopen(filename, "r")) == nullptr) {
  308. perror("fopen");
  309. exit(1);
  310. }
  311. if (pledge("stdio tty", nullptr) < 0) {
  312. perror("pledge");
  313. return 1;
  314. }
  315. if (emulate_more) {
  316. // Configure options that match more's behavior
  317. dont_switch_buffer = true;
  318. quit_at_eof = true;
  319. prompt = "--More--";
  320. }
  321. if (!isatty(STDOUT_FILENO)) {
  322. cat_file(file);
  323. return 0;
  324. }
  325. setup_tty(!dont_switch_buffer);
  326. Pager pager(file, stdout, g_wsize.ws_col, g_wsize.ws_row);
  327. pager.set_filename(filename);
  328. pager.set_prompt(prompt);
  329. pager.init();
  330. StringBuilder modifier_buffer = StringBuilder(10);
  331. for (String sequence;; sequence = get_key_sequence()) {
  332. if (sequence.to_uint().has_value()) {
  333. modifier_buffer.append(sequence);
  334. } else {
  335. if (sequence == "" || sequence == "q") {
  336. break;
  337. } else if (sequence == "j" || sequence == "\e[B" || sequence == "\n") {
  338. if (!emulate_more) {
  339. if (!modifier_buffer.is_empty())
  340. pager.down_n(modifier_buffer.build().to_uint().value_or(1));
  341. else
  342. pager.down();
  343. }
  344. } else if (sequence == "k" || sequence == "\e[A") {
  345. if (!emulate_more) {
  346. if (!modifier_buffer.is_empty())
  347. pager.up_n(modifier_buffer.build().to_uint().value_or(1));
  348. else
  349. pager.up();
  350. }
  351. } else if (sequence == "g") {
  352. if (!emulate_more) {
  353. if (!modifier_buffer.is_empty())
  354. pager.go_to_line(modifier_buffer.build().to_uint().value());
  355. else
  356. pager.top();
  357. }
  358. } else if (sequence == "G") {
  359. if (!emulate_more) {
  360. if (!modifier_buffer.is_empty())
  361. pager.go_to_line(modifier_buffer.build().to_uint().value());
  362. else
  363. pager.bottom();
  364. }
  365. } else if (sequence == " " || sequence == "\e[6~") {
  366. pager.down_page();
  367. } else if (sequence == "\e[5~" && !emulate_more) {
  368. pager.up_page();
  369. } else if (sequence == "d") {
  370. pager.down_half_page();
  371. } else if (sequence == "u" && !emulate_more) {
  372. pager.up_half_page();
  373. }
  374. modifier_buffer.clear();
  375. }
  376. if (quit_at_eof && pager.at_end())
  377. break;
  378. }
  379. pager.clear_status();
  380. teardown_tty(!dont_switch_buffer);
  381. return 0;
  382. }