File size: 39,855 Bytes
d1be154 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 | // MIT License
//
// Copyright (c) 2018 Chun-Xun Lin, Tsung-Wei Huang and Martin D. F. Wong
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#ifndef PROMPT_HPP_
#define PROMPT_HPP_
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <termios.h>
#include <pwd.h>
#include <errno.h>
#include <unistd.h>
#include <algorithm>
#include <unistd.h>
#include <sstream>
#include <iostream>
#include <memory>
#include <list>
#include <vector>
#include <cstring>
#include <fstream>
#include <string_view>
#include <filesystem>
#include <cassert>
// ------------------------------------------------------------------------------------------------
namespace prompt {
// Procedure: read_line
// Read one line from an input stream
//template <typename C, typename T, typename A>
//std::basic_istream<C, T>& read_line(
// std::basic_istream<C, T>& is,
// std::basic_string<C, T, A>& line
//) {
//
// line.clear();
//
// typename std::basic_istream<C, T>::sentry se(is, true);
// std::streambuf* sb = is.rdbuf();
//
// for(;;) {
// switch (int c = sb->sbumpc(); c) {
//
// // case 1: newline
// case '\n':
// return is;
// break;
//
// // case 2: carriage return
// case '\r':
// if(sb->sgetc() == '\n'){
// sb->sbumpc();
// }
// return is;
// break;
//
// // case 3: eof
// case std::streambuf::traits_type::eof():
// // Also handle the case when the last line has no line ending
// if(line.empty()) {
// is.setstate(std::ios::eofbit | std::ios::failbit);
// }
// return is;
// break;
//
// default:
// line.push_back(static_cast<char>(c));
// break;
// }
// }
//
// return is;
//}
template <typename C, typename T, typename A>
bool read_line(
FILE* is,
std::basic_string<C, T, A>& line
) {
line.clear();
for(;;) {
switch (int c = ::fgetc(is); c) {
// case 1: newline
case '\n':
return true;
break;
// case 2: carriage return '\r\n'
case '\r':
if(auto nc = ::fgetc(is); nc != '\n'){
::ungetc(nc, is);
}
return true;
break;
// case 3: eof
case EOF:
// Also handle the case when the last line has no line ending
if(line.empty()) {
// The line is empty (only EOF)
return false;
}
return true;
break;
default:
line.push_back(static_cast<char>(c));
break;
}
}
return true;
}
// ------------------------------------------------------------------------------------------------
// Function: count_prefix
// Count the the length of same prefix between two strings
template <typename C>
constexpr size_t count_prefix(
std::basic_string_view<typename C::value_type, typename C::traits_type> s1,
std::basic_string_view<typename C::value_type, typename C::traits_type> s2){
size_t i {0};
size_t len {std::min(s1.size(), s2.size())};
for(; i<len; ++i){
if(s1[i] != s2[i]){
break;
}
}
return i;
}
// ------------------------------------------------------------------------------------------------
// Class: RadixTree
template <typename C>
class RadixTree{
using value_type = typename C::value_type;
using traits_type = typename C::traits_type;
using allocator_type = typename C::allocator_type;
public:
struct Node {
bool is_word {false};
std::list<std::pair<C, std::unique_ptr<Node>>> children;
};
RadixTree() = default;
RadixTree(const std::vector<C>&);
bool exist(std::basic_string_view<value_type, traits_type>) const;
void insert(const C&);
std::vector<C> match_prefix(const C&) const;
std::vector<C> all_words() const;
C dump() const;
const Node& root() const;
private:
Node _root;
void _insert(std::basic_string_view<value_type, traits_type>, Node&);
void _match_prefix(std::vector<C>&, const Node&, const C&) const;
void _dump(const Node&, size_t, C&) const;
std::pair<const Node*, C> _search_prefix_node(
std::basic_string_view<value_type, traits_type>
) const;
};
// Procedure: Ctor
template <typename C>
RadixTree<C>::RadixTree(const std::vector<C>& words){
for(const auto& w: words){
insert(w);
}
}
// Procedure: dump
// Dump the radix tree into a string
template <typename C>
C RadixTree<C>::dump() const {
C t;
_dump(_root, 0, t);
t.append(1, '\n');
return t;
}
// Procedure: _dump
// Recursively traverse the tree and append each level to string
template <typename C>
void RadixTree<C>::_dump(const Node& n, size_t level, C& s) const {
for(auto &[k,v]: n.children){
s.append(level, '-');
s.append(1, ' ');
s += k;
s.append(1, '\n');
_dump(*v, level+1, s);
}
}
// Procedure: _match_prefix
// Find all words that match the given prefix
template <typename C>
void RadixTree<C>::_match_prefix(
std::vector<C> &vec,
const Node& n,
const C& s
) const {
if(n.is_word){
vec.emplace_back(s);
}
for(auto& [k,v]:n.children){
_match_prefix(vec, *v, s+k);
}
}
// Procedure: all_words
// Extract all words in the radix tree
template <typename C>
std::vector<C> RadixTree<C>::all_words() const {
std::vector<C> words;
for(auto &[k, v]: _root.children){
_match_prefix(words, *v, k);
}
return words;
}
// Procedure: match_prefix
// Collect all words that match the given prefix
template <typename C>
std::vector<C> RadixTree<C>::match_prefix(const C& prefix) const {
if(auto [prefix_node, suffix] = _search_prefix_node(prefix); prefix_node == nullptr){
return {};
}
else{
std::vector<C> matches;
if(prefix_node->is_word){
matches.emplace_back(prefix + suffix);
}
for(auto &[k, v]: prefix_node->children){
_match_prefix(matches, *v, prefix+suffix+k);
}
return matches;
}
}
// Procedure: _search_prefix_node
// Find the node that matches the given prefix
template <typename C>
std::pair<const typename RadixTree<C>::Node*, C> RadixTree<C>::_search_prefix_node(
std::basic_string_view<value_type, traits_type> s
) const {
Node const *n = &_root;
std::basic_string<value_type, traits_type> suffix;
for(size_t pos=0; pos<s.size(); ){ // Search until full match
bool match = {false};
for(const auto& [k, v]: n->children){
if(auto num = count_prefix<C>(k, s.data()+pos); num>0){
pos += num;
if(pos == s.size()){
suffix = k.substr(num, k.size()-num);
}
n = v.get();
match = true;
break;
}
}
if(not match){
return {nullptr, suffix};
}
}
return {n, suffix};
}
// Procedure: exist
// Check whether the given word is in the radix tree or not
template <typename C>
bool RadixTree<C>::exist(std::basic_string_view<value_type, traits_type> s) const {
size_t pos {0};
Node const *n = &_root;
while(not n->children.empty()){ // Search until reaching the leaf
bool match {false};
for(const auto& [k, v]: n->children){
auto match_num = count_prefix<C>(k, s.data()+pos);
if(match_num > 0){
if(pos += match_num; pos == s.size()){
if(match_num == k.size() and v->is_word){
return true;
}
}
else{
n = v.get();
match = true;
}
break;
}
}
if(not match){
return false;
}
}
return false;
}
// Procedure: insert
// Insert a word into radix tree
template <typename C>
void RadixTree<C>::insert(const C& s){
if(s.empty()){ // Empty string not allowed
return;
}
_insert(s, _root);
}
// Procedure: _insert
// Insert a word into radix tree
template <typename C>
void RadixTree<C>::_insert(std::basic_string_view<value_type, traits_type> sv, Node& n){
// base case
if(sv.empty()) {
n.is_word = true;
return;
}
size_t match_num {0};
auto itr = std::find_if(n.children.begin(), n.children.end(), [&] (const auto& kv) {
if(match_num = count_prefix<C>(std::get<0>(kv), sv); match_num > 0) {
return true;
}
else return false;
});
if(match_num == 0){ // Base case 1
assert(itr == n.children.end());
auto& child = std::get<1>(n.children.emplace_back(std::make_pair(sv, new Node)));
child->is_word = true;
}
else {
if(match_num == itr->first.size()) {
_insert(sv.data() + match_num, *itr->second);
}
else {
auto& par = std::get<1>(n.children.emplace_back(
std::make_pair(
std::basic_string_view<value_type, traits_type>{sv.data(), match_num}, new Node))
);
par->children.emplace_back(
std::make_pair(itr->first.data()+match_num, std::move(itr->second))
);
n.children.erase(itr);
_insert(sv.data() + match_num, *par);
}
}
}
// Procedure: root
// Return the root of RadixTree
template <typename C>
const typename RadixTree<C>::Node& RadixTree<C>::root() const{
return _root;
}
// ------------------------------------------------------------------------------------------------
// http://www.physics.udel.edu/~watson/scen103/ascii.html
enum class KEY{
KEY_NULL = 0, /* NULL */
CTRL_A = 1, /* Ctrl+a */
CTRL_B = 2, /* Ctrl-b */
CTRL_C = 3, /* Ctrl-c */
CTRL_D = 4, /* Ctrl-d */
CTRL_E = 5, /* Ctrl-e */
CTRL_F = 6, /* Ctrl-f */
CTRL_H = 8, /* Ctrl-h */
TAB = 9, /* Tab */
CTRL_K = 11, /* Ctrl+k */
CTRL_L = 12, /* Ctrl+l */
ENTER = 13, /* Enter */
CTRL_N = 14, /* Ctrl-n */
CTRL_P = 16, /* Ctrl-p */
CTRL_T = 20, /* Ctrl-t */
CTRL_U = 21, /* Ctrl+u */
CTRL_W = 23, /* Ctrl+w */
ESC = 27, /* Escape */
BACKSPACE = 127 /* Backspace */
};
enum class COLOR{
BLACK = 30,
RED,
GREEN,
YELLOW,
BLUE,
MAGNETA,
CYAN,
WHITE
};
class Prompt {
struct LineInfo{
std::string buf;
int history_trace {0};
size_t cur_pos {0}; // cursor position
void operator = (const LineInfo&);
inline void reset(){
cur_pos = history_trace = 0;
buf.clear();
}
};
public:
//Prompt(
// const std::string&, // Welcome message
// const std::string&, // prompt
// const filesystem::path& = filesystem::current_path()/".prompt_history", // history log path
// std::istream& = std::cin,
// std::ostream& = std::cout,
// std::ostream& = std::cerr,
// int = STDIN_FILENO
//);
//// TODO:
Prompt(
const std::string&, // Welcome message
const std::string&, // prompt
const std::filesystem::path& = std::filesystem::current_path()/".prompt_history", // history log path
FILE* = stdin,
std::ostream& = std::cout,
std::ostream& = std::cerr
);
~Prompt();
bool readline(std::string&);
void set_history_size(size_t);
size_t history_size() const { return _history.size(); };
void autocomplete(const std::string&);
private:
std::string _prompt;
std::filesystem::path _history_path;
// TODO: replace these with FILE* _is, _os, _es;
// fix inserters and extractors
//std::istream& _cin;
FILE* _is;
std::ostream& _cout;
std::ostream& _cerr;
// TODO: remove _infd and use ::fileno(_is);
//int _infd;
size_t _columns {80}; // default width of terminal is 80
RadixTree<std::string> _tree; // Radix tree for command autocomplete
std::string _obuf; // Buffer for _refresh_single_line
bool _unsupported_term();
bool _stdin_not_tty(std::string &);
bool _set_raw_mode();
void _disable_raw_mode();
// History
size_t _max_history_size {100};
std::list<std::string> _history;
void _add_history(const std::string&);
void _save_history();
void _load_history();
termios _orig_termios;
bool _has_orig_termios {false};
bool _save_orig_termios(int);
int _get_cursor_pos();
void _clear_screen();
size_t _terminal_columns();
void _edit_line(std::string&);
void _refresh_single_line(LineInfo&);
LineInfo _line;
LineInfo _line_save;
int _autocomplete_iterate_command();
void _autocomplete_command();
void _autocomplete_folder();
std::vector<std::string> _files_in_folder(const std::filesystem::path&) const;
std::vector<std::string> _files_match_prefix(const std::filesystem::path&) const;
std::string _dump_files(const std::vector<std::string>&, const std::filesystem::path&);
std::string _dump_options(const std::vector<std::string>&);
std::string _next_prefix(const std::vector<std::string>&, const size_t);
std::filesystem::path _user_home() const;
bool _has_read_access(const std::filesystem::path&) const;
// Key handling subroutine
void _key_backspace(LineInfo&);
void _key_delete(LineInfo&);
void _key_delete_prev_word(LineInfo&);
void _key_prev_history(LineInfo&);
void _key_next_history(LineInfo&);
void _key_history(LineInfo&, bool);
bool _key_handle_CSI(LineInfo&);
bool _append_character(LineInfo&, char);
};
// Copy assignment
inline void Prompt::LineInfo::operator = (const LineInfo& l){
buf = l.buf;
cur_pos = l.cur_pos;
history_trace = l.history_trace;
}
//// Procedure: Ctor
//inline Prompt::Prompt(
// const std::string& welcome_msg,
// const std::string& pmt,
// const filesystem::path& path,
// std::istream& in,
// std::ostream& out,
// std::ostream& err,
// int infd
//):
// _prompt(pmt),
// _history_path(path),
// _cin(in),
// _cout(out),
// _cerr(err),
// _infd(infd)
//{
// if(::isatty(_infd)){
// _cout << welcome_msg;
// _columns = _terminal_columns();
// if(filesystem::exists(_history_path)){
// if(std::error_code ec; not filesystem::is_regular_file(_history_path, ec)){
// _cerr << "The history file is not a regular file\n";
// }
// else{
// _load_history();
// }
// }
// }
//}
// Procedure: Ctor
inline Prompt::Prompt(
const std::string& welcome_msg,
const std::string& pmt,
const std::filesystem::path& path,
FILE* in,
std::ostream& out,
std::ostream& err
):
_prompt(pmt),
_history_path(path),
_is(in),
_cout(out),
_cerr(err)
{
if(::isatty(::fileno(_is))){
_cout << welcome_msg;
_columns = _terminal_columns();
if(std::filesystem::exists(_history_path)){
if(std::error_code ec; not std::filesystem::is_regular_file(_history_path, ec)){
_cerr << "The history file is not a regular file\n";
}
else{
_load_history();
}
}
}
}
// Procedure: Dtor
inline Prompt::~Prompt(){
// Restore the original mode if has kept
if(_has_orig_termios){
//::tcsetattr(_infd, TCSAFLUSH, &_orig_termios);
::tcsetattr(::fileno(_is), TCSAFLUSH, &_orig_termios);
}
if(not _history.empty()){
_save_history();
}
}
// Procedure: autocomplete
// This function adds the word into radix tree
inline void Prompt::autocomplete(const std::string& word){
_tree.insert(word);
}
// Procedure: history_size
// Change the max history size
inline void Prompt::set_history_size(size_t new_size){
_max_history_size = new_size;
}
// Procedure: _save_history
// Save history commands to a file
inline void Prompt::_save_history(){
std::ofstream ofs(_history_path);
if(not ofs.good()){
return;
}
for(const auto& c: _history){
ofs << c << '\n';
}
ofs.close();
}
// Procedure: _load_history
// Load history commands from a file
inline void Prompt::_load_history(){
if(std::filesystem::exists(_history_path)){
std::ifstream ifs(_history_path);
std::string placeholder;
while(std::getline(ifs, placeholder)){
if(_history.size() == _max_history_size){
_history.pop_front();
}
_history.emplace_back(std::move(placeholder));
}
}
}
// Procedure: _add_history
// Add command to history list
inline void Prompt::_add_history(const std::string &hist){
// hist cannot be empty and cannot be the same as the last one
if(hist.empty() or (not _history.empty() and _history.back() == hist)){
return ;
}
if(_history.size() == _max_history_size){
_history.pop_front();
}
_history.emplace_back(hist);
}
// Procedure: _stdin_not_tty
// Store input in a string if stdin is not from tty (from pipe or redirected file)
inline bool Prompt::_stdin_not_tty(std::string& s){
//read_line(_cin, s); // Read until newline, CR or EOF.
return read_line(_is, s);
}
// Procedure: _unsupported_term
// Check the terminal is supported or not
inline bool Prompt::_unsupported_term(){
static auto _unsupported_terms = {"dumb", "cons25", "emacs"};
if(char* term = getenv("TERM"); term == NULL){
return false;
}
else if(std::string_view str(term);
std::find(_unsupported_terms.begin(),
_unsupported_terms.end() , str) != _unsupported_terms.end()){
return true;
}
else {
return false;
}
}
// Procedure: readline
// This is the main entry of Prompt
inline bool Prompt::readline(std::string& s) {
if(! ::isatty(::fileno(_is))) {
// not a tty, either from file or pipe; we don't limit the line size
if(!_stdin_not_tty(s)){
return false;
}
// TODO: ferror precedes feof
return ::ferror(_is) ? false : ::feof(_is) ? false : true;
//return _cin.eof() ? false : true;
}
else if(_unsupported_term()){
//read_line(_cin, s);
if(!read_line(_is, s)) return false;
return ::ferror(_is) ? false : ::feof(_is) ? false : true;
//return _cin.eof() ? false : true;
}
else{
if(not _set_raw_mode()){
return {};
}
_edit_line(s);
_add_history(s);
_disable_raw_mode();
// TODO: what?
//std::cout << '\n';
_cout << '\n';
return errno == EAGAIN ? false : true;
}
}
// Procedure: _save_orig_termios
// Save the original termios for recovering before exit
inline bool Prompt::_save_orig_termios(int fd){
if(not _has_orig_termios){
if(::tcgetattr(fd, &_orig_termios) == -1){
return false;
}
_has_orig_termios = true;
}
return true;
}
// Procedure: _get_cursor_pos
// Return the current position of cursor
inline int Prompt::_get_cursor_pos(){
/* Report cursor location */
// x1b[6n : DSR - Device Status Report https://en.wikipedia.org/wiki/ANSI_escape_code
// The output will be like : ESC[n;mR, where "n" is the row and "m" is the column.
// Try this in ur terminal : echo -en "abc \x1b[6n"
if(not (_cout << "\x1b[6n")){
return -1;
}
char buf[32];
int cols, rows;
/* Read the response: ESC [ rows ; cols R */
for(size_t i=0; i<sizeof(buf)-1; i++){
//if(not(_cin >> buf[i]) or buf[i] == 'R'){
if(buf[i]=fgetc(_is); ::ferror(_is) || buf[i] == 'R'){
buf[i] = '\0';
break;
}
}
/* Parse it. */
if (static_cast<KEY>(buf[0]) != KEY::ESC or
buf[1] != '[' or
::sscanf(buf+2, "%d;%d", &rows, &cols) != 2){
return -1;
}
return cols;
}
// Procedure: _clear_screen (ctrl + l)
inline void Prompt::_clear_screen() {
// https://en.wikipedia.org/wiki/ANSI_escape_code
// CSI n ; m H : CUP - Cursor Position
// CSI n J : Erase in Display
//if(_cout.write("\x1b[H\x1b[2J",7); !_cout.good()){
if(not (_cout << "\x1b[H\x1b[2J")){
/* nothing to do, just to avoid warning. */
}
}
// Procedure: _set_raw_mode
// Set the fd to raw mode
inline bool Prompt::_set_raw_mode(){
if(::isatty(::fileno(_is)) and _save_orig_termios(::fileno(_is)) == true){
struct termios raw;
raw = _orig_termios; /* modify the original mode */
/* input modes: no break, no CR to NL, no parity check, no strip char,
* no start/stop output control. */
raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
/* output modes - disable post processing */
raw.c_oflag &= ~(OPOST);
/* control modes - set 8 bit chars */
raw.c_cflag |= (CS8);
/* local modes - choing off, canonical off, no extended functions,
* no signal chars (^Z,^C) */
raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
/* control chars - set return condition: min number of bytes and timer.
* We want read to return every single byte, without timeout. */
raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */
/* put terminal in raw mode after flushing */
if (::tcsetattr(::fileno(_is), TCSAFLUSH, &raw) >= 0){
return true;
}
}
errno = ENOTTY;
return false;
}
// Procedure: _disable_raw_mode
// Recover the termios to the original mode
inline void Prompt::_disable_raw_mode(){
if(_has_orig_termios){
::tcsetattr(::fileno(_is), TCSAFLUSH, &_orig_termios);
}
}
// Procedure: _terminal_columns
// Get the number of columns of current line buf
inline size_t Prompt::_terminal_columns(){
// Use ioctl to get Window size
if(winsize ws; ::ioctl(1, TIOCGWINSZ, &ws) == -1 or ws.ws_col == 0){
int start = _get_cursor_pos();
if(start == -1 or not (_cout << "\x1b[999c")){
return 80;
}
int cols = _get_cursor_pos();
if(cols == -1){
return 80;
}
if(cols > start){
char seq[32];
// Move cursor back
::snprintf(seq, 32, "\x1b[%dD", cols-start);
if(_cout.write(seq, strlen(seq)); not _cout.good()){
/* Fail to move cursor back*/
}
}
return cols;
}
else{
return ws.ws_col;
}
}
// Procedure: user_home
// Return the home folder of user
inline std::filesystem::path Prompt::_user_home() const{
auto home = ::getenv("HOME");
if(home == nullptr) {
home = ::getpwuid(::getuid())->pw_dir;
}
return home ? home : std::filesystem::current_path();
}
// Procedure: _has_read_access
// Check a file has read access grant to the user
inline bool Prompt::_has_read_access(const std::filesystem::path &path) const {
if(auto rval=::access(path.c_str(), F_OK); rval == 0){
if(rval = ::access(path.c_str(), R_OK); rval == 0){
return true;
}
}
return false;
}
// Procedure: _next_prefix
// Find the prefix among a set of strings starting from position n
inline std::string Prompt::_next_prefix(const std::vector<std::string>& words, const size_t n){
if(words.empty()){
return {};
}
else if(words.size() == 1){
return words[0].substr(n, words[0].size()-n);
}
else{
for(size_t end=n ;;++end){
if(words[0].size() <= end){
return words[0].substr(n, end-n);
}
for(size_t i=1; i<words.size(); i++){
if(words[i].size() <= end or words[i][end] != words[0][end]){
return words[i].substr(n, end-n);
}
}
}
}
}
// Procedure: _autocomplete_iterate_command
// This is the main entry for autocomplete iterating commands
inline int Prompt::_autocomplete_iterate_command(){
if(auto words = _tree.match_prefix(_line.buf); words.empty()){
return 0;
}
else{
char c {0};
bool stop {false};
for(size_t i=0; not stop;){
if(i < words.size()){
_line_save = _line;
_line.cur_pos = words[i].size();
_line.buf = words[i];
_refresh_single_line(_line);
_line = _line_save;
}
else{
_refresh_single_line(_line);
}
//if(_cin.read(&c, 1); not _cin.good()){
if(c = ::fgetc(_is); ::ferror(_is)){
return -1;
}
switch(static_cast<KEY>(c)){
case KEY::TAB:
i = (i+1) % words.size();
break;
case KEY::ESC: // refresh the same thing again
_refresh_single_line(_line);
stop = true;
break;
default:
if(i < words.size()){
_line.buf = words[i];
_line.cur_pos = words[i].size();
}
stop = true;
break;
}
}
return c;
}
}
inline std::string Prompt::_dump_options(const std::vector<std::string>& opts){
if(opts.empty()){
return {};
}
const size_t col_width = std::max_element(opts.begin(), opts.end(),
[](const auto& a, const auto& b){
return a.size() < b.size();
}
)->size() + 4;
auto col_num = std::max(size_t{1}, _terminal_columns() / col_width);
std::string s;
for(size_t i=0; i<opts.size(); ++i){
if(i % col_num == 0) {
s.append("\n\r\x1b[0K");
}
s.append(opts[i]);
if(opts[i].size() < col_width){
s.append(col_width - opts[i].size(), ' ');
}
}
return s;
}
// Procedure: _autocomplete_command
// This is the main entry for command autocomplete
inline void Prompt::_autocomplete_command(){
if(auto words = _tree.match_prefix(_line.buf); words.empty()){
}
else{
if(auto suffix = _next_prefix(words, _line.cur_pos); not suffix.empty()){
_line.buf.insert(_line.cur_pos, suffix);
_line.cur_pos += suffix.size();
}
if(auto s = _dump_options(words); s.size() > 0){
s.append("\x1b[0K\n");
_cout << s;
}
_refresh_single_line(_line);
}
}
// Procedure: _files_match_prefix
// Find all the files in a folder that match the prefix
inline std::vector<std::string> Prompt::_files_match_prefix(
const std::filesystem::path& path
) const {
// Need to check in case path is a file in current folder (parent_path = "")
auto folder = path.filename() == path ? std::filesystem::current_path() : path.parent_path();
std::string prefix(path.filename());
std::vector<std::string> matches;
if(std::error_code ec; _has_read_access(folder) and std::filesystem::is_directory(folder, ec)){
for(const auto& p: std::filesystem::directory_iterator(folder)){
std::string fname {p.path().filename()};
if(fname.compare(0, prefix.size(), prefix) == 0){
matches.emplace_back(std::move(fname));
}
}
}
return matches;
}
// Procedure: _files_in_folder
// List all files in a given folder
inline std::vector<std::string> Prompt::_files_in_folder(
const std::filesystem::path& path
) const {
auto p = path.empty() ? std::filesystem::current_path() : path;
std::vector<std::string> matches;
// Check permission
if(_has_read_access(p)){
for(const auto& p: std::filesystem::directory_iterator(p)){
matches.emplace_back(p.path().filename());
}
}
return matches;
}
// Procedure: _dump_files
// Format the strings for pretty print in terminal.
inline std::string Prompt::_dump_files(
const std::vector<std::string>& v,
const std::filesystem::path& path)
{
if(v.empty()){
return {};
}
const size_t col_width = std::max_element(v.begin(), v.end(),
[](const auto& a, const auto& b){
return a.size() < b.size();
}
)->size() + 4;
auto col_num = std::max(size_t{1}, _terminal_columns() / col_width);
std::string s;
char seq[64];
snprintf(seq, 64, "\033[%d;1;49m", static_cast<int>(COLOR::BLUE));
std::error_code ec;
for(size_t i=0; i<v.size(); ++i){
if(i % col_num == 0) {
s.append("\n\r\x1b[0K");
}
if(std::filesystem::is_directory(path.native() + "/" + v[i], ec)){
// A typical color code example : \033[31;1;4m
// \033[ : begin of color code, 31 : red color, 1 : bold, 4 : underlined
s.append(seq, strlen(seq));
s.append(v[i]);
s.append("\033[0m");
}
else{
s.append(v[i]);
}
s.append(col_width - v[i].size(), ' ');
}
return s;
}
// Procedure: _autocomplete_folder
// The entry for folder autocomplete
inline void Prompt::_autocomplete_folder(){
std::string s;
size_t ws_index = _line.buf.rfind(' ', _line.cur_pos) + 1;
std::filesystem::path p(
_line.buf[ws_index] != '~' ?
_line.buf.substr(ws_index, _line.cur_pos - ws_index) :
_user_home().native() + _line.buf.substr(ws_index+1, _line.cur_pos-ws_index-1)
);
if(std::error_code ec; p.empty() or std::filesystem::is_directory(p, ec)) {
s = _dump_files(_files_in_folder(p), p);
}
else{
auto match = _files_match_prefix(p);
if(not match.empty()){
s = _dump_files(match, p.parent_path());
if(auto suffix = _next_prefix(match, p.filename().native().size()); not suffix.empty()){
_line.buf.insert(_line.cur_pos, suffix);
_line.cur_pos += suffix.size();
p += suffix;
// Append a '/' if is a folder and not the prefix of other files
if(std::filesystem::is_directory(p, ec) and
std::count_if(match.begin(), match.end(),
[p = p.filename().native()](const auto& m)
{ return (m.size() >= p.size() and m.compare(0, p.size(), p) == 0); }) == 1){
_line.buf.insert(_line.cur_pos, 1, '/');
_line.cur_pos += 1;
}
}
}
}
if(s.size() > 0){
s.append("\x1b[0K\n");
_cout << s;
}
_refresh_single_line(_line);
}
// Procedure: _key_delete_prev_word
// Remove the word before cursor (including the whitespace between cursor and the word)
inline void Prompt::_key_delete_prev_word(LineInfo& line){
// Remove all whitespace before cursor
auto iter = std::find_if_not(line.buf.rbegin()+line.buf.size()-line.cur_pos, line.buf.rend(),
[](const auto& c){ return c == ' ';});
auto offset = std::distance(iter.base(), line.buf.begin()+line.cur_pos);
line.buf.erase(iter.base(), line.buf.begin()+line.cur_pos);
line.cur_pos -= offset;
// Remove the word before cursor and stop at the first ws
iter = std::find_if_not(line.buf.rbegin()+line.buf.size()-line.cur_pos, line.buf.rend(),
[](const auto& c){ return c != ' ';});
offset = std::distance(iter.base(), line.buf.begin()+line.cur_pos);
line.buf.erase(iter.base(), line.buf.begin()+line.cur_pos);
line.cur_pos -= offset;
}
// Procedure: _key_delete
// Remove the character at cursor
inline void Prompt::_key_delete(LineInfo &line){
if(line.buf.size() > 0){
line.buf.erase(line.cur_pos, 1);
}
}
// Procedure: _key_backspace
// Remove the character before curosr
inline void Prompt::_key_backspace(LineInfo &line){
if(line.cur_pos > 0){
line.buf.erase(line.cur_pos-1, 1);
line.cur_pos--;
}
}
// Procedure: _key_prev_history
// Set line buffer to previous command in history
inline void Prompt::_key_prev_history(LineInfo& line){
_key_history(line, true);
}
// Procedure: _key_next_history
// Set line buffer to next command in history
inline void Prompt::_key_next_history(LineInfo& line){
_key_history(line, false);
}
// Procedure:_key_history
// Set the line buffer to previous/next history command
inline void Prompt::_key_history(LineInfo &line, bool prev){
if(_history.size() > 1){
*std::next(_history.begin(), _history.size()-1-line.history_trace) = line.buf;
if(line.history_trace += prev ? 1 : -1; line.history_trace < 0){
line.history_trace = 0;
}
else if(line.history_trace >= static_cast<int>(_history.size())){
line.history_trace = _history.size()-1;
}
else{
auto it = std::next(_history.begin(), _history.size()-1-line.history_trace);
line.buf = *it;
line.cur_pos = line.buf.size();
}
}
}
// Procedure: _append_character
// Insert a character to the cursor position in line buffer
inline bool Prompt::_append_character(LineInfo& line, char c){
try{
line.buf.insert(line.cur_pos, 1, c);
}
catch (const std::exception& e){
_cerr << "append failed: " << e.what() << '\n';
assert(false);
}
if(line.cur_pos++; line.buf.size() == line.cur_pos){
if(not (_cout << c)){
return false;
}
}
else{
_refresh_single_line(line);
}
return true;
}
// Procedure: _key_handle_CSI
// Handle Control Sequence Introducer
inline bool Prompt::_key_handle_CSI(LineInfo& line){
char seq[3];
//if(_cin.read(seq,1), _cin.read(seq+1,1); not _cin.good() ){
if(seq[0] = ::fgetc(_is), seq[1] = ::fgetc(_is); ::ferror(_is)){
return false;
}
if(seq[0] == '['){
if(seq[1] >= '0' and seq[1] <= '9'){
//if(_cin.read(seq+2, 1); not _cin.good()){
if(seq[2] = ::fgetc(_is); ::ferror(_is)){
return false;
}
if(seq[2] == '~' and seq[1] == '3'){
_key_delete(line);
}
}
else{
switch(seq[1]){
case 'A': // Prev history
_key_prev_history(line);
break;
case 'B': // Next history
_key_next_history(line);
break;
case 'C': // Move cursor to right
if(line.cur_pos != line.buf.size()){
line.cur_pos ++;
}
break;
case 'D': // Move cursor to left
if(line.cur_pos > 0){
line.cur_pos --;
}
break;
case 'H': // Home : move cursor to the starting
line.cur_pos = 0;
break;
case 'F': // End : move cursor to the end
line.cur_pos = line.buf.size();
break;
}
}
}
else if(seq[0] == 'O'){
switch(seq[1]){
case 'H': // Home : move cursor to the starting
line.cur_pos = 0;
break;
case 'F': // End : move cursor to the end
line.cur_pos = line.buf.size();
break;
}
}
return true;
}
// Procedure: _edit_line
// Handle the character input from the user
inline void Prompt::_edit_line(std::string &s){
if(not (_cout << _prompt)){
return;
}
_history.emplace_back("");
_line.reset();
s.clear();
for(char c;;){
//if(_cin.read(&c, 1); not _cin.good()){
if(c = ::fgetc(_is); ::ferror(_is)){
s = _line.buf;
return ;
}
// if user hits tab
if(static_cast<KEY>(c) == KEY::TAB){
if(_line.buf.empty()){
continue;
}
else if(_line.buf.rfind(' ', _line.cur_pos) != std::string::npos){
_autocomplete_folder();
continue;
}
else{
_autocomplete_command();
continue;
//if(c=_autocomplete_iterate_command(); c<0){
//if(c=_autocomplete_command(); c<0){
// // something wrong happened
// return;
//}
//else if(c == 0){
// continue;
//}
}
}
// Proceed to process character
switch(static_cast<KEY>(c)){
case KEY::ENTER:
_history.pop_back(); // Remove the emptry string history added in beginning
s = _line.buf;
return ;
case KEY::CTRL_A: // Go to the start of the line
if(_line.cur_pos != 0){
_line.cur_pos = 0;
}
_refresh_single_line(_line);
break;
case KEY::CTRL_B: // Move cursor to left
if(_line.cur_pos > 0){
_line.cur_pos --;
}
_refresh_single_line(_line);
break;
case KEY::CTRL_C:
_history.pop_back(); // Remove the emptry string history added in beginning
errno = EAGAIN;
return ;
case KEY::CTRL_D: // Remove the char at the right of cursor.
// If the line is empty, act as end-of-file
if(_line.buf.size() > 0){
_key_delete(_line);
_refresh_single_line(_line);
}
else{
_history.pop_back();
return;
}
break;
case KEY::CTRL_E: // Move cursor to end of line
if(_line.cur_pos != _line.buf.size()){
_line.cur_pos = _line.buf.size();
}
_refresh_single_line(_line);
break;
case KEY::CTRL_F: // Move cursor to right
if(_line.cur_pos != _line.buf.size()){
_line.cur_pos ++;
}
_refresh_single_line(_line);
break;
case KEY::BACKSPACE: // CTRL_H is the same as BACKSPACE
case KEY::CTRL_H:
_key_backspace(_line);
_refresh_single_line(_line);
break;
case KEY::CTRL_K: // Delete from current to EOF
_line.buf.erase(_line.cur_pos, _line.buf.size()-_line.cur_pos);
_refresh_single_line(_line);
break;
case KEY::CTRL_L: // Clear screen
_clear_screen();
_refresh_single_line(_line);
break;
case KEY::CTRL_N: // Next history command
_key_next_history(_line);
_refresh_single_line(_line);
break;
case KEY::CTRL_P: // Previous history command
_key_prev_history(_line);
_refresh_single_line(_line);
break;
case KEY::CTRL_T: // Swap current char with previous
if(_line.cur_pos > 0){
std::swap(_line.buf[_line.cur_pos], _line.buf[_line.cur_pos-1]);
if(_line.cur_pos < _line.buf.size()){
_line.cur_pos ++;
}
_refresh_single_line(_line);
}
break;
case KEY::CTRL_U: // Delete whole line
_line.cur_pos = 0;
_line.buf.clear();
_refresh_single_line(_line);
break;
case KEY::CTRL_W: // Delete previous word
_key_delete_prev_word(_line);
_refresh_single_line(_line);
break;
case KEY::ESC:
if(not _key_handle_CSI(_line)){
_history.pop_back(); // Remove the emptry string history added in beginning
return;
}
_refresh_single_line(_line);
break;
default:
_append_character(_line, c);
break;
}
}
}
// Procedure: _refresh_single_line
// Flush the current line buffer on screen
inline void Prompt::_refresh_single_line(LineInfo &l){
// 1. Append "move cursor to left" in the output buffer
// 2. Append buf to output buffer
// 3. Append "erase to the right" to the output buffer
// 4. Append "forward cursor" to the output buffer : Adjust cursor to correct pos
// 5. Write output buffer to fd
static const std::string CR {"\r"}; // Carriage Return (set cursor to left)
static const std::string EL {"\x1b[0K"}; // Erase in Line (clear from cursor to the end of the line)
auto len {l.buf.size()};
auto pos {l.cur_pos};
size_t start {0};
if(_prompt.length()+pos >= _columns){
start += _prompt.length()+pos-_columns-1;
len -= _prompt.length()+pos-_columns-1;
pos += (_prompt.length()+pos-_columns-1);
}
if(_prompt.length()+len > _columns){
len -= (_prompt.length()+len-_columns);
}
char seq[64];
::snprintf(seq, 64, "\r\x1b[%dC", (int)(pos+_prompt.length()));
_obuf.clear();
_obuf.reserve(CR.length()+_prompt.length()+len+EL.length()+strlen(seq));
_obuf.append(CR);
_obuf.append(_prompt);
_obuf.append(l.buf.data() + start, len);
_obuf.append(EL);
_obuf.append(seq, strlen(seq));
if(not (_cout << _obuf)){
_cerr << "Refresh line fail\n";
}
}
}; // end of namespace prompt. -------------------------------------------------------------------
#endif
|