├── .gitignore ├── CMakeLists.txt ├── LICENSE ├── README.md ├── example ├── CMakeLists.txt ├── example.cpp ├── example.sln ├── example.vcxproj ├── example_old.cpp └── multiinclude │ ├── f1.cpp │ ├── f2.cpp │ └── main.cpp └── linenoise.hpp /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files 2 | *.slo 3 | *.lo 4 | *.o 5 | *.obj 6 | 7 | # Precompiled Headers 8 | *.gch 9 | *.pch 10 | 11 | # Compiled Dynamic libraries 12 | *.so 13 | *.dylib 14 | *.dll 15 | 16 | # Fortran module files 17 | *.mod 18 | 19 | # Compiled Static libraries 20 | *.lai 21 | *.la 22 | *.a 23 | *.lib 24 | 25 | # Executables 26 | *.exe 27 | *.out 28 | *.app 29 | 30 | # Others 31 | *.dSYM 32 | *.swp 33 | Debug 34 | Release 35 | *.suo 36 | *.sdf 37 | *.user 38 | xcuserdata 39 | *.xcworkspace 40 | Makefile 41 | CMakeFiles 42 | CMakeCache.txt 43 | *.cmake 44 | history.txt 45 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | project(linenoise) 2 | 3 | cmake_minimum_required(VERSION 3.0) 4 | 5 | add_library(linenoise INTERFACE) 6 | target_include_directories(linenoise INTERFACE .) 7 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2015 yhirose 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | 1. Redistributions of source code must retain the above copyright notice, this 8 | list of conditions and the following disclaimer. 9 | 2. Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 14 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 15 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 16 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 17 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 18 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 19 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 20 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 21 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 22 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | cpp-linenoise 2 | ============= 3 | 4 | Multi-platform (Unix, Windows) C++ header-only linenoise-based readline library. 5 | 6 | This library gathered code from following excellent libraries, clean it up, and put it into a C++ header file for convenience. 7 | 8 | * `linenoise.h` and `linenoise.c` ([antirez/linenoise](https://github.com/antirez/linenoise)) 9 | * `ANSI.c` ([adoxa/ansicon](https://github.com/adoxa/ansicon)) 10 | * `Win32_ANSI.h` and `Win32_ANSI.c` ([MSOpenTech/redis](https://github.com/MSOpenTech/redis)) 11 | 12 | The licenses for the libraries are included in `linenoise.hpp`. 13 | 14 | Usage 15 | ----- 16 | 17 | ```c++ 18 | #include "linenoise.hpp" 19 | 20 | ... 21 | 22 | const auto path = "history.txt"; 23 | 24 | // Setup completion words every time when a user types 25 | linenoise::SetCompletionCallback([](const char* editBuffer, std::vector& completions) { 26 | if (editBuffer[0] == 'h') { 27 | completions.push_back("hello"); 28 | completions.push_back("hello there"); 29 | } 30 | }); 31 | 32 | // Enable the multi-line mode 33 | linenoise::SetMultiLine(true); 34 | 35 | // Set max length of the history 36 | linenoise::SetHistoryMaxLen(4); 37 | 38 | // Load history 39 | linenoise::LoadHistory(path); 40 | 41 | while (true) { 42 | // Read line 43 | std::string line; 44 | auto quit = linenoise::Readline("hello> ", line); 45 | 46 | if (quit) { 47 | break; 48 | } 49 | 50 | cout << "echo: '" << line << "'" << endl; 51 | 52 | // Add text to history 53 | linenoise::AddHistory(line.c_str()); 54 | } 55 | 56 | // Save history 57 | linenoise::SaveHistory(path); 58 | ``` 59 | 60 | API 61 | --- 62 | 63 | ```c++ 64 | namespace linenoise; 65 | 66 | std::string Readline(const char* prompt); 67 | 68 | void SetMultiLine(bool multiLineMode); 69 | 70 | typedef std::function& completions)> CompletionCallback; 71 | 72 | void SetCompletionCallback(CompletionCallback fn); 73 | 74 | bool SetHistoryMaxLen(size_t len); 75 | 76 | bool LoadHistory(const char* path); 77 | 78 | bool SaveHistory(const char* path); 79 | 80 | bool AddHistory(const char* line); 81 | 82 | const std::vector& GetHistory(); 83 | ``` 84 | 85 | Tested compilers 86 | ---------------- 87 | 88 | * Visual Studio 2015 89 | * Clang 3.5 90 | * GCC 6.3.1 91 | 92 | License 93 | ------- 94 | 95 | BSD license (© 2015 Yuji Hirose) 96 | -------------------------------------------------------------------------------- /example/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.0) 2 | include_directories(.) 3 | add_definitions("-std=c++1y") 4 | 5 | add_executable(example example.cpp) 6 | add_executable(example_old example_old.cpp) 7 | 8 | add_executable(multiinclude 9 | multiinclude/main.cpp 10 | multiinclude/f1.cpp 11 | multiinclude/f2.cpp 12 | ) 13 | 14 | -------------------------------------------------------------------------------- /example/example.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "../linenoise.hpp" 3 | 4 | using namespace std; 5 | 6 | int main(int argc, const char** argv) 7 | { 8 | const auto path = "history.txt"; 9 | 10 | #ifdef _WIN32 11 | const char *prompt = "hello> "; 12 | #else 13 | const char *prompt = "\033[32mこんにちは\x1b[0m> "; 14 | #endif 15 | 16 | linenoise::linenoiseState l(prompt); 17 | 18 | // Enable the multi-line mode 19 | l.EnableMultiLine(); 20 | 21 | // Set max length of the history 22 | l.SetHistoryMaxLen(4); 23 | 24 | // Setup completion words every time when a user types 25 | l.SetCompletionCallback([](const char* editBuffer, std::vector& completions) { 26 | if (editBuffer[0] == 'h') { 27 | #ifdef _WIN32 28 | completions.push_back("hello こんにちは"); 29 | completions.push_back("hello こんにちは there"); 30 | #else 31 | completions.push_back("hello"); 32 | completions.push_back("hello there"); 33 | #endif 34 | } 35 | }); 36 | 37 | // Load history 38 | l.LoadHistory(path); 39 | 40 | while (true) { 41 | std::string line; 42 | auto quit = l.Readline(line); 43 | 44 | if (quit) { 45 | break; 46 | } 47 | 48 | cout << "echo: '" << line << "'" << endl; 49 | 50 | // Add line to history 51 | l.AddHistory(line.c_str()); 52 | 53 | // Save history 54 | l.SaveHistory(path); 55 | } 56 | 57 | return 0; 58 | } 59 | -------------------------------------------------------------------------------- /example/example.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 14 4 | VisualStudioVersion = 14.0.23107.0 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "example", "example.vcxproj", "{563BF990-4217-439F-92A4-F8A285052772}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|x64 = Debug|x64 11 | Debug|x86 = Debug|x86 12 | Release|x64 = Release|x64 13 | Release|x86 = Release|x86 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {563BF990-4217-439F-92A4-F8A285052772}.Debug|x64.ActiveCfg = Debug|x64 17 | {563BF990-4217-439F-92A4-F8A285052772}.Debug|x64.Build.0 = Debug|x64 18 | {563BF990-4217-439F-92A4-F8A285052772}.Debug|x86.ActiveCfg = Debug|Win32 19 | {563BF990-4217-439F-92A4-F8A285052772}.Debug|x86.Build.0 = Debug|Win32 20 | {563BF990-4217-439F-92A4-F8A285052772}.Release|x64.ActiveCfg = Release|x64 21 | {563BF990-4217-439F-92A4-F8A285052772}.Release|x64.Build.0 = Release|x64 22 | {563BF990-4217-439F-92A4-F8A285052772}.Release|x86.ActiveCfg = Release|Win32 23 | {563BF990-4217-439F-92A4-F8A285052772}.Release|x86.Build.0 = Release|Win32 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | EndGlobal 29 | -------------------------------------------------------------------------------- /example/example.vcxproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | Win32 7 | 8 | 9 | Release 10 | Win32 11 | 12 | 13 | Debug 14 | x64 15 | 16 | 17 | Release 18 | x64 19 | 20 | 21 | 22 | {563BF990-4217-439F-92A4-F8A285052772} 23 | Win32Proj 24 | example 25 | 8.1 26 | 27 | 28 | 29 | Application 30 | true 31 | v140 32 | Unicode 33 | 34 | 35 | Application 36 | false 37 | v140 38 | true 39 | Unicode 40 | 41 | 42 | Application 43 | true 44 | v140 45 | Unicode 46 | 47 | 48 | Application 49 | false 50 | v140 51 | true 52 | Unicode 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | true 74 | 75 | 76 | true 77 | 78 | 79 | false 80 | 81 | 82 | false 83 | 84 | 85 | 86 | 87 | 88 | Level3 89 | Disabled 90 | WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) 91 | 92 | 93 | Console 94 | true 95 | 96 | 97 | 98 | 99 | 100 | 101 | Level3 102 | Disabled 103 | _DEBUG;_CONSOLE;%(PreprocessorDefinitions) 104 | 105 | 106 | Console 107 | true 108 | 109 | 110 | 111 | 112 | Level3 113 | 114 | 115 | MaxSpeed 116 | true 117 | true 118 | WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 119 | 120 | 121 | Console 122 | true 123 | true 124 | true 125 | 126 | 127 | 128 | 129 | Level3 130 | 131 | 132 | MaxSpeed 133 | true 134 | true 135 | NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 136 | 137 | 138 | Console 139 | true 140 | true 141 | true 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | -------------------------------------------------------------------------------- /example/example_old.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "../linenoise.hpp" 3 | 4 | using namespace std; 5 | 6 | int main(int argc, const char** argv) 7 | { 8 | const auto path = "history.txt"; 9 | 10 | // Enable the multi-line mode 11 | linenoise::SetMultiLine(true); 12 | 13 | // Set max length of the history 14 | linenoise::SetHistoryMaxLen(4); 15 | 16 | // Setup completion words every time when a user types 17 | linenoise::SetCompletionCallback([](const char* editBuffer, std::vector& completions) { 18 | if (editBuffer[0] == 'h') { 19 | #ifdef _WIN32 20 | completions.push_back("hello こんにちは"); 21 | completions.push_back("hello こんにちは there"); 22 | #else 23 | completions.push_back("hello"); 24 | completions.push_back("hello there"); 25 | #endif 26 | } 27 | }); 28 | 29 | // Load history 30 | linenoise::LoadHistory(path); 31 | 32 | while (true) { 33 | std::string line; 34 | #ifdef _WIN32 35 | auto quit = linenoise::Readline("hello> ", line); 36 | #else 37 | auto quit = linenoise::Readline("\033[32mこんにちは\x1b[0m> ", line); 38 | #endif 39 | 40 | if (quit) { 41 | break; 42 | } 43 | 44 | cout << "echo: '" << line << "'" << endl; 45 | 46 | // Add line to history 47 | linenoise::AddHistory(line.c_str()); 48 | 49 | // Save history 50 | linenoise::SaveHistory(path); 51 | } 52 | 53 | return 0; 54 | } 55 | -------------------------------------------------------------------------------- /example/multiinclude/f1.cpp: -------------------------------------------------------------------------------- 1 | #include "../linenoise.hpp" 2 | 3 | void f1() 4 | { 5 | linenoise::linenoiseState l("p1"); 6 | l.EnableMultiLine(); 7 | } 8 | 9 | -------------------------------------------------------------------------------- /example/multiinclude/f2.cpp: -------------------------------------------------------------------------------- 1 | #include "../linenoise.hpp" 2 | 3 | void f2() 4 | { 5 | linenoise::linenoiseState l("p2"); 6 | l.EnableMultiLine(); 7 | } 8 | 9 | -------------------------------------------------------------------------------- /example/multiinclude/main.cpp: -------------------------------------------------------------------------------- 1 | extern void f1(); 2 | extern void f2(); 3 | 4 | int main(int argc, const char** argv) 5 | { 6 | f1(); 7 | f2(); 8 | return 0; 9 | } 10 | -------------------------------------------------------------------------------- /linenoise.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | * linenoise.hpp -- Multi-platform C++ header-only linenoise library. 3 | * 4 | * All credits and commendations have to go to the authors of the 5 | * following excellent libraries. 6 | * 7 | * - linenoise.h and linenoise.c (https://github.com/antirez/linenoise) 8 | * - ANSI.c (https://github.com/adoxa/ansicon) 9 | * - Win32_ANSI.h and Win32_ANSI.c (https://github.com/MSOpenTech/redis) 10 | * 11 | * ------------------------------------------------------------------------ 12 | * 13 | * Copyright (c) 2015 yhirose 14 | * All rights reserved. 15 | * 16 | * Redistribution and use in source and binary forms, with or without 17 | * modification, are permitted provided that the following conditions are met: 18 | * 19 | * 1. Redistributions of source code must retain the above copyright notice, this 20 | * list of conditions and the following disclaimer. 21 | * 2. Redistributions in binary form must reproduce the above copyright notice, 22 | * this list of conditions and the following disclaimer in the documentation 23 | * and/or other materials provided with the distribution. 24 | * 25 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 26 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 27 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 28 | * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 29 | * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 30 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 31 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 32 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 33 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 34 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 35 | */ 36 | 37 | /* linenoise.h -- guerrilla line editing library against the idea that a 38 | * line editing lib needs to be 20,000 lines of C code. 39 | * 40 | * See linenoise.c for more information. 41 | * 42 | * ------------------------------------------------------------------------ 43 | * 44 | * Copyright (c) 2010, Salvatore Sanfilippo 45 | * Copyright (c) 2010, Pieter Noordhuis 46 | * 47 | * All rights reserved. 48 | * 49 | * Redistribution and use in source and binary forms, with or without 50 | * modification, are permitted provided that the following conditions are 51 | * met: 52 | * 53 | * * Redistributions of source code must retain the above copyright 54 | * notice, this list of conditions and the following disclaimer. 55 | * 56 | * * Redistributions in binary form must reproduce the above copyright 57 | * notice, this list of conditions and the following disclaimer in the 58 | * documentation and/or other materials provided with the distribution. 59 | * 60 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 61 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 62 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 63 | * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 64 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 65 | * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 66 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 67 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 68 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 69 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 70 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 71 | */ 72 | 73 | /* 74 | * ANSI.c - ANSI escape sequence console driver. 75 | * 76 | * Copyright (C) 2005-2014 Jason Hood 77 | * This software is provided 'as-is', without any express or implied 78 | * warranty. In no event will the author be held liable for any damages 79 | * arising from the use of this software. 80 | * 81 | * Permission is granted to anyone to use this software for any purpose, 82 | * including commercial applications, and to alter it and redistribute it 83 | * freely, subject to the following restrictions: 84 | * 85 | * 1. The origin of this software must not be misrepresented; you must not 86 | * claim that you wrote the original software. If you use this software 87 | * in a product, an acknowledgment in the product documentation would be 88 | * appreciated but is not required. 89 | * 2. Altered source versions must be plainly marked as such, and must not be 90 | * misrepresented as being the original software. 91 | * 3. This notice may not be removed or altered from any source distribution. 92 | * 93 | * Jason Hood 94 | * jadoxa@yahoo.com.au 95 | */ 96 | 97 | /* 98 | * Win32_ANSI.h and Win32_ANSI.c 99 | * 100 | * Derived from ANSI.c by Jason Hood, from his ansicon project (https://github.com/adoxa/ansicon), with modifications. 101 | * 102 | * Copyright (c), Microsoft Open Technologies, Inc. 103 | * All rights reserved. 104 | * Redistribution and use in source and binary forms, with or without 105 | * modification, are permitted provided that the following conditions are met: 106 | * - Redistributions of source code must retain the above copyright notice, 107 | * this list of conditions and the following disclaimer. 108 | * - Redistributions in binary form must reproduce the above copyright notice, 109 | * this list of conditions and the following disclaimer in the documentation 110 | * and/or other materials provided with the distribution. 111 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 112 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 113 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 114 | * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 115 | * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 116 | * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 117 | * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 118 | * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 119 | * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 120 | * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 121 | */ 122 | 123 | #ifndef LINENOISE_HPP 124 | #define LINENOISE_HPP 125 | 126 | #ifndef _WIN32 127 | #include 128 | #include 129 | #include 130 | #else 131 | #ifndef NOMINMAX 132 | #define NOMINMAX 133 | #endif 134 | #include 135 | #include 136 | #ifndef STDIN_FILENO 137 | #define STDIN_FILENO (_fileno(stdin)) 138 | #endif 139 | #ifndef STDOUT_FILENO 140 | #define STDOUT_FILENO 1 141 | #endif 142 | #define isatty _isatty 143 | #define write win32_write 144 | #define read _read 145 | #pragma warning(push) 146 | #pragma warning(disable : 4996) 147 | #endif 148 | #include 149 | #include 150 | #include 151 | #include 152 | #include 153 | #include 154 | #include 155 | #include 156 | #include 157 | #include 158 | #include 159 | #include 160 | #include 161 | 162 | namespace linenoise { 163 | 164 | #define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100 165 | #define LINENOISE_MAX_LINE 4096 166 | 167 | typedef std::function&)> CompletionCallback; 168 | 169 | /* The linenoiseState structure represents the state during line editing, and 170 | * provides methods by which user programs can act on that state. */ 171 | class linenoiseState { 172 | public: 173 | linenoiseState(const char *prompt = NULL, int stdin_fd = STDIN_FILENO, 174 | int stdout_fd = STDOUT_FILENO); 175 | 176 | void EnableMultiLine(); 177 | void DisableMultiLine(); 178 | 179 | bool AddHistory(const char *line); 180 | bool LoadHistory(const char *path); 181 | bool SaveHistory(const char *path); 182 | const std::vector &GetHistory() { return history_; }; 183 | bool SetHistoryMaxLen(size_t len); 184 | 185 | bool Readline(std::string &line); // Primary linenoise entry point 186 | void RefreshLine(); // Restore current line 187 | void WipeLine(); // Temporarily removes line from screen - RefreshLine will restore 188 | void ClearScreen(); // Clear terminal window 189 | 190 | void SetPrompt(const char *p); 191 | void SetPrompt(std::string &p); 192 | 193 | /* Register a callback function to be called for tab-completion. */ 194 | void SetCompletionCallback(CompletionCallback fn) { 195 | completionCallback = fn; 196 | }; 197 | 198 | private: 199 | std::string Readline(bool &quit); 200 | std::string Readline(); 201 | 202 | bool Raw(std::string &line); 203 | int EditInsert(const char *cbuf, int clen); 204 | void EditDelete(); 205 | void EditBackspace(); 206 | void EditDeletePrevWord(); 207 | int Edit(); 208 | void EditHistoryNext(int dir); 209 | void EditMoveLeft(); 210 | void EditMoveRight(); 211 | void EditMoveHome(); 212 | void EditMoveEnd(); 213 | void refreshSingleLine(); 214 | void refreshMultiLine(); 215 | int completeLine(char *cbuf, int *c); 216 | 217 | CompletionCallback completionCallback; 218 | 219 | int ifd_ = STDIN_FILENO; /* Terminal stdin file descriptor. */ 220 | int ofd_ = STDOUT_FILENO; /* Terminal stdout file descriptor. */ 221 | char *buf_ = wbuf_; /* Edited line buffer. */ 222 | int buf_len_ = LINENOISE_MAX_LINE; /* Edited line buffer size. */ 223 | int pos_ = 0; /* Current cursor position. */ 224 | int oldcolpos_ = 0; /* Previous refresh cursor column position. */ 225 | int len_ = 0; /* Current edited line length. */ 226 | int cols_ = -1; /* Number of columns in terminal. */ 227 | int maxrows_ = 0; /* Maximum num of rows used so far (multiline mode) */ 228 | int history_index_ = 0; /* The history index we are currently editing. */ 229 | char wbuf_[LINENOISE_MAX_LINE] = {'\0'}; 230 | std::string history_tmpbuf_; 231 | bool mlmode_ = false; /* Multi line mode. Default is single line. */ 232 | std::mutex mutex_; 233 | std::string prompt_ = std::string("> "); /* Prompt to display. */ 234 | 235 | size_t history_max_len_ = LINENOISE_DEFAULT_HISTORY_MAX_LEN; 236 | std::vector history_; 237 | }; 238 | 239 | 240 | /* Older style public API */ 241 | static linenoiseState *lglobal = NULL; 242 | void SetCompletionCallback(CompletionCallback fn); 243 | void SetMultiLine(bool ml); 244 | bool AddHistory(const char* line); 245 | bool SetHistoryMaxLen(size_t len); 246 | bool SaveHistory(const char* path); 247 | bool LoadHistory(const char* path); 248 | const std::vector& GetHistory(); 249 | bool Readline(const char *prompt, std::string& line); 250 | std::string Readline(const char *prompt, bool& quit); 251 | std::string Readline(const char *prompt); 252 | 253 | 254 | #ifdef _WIN32 255 | 256 | namespace ansi { 257 | 258 | #define lenof(array) (sizeof(array)/sizeof(*(array))) 259 | 260 | typedef struct 261 | { 262 | BYTE foreground; // ANSI base color (0 to 7; add 30) 263 | BYTE background; // ANSI base color (0 to 7; add 40) 264 | BYTE bold; // console FOREGROUND_INTENSITY bit 265 | BYTE underline; // console BACKGROUND_INTENSITY bit 266 | BYTE rvideo; // swap foreground/bold & background/underline 267 | BYTE concealed; // set foreground/bold to background/underline 268 | BYTE reverse; // swap console foreground & background attributes 269 | } GRM, *PGRM; // Graphic Rendition Mode 270 | 271 | 272 | inline bool is_digit(char c) { return '0' <= c && c <= '9'; } 273 | 274 | // ========== Global variables and constants 275 | 276 | HANDLE hConOut; // handle to CONOUT$ 277 | 278 | const char ESC = '\x1B'; // ESCape character 279 | const char BEL = '\x07'; 280 | const char SO = '\x0E'; // Shift Out 281 | const char SI = '\x0F'; // Shift In 282 | 283 | const int MAX_ARG = 16; // max number of args in an escape sequence 284 | int state; // automata state 285 | WCHAR prefix; // escape sequence prefix ( '[', ']' or '(' ); 286 | WCHAR prefix2; // secondary prefix ( '?' or '>' ); 287 | WCHAR suffix; // escape sequence suffix 288 | int es_argc; // escape sequence args count 289 | int es_argv[MAX_ARG]; // escape sequence args 290 | WCHAR Pt_arg[MAX_PATH * 2]; // text parameter for Operating System Command 291 | int Pt_len; 292 | BOOL shifted; 293 | 294 | 295 | // DEC Special Graphics Character Set from 296 | // http://vt100.net/docs/vt220-rm/table2-4.html 297 | // Some of these may not look right, depending on the font and code page (in 298 | // particular, the Control Pictures probably won't work at all). 299 | const WCHAR G1[] = 300 | { 301 | ' ', // _ - blank 302 | L'\x2666', // ` - Black Diamond Suit 303 | L'\x2592', // a - Medium Shade 304 | L'\x2409', // b - HT 305 | L'\x240c', // c - FF 306 | L'\x240d', // d - CR 307 | L'\x240a', // e - LF 308 | L'\x00b0', // f - Degree Sign 309 | L'\x00b1', // g - Plus-Minus Sign 310 | L'\x2424', // h - NL 311 | L'\x240b', // i - VT 312 | L'\x2518', // j - Box Drawings Light Up And Left 313 | L'\x2510', // k - Box Drawings Light Down And Left 314 | L'\x250c', // l - Box Drawings Light Down And Right 315 | L'\x2514', // m - Box Drawings Light Up And Right 316 | L'\x253c', // n - Box Drawings Light Vertical And Horizontal 317 | L'\x00af', // o - SCAN 1 - Macron 318 | L'\x25ac', // p - SCAN 3 - Black Rectangle 319 | L'\x2500', // q - SCAN 5 - Box Drawings Light Horizontal 320 | L'_', // r - SCAN 7 - Low Line 321 | L'_', // s - SCAN 9 - Low Line 322 | L'\x251c', // t - Box Drawings Light Vertical And Right 323 | L'\x2524', // u - Box Drawings Light Vertical And Left 324 | L'\x2534', // v - Box Drawings Light Up And Horizontal 325 | L'\x252c', // w - Box Drawings Light Down And Horizontal 326 | L'\x2502', // x - Box Drawings Light Vertical 327 | L'\x2264', // y - Less-Than Or Equal To 328 | L'\x2265', // z - Greater-Than Or Equal To 329 | L'\x03c0', // { - Greek Small Letter Pi 330 | L'\x2260', // | - Not Equal To 331 | L'\x00a3', // } - Pound Sign 332 | L'\x00b7', // ~ - Middle Dot 333 | }; 334 | 335 | #define FIRST_G1 '_' 336 | #define LAST_G1 '~' 337 | 338 | 339 | // color constants 340 | 341 | #define FOREGROUND_BLACK 0 342 | #define FOREGROUND_WHITE FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_BLUE 343 | 344 | #define BACKGROUND_BLACK 0 345 | #define BACKGROUND_WHITE BACKGROUND_RED|BACKGROUND_GREEN|BACKGROUND_BLUE 346 | 347 | const BYTE foregroundcolor[8] = 348 | { 349 | FOREGROUND_BLACK, // black foreground 350 | FOREGROUND_RED, // red foreground 351 | FOREGROUND_GREEN, // green foreground 352 | FOREGROUND_RED | FOREGROUND_GREEN, // yellow foreground 353 | FOREGROUND_BLUE, // blue foreground 354 | FOREGROUND_BLUE | FOREGROUND_RED, // magenta foreground 355 | FOREGROUND_BLUE | FOREGROUND_GREEN, // cyan foreground 356 | FOREGROUND_WHITE // white foreground 357 | }; 358 | 359 | const BYTE backgroundcolor[8] = 360 | { 361 | BACKGROUND_BLACK, // black background 362 | BACKGROUND_RED, // red background 363 | BACKGROUND_GREEN, // green background 364 | BACKGROUND_RED | BACKGROUND_GREEN, // yellow background 365 | BACKGROUND_BLUE, // blue background 366 | BACKGROUND_BLUE | BACKGROUND_RED, // magenta background 367 | BACKGROUND_BLUE | BACKGROUND_GREEN, // cyan background 368 | BACKGROUND_WHITE, // white background 369 | }; 370 | 371 | const BYTE attr2ansi[8] = // map console attribute to ANSI number 372 | { 373 | 0, // black 374 | 4, // blue 375 | 2, // green 376 | 6, // cyan 377 | 1, // red 378 | 5, // magenta 379 | 3, // yellow 380 | 7 // white 381 | }; 382 | 383 | GRM grm; 384 | 385 | // saved cursor position 386 | COORD SavePos; 387 | 388 | // ========== Print Buffer functions 389 | 390 | #define BUFFER_SIZE 2048 391 | 392 | int nCharInBuffer; 393 | WCHAR ChBuffer[BUFFER_SIZE]; 394 | 395 | //----------------------------------------------------------------------------- 396 | // FlushBuffer() 397 | // Writes the buffer to the console and empties it. 398 | //----------------------------------------------------------------------------- 399 | 400 | inline void FlushBuffer(void) 401 | { 402 | DWORD nWritten; 403 | if (nCharInBuffer <= 0) return; 404 | WriteConsoleW(hConOut, ChBuffer, nCharInBuffer, &nWritten, NULL); 405 | nCharInBuffer = 0; 406 | } 407 | 408 | //----------------------------------------------------------------------------- 409 | // PushBuffer( WCHAR c ) 410 | // Adds a character in the buffer. 411 | //----------------------------------------------------------------------------- 412 | 413 | inline void PushBuffer(WCHAR c) 414 | { 415 | if (shifted && c >= FIRST_G1 && c <= LAST_G1) 416 | c = G1[c - FIRST_G1]; 417 | ChBuffer[nCharInBuffer] = c; 418 | if (++nCharInBuffer == BUFFER_SIZE) 419 | FlushBuffer(); 420 | } 421 | 422 | //----------------------------------------------------------------------------- 423 | // SendSequence( LPCWSTR seq ) 424 | // Send the string to the input buffer. 425 | //----------------------------------------------------------------------------- 426 | 427 | inline void SendSequence(LPCWSTR seq) 428 | { 429 | DWORD out; 430 | INPUT_RECORD in; 431 | HANDLE hStdIn = GetStdHandle(STD_INPUT_HANDLE); 432 | 433 | in.EventType = KEY_EVENT; 434 | in.Event.KeyEvent.bKeyDown = TRUE; 435 | in.Event.KeyEvent.wRepeatCount = 1; 436 | in.Event.KeyEvent.wVirtualKeyCode = 0; 437 | in.Event.KeyEvent.wVirtualScanCode = 0; 438 | in.Event.KeyEvent.dwControlKeyState = 0; 439 | for (; *seq; ++seq) 440 | { 441 | in.Event.KeyEvent.uChar.UnicodeChar = *seq; 442 | WriteConsoleInput(hStdIn, &in, 1, &out); 443 | } 444 | } 445 | 446 | // ========== Print functions 447 | 448 | //----------------------------------------------------------------------------- 449 | // InterpretEscSeq() 450 | // Interprets the last escape sequence scanned by ParseAndPrintANSIString 451 | // prefix escape sequence prefix 452 | // es_argc escape sequence args count 453 | // es_argv[] escape sequence args array 454 | // suffix escape sequence suffix 455 | // 456 | // for instance, with \e[33;45;1m we have 457 | // prefix = '[', 458 | // es_argc = 3, es_argv[0] = 33, es_argv[1] = 45, es_argv[2] = 1 459 | // suffix = 'm' 460 | //----------------------------------------------------------------------------- 461 | 462 | inline void InterpretEscSeq(void) 463 | { 464 | WORD attribute; 465 | CONSOLE_SCREEN_BUFFER_INFO Info; 466 | CONSOLE_CURSOR_INFO CursInfo; 467 | DWORD len, NumberOfCharsWritten; 468 | COORD Pos; 469 | SMALL_RECT Rect; 470 | CHAR_INFO CharInfo; 471 | 472 | if (prefix == '[') 473 | { 474 | if (prefix2 == '?' && (suffix == 'h' || suffix == 'l')) 475 | { 476 | if (es_argc == 1 && es_argv[0] == 25) 477 | { 478 | GetConsoleCursorInfo(hConOut, &CursInfo); 479 | CursInfo.bVisible = (suffix == 'h'); 480 | SetConsoleCursorInfo(hConOut, &CursInfo); 481 | return; 482 | } 483 | } 484 | // Ignore any other \e[? or \e[> sequences. 485 | if (prefix2 != 0) 486 | return; 487 | 488 | GetConsoleScreenBufferInfo(hConOut, &Info); 489 | switch (suffix) 490 | { 491 | case 'm': 492 | if (es_argc == 0) es_argv[es_argc++] = 0; 493 | for (int i = 0; i < es_argc; i++) 494 | { 495 | if (30 <= es_argv[i] && es_argv[i] <= 37) 496 | grm.foreground = es_argv[i] - 30; 497 | else if (40 <= es_argv[i] && es_argv[i] <= 47) 498 | grm.background = es_argv[i] - 40; 499 | else switch (es_argv[i]) 500 | { 501 | case 0: 502 | case 39: 503 | case 49: 504 | { 505 | WCHAR def[4]; 506 | int a; 507 | *def = '7'; def[1] = '\0'; 508 | GetEnvironmentVariableW(L"ANSICON_DEF", def, lenof(def)); 509 | a = wcstol(def, NULL, 16); 510 | grm.reverse = FALSE; 511 | if (a < 0) 512 | { 513 | grm.reverse = TRUE; 514 | a = -a; 515 | } 516 | if (es_argv[i] != 49) 517 | grm.foreground = attr2ansi[a & 7]; 518 | if (es_argv[i] != 39) 519 | grm.background = attr2ansi[(a >> 4) & 7]; 520 | if (es_argv[i] == 0) 521 | { 522 | if (es_argc == 1) 523 | { 524 | grm.bold = a & FOREGROUND_INTENSITY; 525 | grm.underline = a & BACKGROUND_INTENSITY; 526 | } 527 | else 528 | { 529 | grm.bold = 0; 530 | grm.underline = 0; 531 | } 532 | grm.rvideo = 0; 533 | grm.concealed = 0; 534 | } 535 | } 536 | break; 537 | 538 | case 1: grm.bold = FOREGROUND_INTENSITY; break; 539 | case 5: // blink 540 | case 4: grm.underline = BACKGROUND_INTENSITY; break; 541 | case 7: grm.rvideo = 1; break; 542 | case 8: grm.concealed = 1; break; 543 | case 21: // oops, this actually turns on double underline 544 | case 22: grm.bold = 0; break; 545 | case 25: 546 | case 24: grm.underline = 0; break; 547 | case 27: grm.rvideo = 0; break; 548 | case 28: grm.concealed = 0; break; 549 | } 550 | } 551 | if (grm.concealed) 552 | { 553 | if (grm.rvideo) 554 | { 555 | attribute = foregroundcolor[grm.foreground] 556 | | backgroundcolor[grm.foreground]; 557 | if (grm.bold) 558 | attribute |= FOREGROUND_INTENSITY | BACKGROUND_INTENSITY; 559 | } 560 | else 561 | { 562 | attribute = foregroundcolor[grm.background] 563 | | backgroundcolor[grm.background]; 564 | if (grm.underline) 565 | attribute |= FOREGROUND_INTENSITY | BACKGROUND_INTENSITY; 566 | } 567 | } 568 | else if (grm.rvideo) 569 | { 570 | attribute = foregroundcolor[grm.background] 571 | | backgroundcolor[grm.foreground]; 572 | if (grm.bold) 573 | attribute |= BACKGROUND_INTENSITY; 574 | if (grm.underline) 575 | attribute |= FOREGROUND_INTENSITY; 576 | } 577 | else 578 | attribute = foregroundcolor[grm.foreground] | grm.bold 579 | | backgroundcolor[grm.background] | grm.underline; 580 | if (grm.reverse) 581 | attribute = ((attribute >> 4) & 15) | ((attribute & 15) << 4); 582 | SetConsoleTextAttribute(hConOut, attribute); 583 | return; 584 | 585 | case 'J': 586 | if (es_argc == 0) es_argv[es_argc++] = 0; // ESC[J == ESC[0J 587 | if (es_argc != 1) return; 588 | switch (es_argv[0]) 589 | { 590 | case 0: // ESC[0J erase from cursor to end of display 591 | len = (Info.dwSize.Y - Info.dwCursorPosition.Y - 1) * Info.dwSize.X 592 | + Info.dwSize.X - Info.dwCursorPosition.X - 1; 593 | FillConsoleOutputCharacter(hConOut, ' ', len, 594 | Info.dwCursorPosition, 595 | &NumberOfCharsWritten); 596 | FillConsoleOutputAttribute(hConOut, Info.wAttributes, len, 597 | Info.dwCursorPosition, 598 | &NumberOfCharsWritten); 599 | return; 600 | 601 | case 1: // ESC[1J erase from start to cursor. 602 | Pos.X = 0; 603 | Pos.Y = 0; 604 | len = Info.dwCursorPosition.Y * Info.dwSize.X 605 | + Info.dwCursorPosition.X + 1; 606 | FillConsoleOutputCharacter(hConOut, ' ', len, Pos, 607 | &NumberOfCharsWritten); 608 | FillConsoleOutputAttribute(hConOut, Info.wAttributes, len, Pos, 609 | &NumberOfCharsWritten); 610 | return; 611 | 612 | case 2: // ESC[2J Clear screen and home cursor 613 | Pos.X = 0; 614 | Pos.Y = 0; 615 | len = Info.dwSize.X * Info.dwSize.Y; 616 | FillConsoleOutputCharacter(hConOut, ' ', len, Pos, 617 | &NumberOfCharsWritten); 618 | FillConsoleOutputAttribute(hConOut, Info.wAttributes, len, Pos, 619 | &NumberOfCharsWritten); 620 | SetConsoleCursorPosition(hConOut, Pos); 621 | return; 622 | 623 | default: 624 | return; 625 | } 626 | 627 | case 'K': 628 | if (es_argc == 0) es_argv[es_argc++] = 0; // ESC[K == ESC[0K 629 | if (es_argc != 1) return; 630 | switch (es_argv[0]) 631 | { 632 | case 0: // ESC[0K Clear to end of line 633 | len = Info.dwSize.X - Info.dwCursorPosition.X + 1; 634 | FillConsoleOutputCharacter(hConOut, ' ', len, 635 | Info.dwCursorPosition, 636 | &NumberOfCharsWritten); 637 | FillConsoleOutputAttribute(hConOut, Info.wAttributes, len, 638 | Info.dwCursorPosition, 639 | &NumberOfCharsWritten); 640 | return; 641 | 642 | case 1: // ESC[1K Clear from start of line to cursor 643 | Pos.X = 0; 644 | Pos.Y = Info.dwCursorPosition.Y; 645 | FillConsoleOutputCharacter(hConOut, ' ', 646 | Info.dwCursorPosition.X + 1, Pos, 647 | &NumberOfCharsWritten); 648 | FillConsoleOutputAttribute(hConOut, Info.wAttributes, 649 | Info.dwCursorPosition.X + 1, Pos, 650 | &NumberOfCharsWritten); 651 | return; 652 | 653 | case 2: // ESC[2K Clear whole line. 654 | Pos.X = 0; 655 | Pos.Y = Info.dwCursorPosition.Y; 656 | FillConsoleOutputCharacter(hConOut, ' ', Info.dwSize.X, Pos, 657 | &NumberOfCharsWritten); 658 | FillConsoleOutputAttribute(hConOut, Info.wAttributes, 659 | Info.dwSize.X, Pos, 660 | &NumberOfCharsWritten); 661 | return; 662 | 663 | default: 664 | return; 665 | } 666 | 667 | case 'X': // ESC[#X Erase # characters. 668 | if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[X == ESC[1X 669 | if (es_argc != 1) return; 670 | FillConsoleOutputCharacter(hConOut, ' ', es_argv[0], 671 | Info.dwCursorPosition, 672 | &NumberOfCharsWritten); 673 | FillConsoleOutputAttribute(hConOut, Info.wAttributes, es_argv[0], 674 | Info.dwCursorPosition, 675 | &NumberOfCharsWritten); 676 | return; 677 | 678 | case 'L': // ESC[#L Insert # blank lines. 679 | if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[L == ESC[1L 680 | if (es_argc != 1) return; 681 | Rect.Left = 0; 682 | Rect.Top = Info.dwCursorPosition.Y; 683 | Rect.Right = Info.dwSize.X - 1; 684 | Rect.Bottom = Info.dwSize.Y - 1; 685 | Pos.X = 0; 686 | Pos.Y = Info.dwCursorPosition.Y + es_argv[0]; 687 | CharInfo.Char.UnicodeChar = ' '; 688 | CharInfo.Attributes = Info.wAttributes; 689 | ScrollConsoleScreenBuffer(hConOut, &Rect, NULL, Pos, &CharInfo); 690 | return; 691 | 692 | case 'M': // ESC[#M Delete # lines. 693 | if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[M == ESC[1M 694 | if (es_argc != 1) return; 695 | if (es_argv[0] > Info.dwSize.Y - Info.dwCursorPosition.Y) 696 | es_argv[0] = Info.dwSize.Y - Info.dwCursorPosition.Y; 697 | Rect.Left = 0; 698 | Rect.Top = Info.dwCursorPosition.Y + es_argv[0]; 699 | Rect.Right = Info.dwSize.X - 1; 700 | Rect.Bottom = Info.dwSize.Y - 1; 701 | Pos.X = 0; 702 | Pos.Y = Info.dwCursorPosition.Y; 703 | CharInfo.Char.UnicodeChar = ' '; 704 | CharInfo.Attributes = Info.wAttributes; 705 | ScrollConsoleScreenBuffer(hConOut, &Rect, NULL, Pos, &CharInfo); 706 | return; 707 | 708 | case 'P': // ESC[#P Delete # characters. 709 | if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[P == ESC[1P 710 | if (es_argc != 1) return; 711 | if (Info.dwCursorPosition.X + es_argv[0] > Info.dwSize.X - 1) 712 | es_argv[0] = Info.dwSize.X - Info.dwCursorPosition.X; 713 | Rect.Left = Info.dwCursorPosition.X + es_argv[0]; 714 | Rect.Top = Info.dwCursorPosition.Y; 715 | Rect.Right = Info.dwSize.X - 1; 716 | Rect.Bottom = Info.dwCursorPosition.Y; 717 | CharInfo.Char.UnicodeChar = ' '; 718 | CharInfo.Attributes = Info.wAttributes; 719 | ScrollConsoleScreenBuffer(hConOut, &Rect, NULL, Info.dwCursorPosition, 720 | &CharInfo); 721 | return; 722 | 723 | case '@': // ESC[#@ Insert # blank characters. 724 | if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[@ == ESC[1@ 725 | if (es_argc != 1) return; 726 | if (Info.dwCursorPosition.X + es_argv[0] > Info.dwSize.X - 1) 727 | es_argv[0] = Info.dwSize.X - Info.dwCursorPosition.X; 728 | Rect.Left = Info.dwCursorPosition.X; 729 | Rect.Top = Info.dwCursorPosition.Y; 730 | Rect.Right = Info.dwSize.X - 1 - es_argv[0]; 731 | Rect.Bottom = Info.dwCursorPosition.Y; 732 | Pos.X = Info.dwCursorPosition.X + es_argv[0]; 733 | Pos.Y = Info.dwCursorPosition.Y; 734 | CharInfo.Char.UnicodeChar = ' '; 735 | CharInfo.Attributes = Info.wAttributes; 736 | ScrollConsoleScreenBuffer(hConOut, &Rect, NULL, Pos, &CharInfo); 737 | return; 738 | 739 | case 'k': // ESC[#k 740 | case 'A': // ESC[#A Moves cursor up # lines 741 | if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[A == ESC[1A 742 | if (es_argc != 1) return; 743 | Pos.Y = Info.dwCursorPosition.Y - es_argv[0]; 744 | if (Pos.Y < 0) Pos.Y = 0; 745 | Pos.X = Info.dwCursorPosition.X; 746 | SetConsoleCursorPosition(hConOut, Pos); 747 | return; 748 | 749 | case 'e': // ESC[#e 750 | case 'B': // ESC[#B Moves cursor down # lines 751 | if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[B == ESC[1B 752 | if (es_argc != 1) return; 753 | Pos.Y = Info.dwCursorPosition.Y + es_argv[0]; 754 | if (Pos.Y >= Info.dwSize.Y) Pos.Y = Info.dwSize.Y - 1; 755 | Pos.X = Info.dwCursorPosition.X; 756 | SetConsoleCursorPosition(hConOut, Pos); 757 | return; 758 | 759 | case 'a': // ESC[#a 760 | case 'C': // ESC[#C Moves cursor forward # spaces 761 | if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[C == ESC[1C 762 | if (es_argc != 1) return; 763 | Pos.X = Info.dwCursorPosition.X + es_argv[0]; 764 | if (Pos.X >= Info.dwSize.X) Pos.X = Info.dwSize.X - 1; 765 | Pos.Y = Info.dwCursorPosition.Y; 766 | SetConsoleCursorPosition(hConOut, Pos); 767 | return; 768 | 769 | case 'j': // ESC[#j 770 | case 'D': // ESC[#D Moves cursor back # spaces 771 | if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[D == ESC[1D 772 | if (es_argc != 1) return; 773 | Pos.X = Info.dwCursorPosition.X - es_argv[0]; 774 | if (Pos.X < 0) Pos.X = 0; 775 | Pos.Y = Info.dwCursorPosition.Y; 776 | SetConsoleCursorPosition(hConOut, Pos); 777 | return; 778 | 779 | case 'E': // ESC[#E Moves cursor down # lines, column 1. 780 | if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[E == ESC[1E 781 | if (es_argc != 1) return; 782 | Pos.Y = Info.dwCursorPosition.Y + es_argv[0]; 783 | if (Pos.Y >= Info.dwSize.Y) Pos.Y = Info.dwSize.Y - 1; 784 | Pos.X = 0; 785 | SetConsoleCursorPosition(hConOut, Pos); 786 | return; 787 | 788 | case 'F': // ESC[#F Moves cursor up # lines, column 1. 789 | if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[F == ESC[1F 790 | if (es_argc != 1) return; 791 | Pos.Y = Info.dwCursorPosition.Y - es_argv[0]; 792 | if (Pos.Y < 0) Pos.Y = 0; 793 | Pos.X = 0; 794 | SetConsoleCursorPosition(hConOut, Pos); 795 | return; 796 | 797 | case '`': // ESC[#` 798 | case 'G': // ESC[#G Moves cursor column # in current row. 799 | if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[G == ESC[1G 800 | if (es_argc != 1) return; 801 | Pos.X = es_argv[0] - 1; 802 | if (Pos.X >= Info.dwSize.X) Pos.X = Info.dwSize.X - 1; 803 | if (Pos.X < 0) Pos.X = 0; 804 | Pos.Y = Info.dwCursorPosition.Y; 805 | SetConsoleCursorPosition(hConOut, Pos); 806 | return; 807 | 808 | case 'd': // ESC[#d Moves cursor row #, current column. 809 | if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[d == ESC[1d 810 | if (es_argc != 1) return; 811 | Pos.Y = es_argv[0] - 1; 812 | if (Pos.Y < 0) Pos.Y = 0; 813 | if (Pos.Y >= Info.dwSize.Y) Pos.Y = Info.dwSize.Y - 1; 814 | SetConsoleCursorPosition(hConOut, Pos); 815 | return; 816 | 817 | case 'f': // ESC[#;#f 818 | case 'H': // ESC[#;#H Moves cursor to line #, column # 819 | if (es_argc == 0) 820 | es_argv[es_argc++] = 1; // ESC[H == ESC[1;1H 821 | if (es_argc == 1) 822 | es_argv[es_argc++] = 1; // ESC[#H == ESC[#;1H 823 | if (es_argc > 2) return; 824 | Pos.X = es_argv[1] - 1; 825 | if (Pos.X < 0) Pos.X = 0; 826 | if (Pos.X >= Info.dwSize.X) Pos.X = Info.dwSize.X - 1; 827 | Pos.Y = es_argv[0] - 1; 828 | if (Pos.Y < 0) Pos.Y = 0; 829 | if (Pos.Y >= Info.dwSize.Y) Pos.Y = Info.dwSize.Y - 1; 830 | SetConsoleCursorPosition(hConOut, Pos); 831 | return; 832 | 833 | case 's': // ESC[s Saves cursor position for recall later 834 | if (es_argc != 0) return; 835 | SavePos = Info.dwCursorPosition; 836 | return; 837 | 838 | case 'u': // ESC[u Return to saved cursor position 839 | if (es_argc != 0) return; 840 | SetConsoleCursorPosition(hConOut, SavePos); 841 | return; 842 | 843 | case 'n': // ESC[#n Device status report 844 | if (es_argc != 1) return; // ESC[n == ESC[0n -> ignored 845 | switch (es_argv[0]) 846 | { 847 | case 5: // ESC[5n Report status 848 | SendSequence(L"\33[0n"); // "OK" 849 | return; 850 | 851 | case 6: // ESC[6n Report cursor position 852 | { 853 | WCHAR buf[32]; 854 | swprintf(buf, 32, L"\33[%d;%dR", Info.dwCursorPosition.Y + 1, 855 | Info.dwCursorPosition.X + 1); 856 | SendSequence(buf); 857 | } 858 | return; 859 | 860 | default: 861 | return; 862 | } 863 | 864 | case 't': // ESC[#t Window manipulation 865 | if (es_argc != 1) return; 866 | if (es_argv[0] == 21) // ESC[21t Report xterm window's title 867 | { 868 | WCHAR buf[MAX_PATH * 2]; 869 | len = GetConsoleTitleW(buf + 3, lenof(buf) - 3 - 2); 870 | // Too bad if it's too big or fails. 871 | buf[0] = ESC; 872 | buf[1] = ']'; 873 | buf[2] = 'l'; 874 | buf[3 + len] = ESC; 875 | buf[3 + len + 1] = '\\'; 876 | buf[3 + len + 2] = '\0'; 877 | SendSequence(buf); 878 | } 879 | return; 880 | 881 | default: 882 | return; 883 | } 884 | } 885 | else // (prefix == ']') 886 | { 887 | // Ignore any \e]? or \e]> sequences. 888 | if (prefix2 != 0) 889 | return; 890 | 891 | if (es_argc == 1 && es_argv[0] == 0) // ESC]0;titleST 892 | { 893 | SetConsoleTitleW(Pt_arg); 894 | } 895 | } 896 | } 897 | 898 | //----------------------------------------------------------------------------- 899 | // ParseAndPrintANSIString(hDev, lpBuffer, nNumberOfBytesToWrite) 900 | // Parses the string lpBuffer, interprets the escapes sequences and prints the 901 | // characters in the device hDev (console). 902 | // The lexer is a three states automata. 903 | // If the number of arguments es_argc > MAX_ARG, only the MAX_ARG-1 firsts and 904 | // the last arguments are processed (no es_argv[] overflow). 905 | //----------------------------------------------------------------------------- 906 | 907 | inline BOOL ParseAndPrintANSIString(HANDLE hDev, LPCVOID lpBuffer, DWORD nNumberOfBytesToWrite, LPDWORD lpNumberOfBytesWritten) 908 | { 909 | DWORD i; 910 | LPCSTR s; 911 | 912 | if (hDev != hConOut) // reinit if device has changed 913 | { 914 | hConOut = hDev; 915 | state = 1; 916 | shifted = FALSE; 917 | } 918 | for (i = nNumberOfBytesToWrite, s = (LPCSTR)lpBuffer; i > 0; i--, s++) 919 | { 920 | if (state == 1) 921 | { 922 | if (*s == ESC) state = 2; 923 | else if (*s == SO) shifted = TRUE; 924 | else if (*s == SI) shifted = FALSE; 925 | else PushBuffer(*s); 926 | } 927 | else if (state == 2) 928 | { 929 | if (*s == ESC); // \e\e...\e == \e 930 | else if ((*s == '[') || (*s == ']')) 931 | { 932 | FlushBuffer(); 933 | prefix = *s; 934 | prefix2 = 0; 935 | state = 3; 936 | Pt_len = 0; 937 | *Pt_arg = '\0'; 938 | } 939 | else if (*s == ')' || *s == '(') state = 6; 940 | else state = 1; 941 | } 942 | else if (state == 3) 943 | { 944 | if (is_digit(*s)) 945 | { 946 | es_argc = 0; 947 | es_argv[0] = *s - '0'; 948 | state = 4; 949 | } 950 | else if (*s == ';') 951 | { 952 | es_argc = 1; 953 | es_argv[0] = 0; 954 | es_argv[1] = 0; 955 | state = 4; 956 | } 957 | else if (*s == '?' || *s == '>') 958 | { 959 | prefix2 = *s; 960 | } 961 | else 962 | { 963 | es_argc = 0; 964 | suffix = *s; 965 | InterpretEscSeq(); 966 | state = 1; 967 | } 968 | } 969 | else if (state == 4) 970 | { 971 | if (is_digit(*s)) 972 | { 973 | es_argv[es_argc] = 10 * es_argv[es_argc] + (*s - '0'); 974 | } 975 | else if (*s == ';') 976 | { 977 | if (es_argc < MAX_ARG - 1) es_argc++; 978 | es_argv[es_argc] = 0; 979 | if (prefix == ']') 980 | state = 5; 981 | } 982 | else 983 | { 984 | es_argc++; 985 | suffix = *s; 986 | InterpretEscSeq(); 987 | state = 1; 988 | } 989 | } 990 | else if (state == 5) 991 | { 992 | if (*s == BEL) 993 | { 994 | Pt_arg[Pt_len] = '\0'; 995 | InterpretEscSeq(); 996 | state = 1; 997 | } 998 | else if (*s == '\\' && Pt_len > 0 && Pt_arg[Pt_len - 1] == ESC) 999 | { 1000 | Pt_arg[--Pt_len] = '\0'; 1001 | InterpretEscSeq(); 1002 | state = 1; 1003 | } 1004 | else if (Pt_len < lenof(Pt_arg) - 1) 1005 | Pt_arg[Pt_len++] = *s; 1006 | } 1007 | else if (state == 6) 1008 | { 1009 | // Ignore it (ESC ) 0 is implicit; nothing else is supported). 1010 | state = 1; 1011 | } 1012 | } 1013 | FlushBuffer(); 1014 | if (lpNumberOfBytesWritten != NULL) 1015 | *lpNumberOfBytesWritten = nNumberOfBytesToWrite - i; 1016 | return (i == 0); 1017 | } 1018 | 1019 | } // namespace ansi 1020 | 1021 | HANDLE hOut; 1022 | HANDLE hIn; 1023 | DWORD consolemodeIn = 0; 1024 | 1025 | inline int win32read(int *c) { 1026 | DWORD foo; 1027 | INPUT_RECORD b; 1028 | KEY_EVENT_RECORD e; 1029 | BOOL altgr; 1030 | 1031 | while (1) { 1032 | if (!ReadConsoleInput(hIn, &b, 1, &foo)) return 0; 1033 | if (!foo) return 0; 1034 | 1035 | if (b.EventType == KEY_EVENT && b.Event.KeyEvent.bKeyDown) { 1036 | 1037 | e = b.Event.KeyEvent; 1038 | *c = b.Event.KeyEvent.uChar.AsciiChar; 1039 | 1040 | altgr = e.dwControlKeyState & (LEFT_CTRL_PRESSED | RIGHT_ALT_PRESSED); 1041 | 1042 | if (e.dwControlKeyState & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED) && !altgr) { 1043 | 1044 | /* Ctrl+Key */ 1045 | switch (*c) { 1046 | case 'D': 1047 | *c = 4; 1048 | return 1; 1049 | case 'C': 1050 | *c = 3; 1051 | return 1; 1052 | case 'H': 1053 | *c = 8; 1054 | return 1; 1055 | case 'T': 1056 | *c = 20; 1057 | return 1; 1058 | case 'B': /* ctrl-b, left_arrow */ 1059 | *c = 2; 1060 | return 1; 1061 | case 'F': /* ctrl-f right_arrow*/ 1062 | *c = 6; 1063 | return 1; 1064 | case 'P': /* ctrl-p up_arrow*/ 1065 | *c = 16; 1066 | return 1; 1067 | case 'N': /* ctrl-n down_arrow*/ 1068 | *c = 14; 1069 | return 1; 1070 | case 'U': /* Ctrl+u, delete the whole line. */ 1071 | *c = 21; 1072 | return 1; 1073 | case 'K': /* Ctrl+k, delete from current to end of line. */ 1074 | *c = 11; 1075 | return 1; 1076 | case 'A': /* Ctrl+a, go to the start of the line */ 1077 | *c = 1; 1078 | return 1; 1079 | case 'E': /* ctrl+e, go to the end of the line */ 1080 | *c = 5; 1081 | return 1; 1082 | } 1083 | 1084 | /* Other Ctrl+KEYs ignored */ 1085 | } else { 1086 | 1087 | switch (e.wVirtualKeyCode) { 1088 | 1089 | case VK_ESCAPE: /* ignore - send ctrl-c, will return -1 */ 1090 | *c = 3; 1091 | return 1; 1092 | case VK_RETURN: /* enter */ 1093 | *c = 13; 1094 | return 1; 1095 | case VK_LEFT: /* left */ 1096 | *c = 2; 1097 | return 1; 1098 | case VK_RIGHT: /* right */ 1099 | *c = 6; 1100 | return 1; 1101 | case VK_UP: /* up */ 1102 | *c = 16; 1103 | return 1; 1104 | case VK_DOWN: /* down */ 1105 | *c = 14; 1106 | return 1; 1107 | case VK_HOME: 1108 | *c = 1; 1109 | return 1; 1110 | case VK_END: 1111 | *c = 5; 1112 | return 1; 1113 | case VK_BACK: 1114 | *c = 8; 1115 | return 1; 1116 | case VK_DELETE: 1117 | *c = 4; /* same as Ctrl+D above */ 1118 | return 1; 1119 | default: 1120 | if (*c) return 1; 1121 | } 1122 | } 1123 | } 1124 | } 1125 | 1126 | return -1; /* Makes compiler happy */ 1127 | } 1128 | 1129 | inline int win32_write(int fd, const void *buffer, unsigned int count) { 1130 | if (fd == _fileno(stdout)) { 1131 | DWORD bytesWritten = 0; 1132 | if (FALSE != ansi::ParseAndPrintANSIString(GetStdHandle(STD_OUTPUT_HANDLE), buffer, (DWORD)count, &bytesWritten)) { 1133 | return (int)bytesWritten; 1134 | } else { 1135 | errno = GetLastError(); 1136 | return 0; 1137 | } 1138 | } else if (fd == _fileno(stderr)) { 1139 | DWORD bytesWritten = 0; 1140 | if (FALSE != ansi::ParseAndPrintANSIString(GetStdHandle(STD_ERROR_HANDLE), buffer, (DWORD)count, &bytesWritten)) { 1141 | return (int)bytesWritten; 1142 | } else { 1143 | errno = GetLastError(); 1144 | return 0; 1145 | } 1146 | } else { 1147 | return _write(fd, buffer, count); 1148 | } 1149 | } 1150 | #endif // _WIN32 1151 | 1152 | #ifndef _WIN32 1153 | static struct termios orig_termios; /* In order to restore at exit.*/ 1154 | #endif 1155 | static bool rawmode = false; /* For atexit() function to check if restore is needed*/ 1156 | static bool atexit_registered = false; /* Register atexit just 1 time. */ 1157 | 1158 | enum KEY_ACTION { 1159 | KEY_NULL = 0, /* NULL */ 1160 | CTRL_A = 1, /* Ctrl+a */ 1161 | CTRL_B = 2, /* Ctrl-b */ 1162 | CTRL_C = 3, /* Ctrl-c */ 1163 | CTRL_D = 4, /* Ctrl-d */ 1164 | CTRL_E = 5, /* Ctrl-e */ 1165 | CTRL_F = 6, /* Ctrl-f */ 1166 | CTRL_H = 8, /* Ctrl-h */ 1167 | TAB = 9, /* Tab */ 1168 | CTRL_K = 11, /* Ctrl+k */ 1169 | CTRL_L = 12, /* Ctrl+l */ 1170 | ENTER = 13, /* Enter */ 1171 | CTRL_N = 14, /* Ctrl-n */ 1172 | CTRL_P = 16, /* Ctrl-p */ 1173 | CTRL_T = 20, /* Ctrl-t */ 1174 | CTRL_U = 21, /* Ctrl+u */ 1175 | CTRL_W = 23, /* Ctrl+w */ 1176 | ESC = 27, /* Escape */ 1177 | BACKSPACE = 127 /* Backspace */ 1178 | }; 1179 | 1180 | void linenoiseAtExit(void); 1181 | bool AddHistory(const char *line); 1182 | 1183 | /* ============================ UTF8 utilities ============================== */ 1184 | 1185 | static unsigned long unicodeWideCharTable[][2] = { 1186 | { 0x1100, 0x115F }, { 0x2329, 0x232A }, { 0x2E80, 0x2E99, }, { 0x2E9B, 0x2EF3, }, 1187 | { 0x2F00, 0x2FD5, }, { 0x2FF0, 0x2FFB, }, { 0x3000, 0x303E, }, { 0x3041, 0x3096, }, 1188 | { 0x3099, 0x30FF, }, { 0x3105, 0x312D, }, { 0x3131, 0x318E, }, { 0x3190, 0x31BA, }, 1189 | { 0x31C0, 0x31E3, }, { 0x31F0, 0x321E, }, { 0x3220, 0x3247, }, { 0x3250, 0x4DBF, }, 1190 | { 0x4E00, 0xA48C, }, { 0xA490, 0xA4C6, }, { 0xA960, 0xA97C, }, { 0xAC00, 0xD7A3, }, 1191 | { 0xF900, 0xFAFF, }, { 0xFE10, 0xFE19, }, { 0xFE30, 0xFE52, }, { 0xFE54, 0xFE66, }, 1192 | { 0xFE68, 0xFE6B, }, { 0xFF01, 0xFFE6, }, 1193 | { 0x1B000, 0x1B001, }, { 0x1F200, 0x1F202, }, { 0x1F210, 0x1F23A, }, 1194 | { 0x1F240, 0x1F248, }, { 0x1F250, 0x1F251, }, { 0x20000, 0x3FFFD, }, 1195 | }; 1196 | 1197 | static int unicodeWideCharTableSize = sizeof(unicodeWideCharTable) / sizeof(unicodeWideCharTable[0]); 1198 | 1199 | static int unicodeIsWideChar(unsigned long cp) 1200 | { 1201 | int i; 1202 | for (i = 0; i < unicodeWideCharTableSize; i++) { 1203 | if (unicodeWideCharTable[i][0] <= cp && cp <= unicodeWideCharTable[i][1]) { 1204 | return 1; 1205 | } 1206 | } 1207 | return 0; 1208 | } 1209 | 1210 | static unsigned long unicodeCombiningCharTable[] = { 1211 | 0x0300,0x0301,0x0302,0x0303,0x0304,0x0305,0x0306,0x0307, 1212 | 0x0308,0x0309,0x030A,0x030B,0x030C,0x030D,0x030E,0x030F, 1213 | 0x0310,0x0311,0x0312,0x0313,0x0314,0x0315,0x0316,0x0317, 1214 | 0x0318,0x0319,0x031A,0x031B,0x031C,0x031D,0x031E,0x031F, 1215 | 0x0320,0x0321,0x0322,0x0323,0x0324,0x0325,0x0326,0x0327, 1216 | 0x0328,0x0329,0x032A,0x032B,0x032C,0x032D,0x032E,0x032F, 1217 | 0x0330,0x0331,0x0332,0x0333,0x0334,0x0335,0x0336,0x0337, 1218 | 0x0338,0x0339,0x033A,0x033B,0x033C,0x033D,0x033E,0x033F, 1219 | 0x0340,0x0341,0x0342,0x0343,0x0344,0x0345,0x0346,0x0347, 1220 | 0x0348,0x0349,0x034A,0x034B,0x034C,0x034D,0x034E,0x034F, 1221 | 0x0350,0x0351,0x0352,0x0353,0x0354,0x0355,0x0356,0x0357, 1222 | 0x0358,0x0359,0x035A,0x035B,0x035C,0x035D,0x035E,0x035F, 1223 | 0x0360,0x0361,0x0362,0x0363,0x0364,0x0365,0x0366,0x0367, 1224 | 0x0368,0x0369,0x036A,0x036B,0x036C,0x036D,0x036E,0x036F, 1225 | 0x0483,0x0484,0x0485,0x0486,0x0487,0x0591,0x0592,0x0593, 1226 | 0x0594,0x0595,0x0596,0x0597,0x0598,0x0599,0x059A,0x059B, 1227 | 0x059C,0x059D,0x059E,0x059F,0x05A0,0x05A1,0x05A2,0x05A3, 1228 | 0x05A4,0x05A5,0x05A6,0x05A7,0x05A8,0x05A9,0x05AA,0x05AB, 1229 | 0x05AC,0x05AD,0x05AE,0x05AF,0x05B0,0x05B1,0x05B2,0x05B3, 1230 | 0x05B4,0x05B5,0x05B6,0x05B7,0x05B8,0x05B9,0x05BA,0x05BB, 1231 | 0x05BC,0x05BD,0x05BF,0x05C1,0x05C2,0x05C4,0x05C5,0x05C7, 1232 | 0x0610,0x0611,0x0612,0x0613,0x0614,0x0615,0x0616,0x0617, 1233 | 0x0618,0x0619,0x061A,0x064B,0x064C,0x064D,0x064E,0x064F, 1234 | 0x0650,0x0651,0x0652,0x0653,0x0654,0x0655,0x0656,0x0657, 1235 | 0x0658,0x0659,0x065A,0x065B,0x065C,0x065D,0x065E,0x065F, 1236 | 0x0670,0x06D6,0x06D7,0x06D8,0x06D9,0x06DA,0x06DB,0x06DC, 1237 | 0x06DF,0x06E0,0x06E1,0x06E2,0x06E3,0x06E4,0x06E7,0x06E8, 1238 | 0x06EA,0x06EB,0x06EC,0x06ED,0x0711,0x0730,0x0731,0x0732, 1239 | 0x0733,0x0734,0x0735,0x0736,0x0737,0x0738,0x0739,0x073A, 1240 | 0x073B,0x073C,0x073D,0x073E,0x073F,0x0740,0x0741,0x0742, 1241 | 0x0743,0x0744,0x0745,0x0746,0x0747,0x0748,0x0749,0x074A, 1242 | 0x07A6,0x07A7,0x07A8,0x07A9,0x07AA,0x07AB,0x07AC,0x07AD, 1243 | 0x07AE,0x07AF,0x07B0,0x07EB,0x07EC,0x07ED,0x07EE,0x07EF, 1244 | 0x07F0,0x07F1,0x07F2,0x07F3,0x0816,0x0817,0x0818,0x0819, 1245 | 0x081B,0x081C,0x081D,0x081E,0x081F,0x0820,0x0821,0x0822, 1246 | 0x0823,0x0825,0x0826,0x0827,0x0829,0x082A,0x082B,0x082C, 1247 | 0x082D,0x0859,0x085A,0x085B,0x08E3,0x08E4,0x08E5,0x08E6, 1248 | 0x08E7,0x08E8,0x08E9,0x08EA,0x08EB,0x08EC,0x08ED,0x08EE, 1249 | 0x08EF,0x08F0,0x08F1,0x08F2,0x08F3,0x08F4,0x08F5,0x08F6, 1250 | 0x08F7,0x08F8,0x08F9,0x08FA,0x08FB,0x08FC,0x08FD,0x08FE, 1251 | 0x08FF,0x0900,0x0901,0x0902,0x093A,0x093C,0x0941,0x0942, 1252 | 0x0943,0x0944,0x0945,0x0946,0x0947,0x0948,0x094D,0x0951, 1253 | 0x0952,0x0953,0x0954,0x0955,0x0956,0x0957,0x0962,0x0963, 1254 | 0x0981,0x09BC,0x09C1,0x09C2,0x09C3,0x09C4,0x09CD,0x09E2, 1255 | 0x09E3,0x0A01,0x0A02,0x0A3C,0x0A41,0x0A42,0x0A47,0x0A48, 1256 | 0x0A4B,0x0A4C,0x0A4D,0x0A51,0x0A70,0x0A71,0x0A75,0x0A81, 1257 | 0x0A82,0x0ABC,0x0AC1,0x0AC2,0x0AC3,0x0AC4,0x0AC5,0x0AC7, 1258 | 0x0AC8,0x0ACD,0x0AE2,0x0AE3,0x0B01,0x0B3C,0x0B3F,0x0B41, 1259 | 0x0B42,0x0B43,0x0B44,0x0B4D,0x0B56,0x0B62,0x0B63,0x0B82, 1260 | 0x0BC0,0x0BCD,0x0C00,0x0C3E,0x0C3F,0x0C40,0x0C46,0x0C47, 1261 | 0x0C48,0x0C4A,0x0C4B,0x0C4C,0x0C4D,0x0C55,0x0C56,0x0C62, 1262 | 0x0C63,0x0C81,0x0CBC,0x0CBF,0x0CC6,0x0CCC,0x0CCD,0x0CE2, 1263 | 0x0CE3,0x0D01,0x0D41,0x0D42,0x0D43,0x0D44,0x0D4D,0x0D62, 1264 | 0x0D63,0x0DCA,0x0DD2,0x0DD3,0x0DD4,0x0DD6,0x0E31,0x0E34, 1265 | 0x0E35,0x0E36,0x0E37,0x0E38,0x0E39,0x0E3A,0x0E47,0x0E48, 1266 | 0x0E49,0x0E4A,0x0E4B,0x0E4C,0x0E4D,0x0E4E,0x0EB1,0x0EB4, 1267 | 0x0EB5,0x0EB6,0x0EB7,0x0EB8,0x0EB9,0x0EBB,0x0EBC,0x0EC8, 1268 | 0x0EC9,0x0ECA,0x0ECB,0x0ECC,0x0ECD,0x0F18,0x0F19,0x0F35, 1269 | 0x0F37,0x0F39,0x0F71,0x0F72,0x0F73,0x0F74,0x0F75,0x0F76, 1270 | 0x0F77,0x0F78,0x0F79,0x0F7A,0x0F7B,0x0F7C,0x0F7D,0x0F7E, 1271 | 0x0F80,0x0F81,0x0F82,0x0F83,0x0F84,0x0F86,0x0F87,0x0F8D, 1272 | 0x0F8E,0x0F8F,0x0F90,0x0F91,0x0F92,0x0F93,0x0F94,0x0F95, 1273 | 0x0F96,0x0F97,0x0F99,0x0F9A,0x0F9B,0x0F9C,0x0F9D,0x0F9E, 1274 | 0x0F9F,0x0FA0,0x0FA1,0x0FA2,0x0FA3,0x0FA4,0x0FA5,0x0FA6, 1275 | 0x0FA7,0x0FA8,0x0FA9,0x0FAA,0x0FAB,0x0FAC,0x0FAD,0x0FAE, 1276 | 0x0FAF,0x0FB0,0x0FB1,0x0FB2,0x0FB3,0x0FB4,0x0FB5,0x0FB6, 1277 | 0x0FB7,0x0FB8,0x0FB9,0x0FBA,0x0FBB,0x0FBC,0x0FC6,0x102D, 1278 | 0x102E,0x102F,0x1030,0x1032,0x1033,0x1034,0x1035,0x1036, 1279 | 0x1037,0x1039,0x103A,0x103D,0x103E,0x1058,0x1059,0x105E, 1280 | 0x105F,0x1060,0x1071,0x1072,0x1073,0x1074,0x1082,0x1085, 1281 | 0x1086,0x108D,0x109D,0x135D,0x135E,0x135F,0x1712,0x1713, 1282 | 0x1714,0x1732,0x1733,0x1734,0x1752,0x1753,0x1772,0x1773, 1283 | 0x17B4,0x17B5,0x17B7,0x17B8,0x17B9,0x17BA,0x17BB,0x17BC, 1284 | 0x17BD,0x17C6,0x17C9,0x17CA,0x17CB,0x17CC,0x17CD,0x17CE, 1285 | 0x17CF,0x17D0,0x17D1,0x17D2,0x17D3,0x17DD,0x180B,0x180C, 1286 | 0x180D,0x18A9,0x1920,0x1921,0x1922,0x1927,0x1928,0x1932, 1287 | 0x1939,0x193A,0x193B,0x1A17,0x1A18,0x1A1B,0x1A56,0x1A58, 1288 | 0x1A59,0x1A5A,0x1A5B,0x1A5C,0x1A5D,0x1A5E,0x1A60,0x1A62, 1289 | 0x1A65,0x1A66,0x1A67,0x1A68,0x1A69,0x1A6A,0x1A6B,0x1A6C, 1290 | 0x1A73,0x1A74,0x1A75,0x1A76,0x1A77,0x1A78,0x1A79,0x1A7A, 1291 | 0x1A7B,0x1A7C,0x1A7F,0x1AB0,0x1AB1,0x1AB2,0x1AB3,0x1AB4, 1292 | 0x1AB5,0x1AB6,0x1AB7,0x1AB8,0x1AB9,0x1ABA,0x1ABB,0x1ABC, 1293 | 0x1ABD,0x1B00,0x1B01,0x1B02,0x1B03,0x1B34,0x1B36,0x1B37, 1294 | 0x1B38,0x1B39,0x1B3A,0x1B3C,0x1B42,0x1B6B,0x1B6C,0x1B6D, 1295 | 0x1B6E,0x1B6F,0x1B70,0x1B71,0x1B72,0x1B73,0x1B80,0x1B81, 1296 | 0x1BA2,0x1BA3,0x1BA4,0x1BA5,0x1BA8,0x1BA9,0x1BAB,0x1BAC, 1297 | 0x1BAD,0x1BE6,0x1BE8,0x1BE9,0x1BED,0x1BEF,0x1BF0,0x1BF1, 1298 | 0x1C2C,0x1C2D,0x1C2E,0x1C2F,0x1C30,0x1C31,0x1C32,0x1C33, 1299 | 0x1C36,0x1C37,0x1CD0,0x1CD1,0x1CD2,0x1CD4,0x1CD5,0x1CD6, 1300 | 0x1CD7,0x1CD8,0x1CD9,0x1CDA,0x1CDB,0x1CDC,0x1CDD,0x1CDE, 1301 | 0x1CDF,0x1CE0,0x1CE2,0x1CE3,0x1CE4,0x1CE5,0x1CE6,0x1CE7, 1302 | 0x1CE8,0x1CED,0x1CF4,0x1CF8,0x1CF9,0x1DC0,0x1DC1,0x1DC2, 1303 | 0x1DC3,0x1DC4,0x1DC5,0x1DC6,0x1DC7,0x1DC8,0x1DC9,0x1DCA, 1304 | 0x1DCB,0x1DCC,0x1DCD,0x1DCE,0x1DCF,0x1DD0,0x1DD1,0x1DD2, 1305 | 0x1DD3,0x1DD4,0x1DD5,0x1DD6,0x1DD7,0x1DD8,0x1DD9,0x1DDA, 1306 | 0x1DDB,0x1DDC,0x1DDD,0x1DDE,0x1DDF,0x1DE0,0x1DE1,0x1DE2, 1307 | 0x1DE3,0x1DE4,0x1DE5,0x1DE6,0x1DE7,0x1DE8,0x1DE9,0x1DEA, 1308 | 0x1DEB,0x1DEC,0x1DED,0x1DEE,0x1DEF,0x1DF0,0x1DF1,0x1DF2, 1309 | 0x1DF3,0x1DF4,0x1DF5,0x1DFC,0x1DFD,0x1DFE,0x1DFF,0x20D0, 1310 | 0x20D1,0x20D2,0x20D3,0x20D4,0x20D5,0x20D6,0x20D7,0x20D8, 1311 | 0x20D9,0x20DA,0x20DB,0x20DC,0x20E1,0x20E5,0x20E6,0x20E7, 1312 | 0x20E8,0x20E9,0x20EA,0x20EB,0x20EC,0x20ED,0x20EE,0x20EF, 1313 | 0x20F0,0x2CEF,0x2CF0,0x2CF1,0x2D7F,0x2DE0,0x2DE1,0x2DE2, 1314 | 0x2DE3,0x2DE4,0x2DE5,0x2DE6,0x2DE7,0x2DE8,0x2DE9,0x2DEA, 1315 | 0x2DEB,0x2DEC,0x2DED,0x2DEE,0x2DEF,0x2DF0,0x2DF1,0x2DF2, 1316 | 0x2DF3,0x2DF4,0x2DF5,0x2DF6,0x2DF7,0x2DF8,0x2DF9,0x2DFA, 1317 | 0x2DFB,0x2DFC,0x2DFD,0x2DFE,0x2DFF,0x302A,0x302B,0x302C, 1318 | 0x302D,0x3099,0x309A,0xA66F,0xA674,0xA675,0xA676,0xA677, 1319 | 0xA678,0xA679,0xA67A,0xA67B,0xA67C,0xA67D,0xA69E,0xA69F, 1320 | 0xA6F0,0xA6F1,0xA802,0xA806,0xA80B,0xA825,0xA826,0xA8C4, 1321 | 0xA8E0,0xA8E1,0xA8E2,0xA8E3,0xA8E4,0xA8E5,0xA8E6,0xA8E7, 1322 | 0xA8E8,0xA8E9,0xA8EA,0xA8EB,0xA8EC,0xA8ED,0xA8EE,0xA8EF, 1323 | 0xA8F0,0xA8F1,0xA926,0xA927,0xA928,0xA929,0xA92A,0xA92B, 1324 | 0xA92C,0xA92D,0xA947,0xA948,0xA949,0xA94A,0xA94B,0xA94C, 1325 | 0xA94D,0xA94E,0xA94F,0xA950,0xA951,0xA980,0xA981,0xA982, 1326 | 0xA9B3,0xA9B6,0xA9B7,0xA9B8,0xA9B9,0xA9BC,0xA9E5,0xAA29, 1327 | 0xAA2A,0xAA2B,0xAA2C,0xAA2D,0xAA2E,0xAA31,0xAA32,0xAA35, 1328 | 0xAA36,0xAA43,0xAA4C,0xAA7C,0xAAB0,0xAAB2,0xAAB3,0xAAB4, 1329 | 0xAAB7,0xAAB8,0xAABE,0xAABF,0xAAC1,0xAAEC,0xAAED,0xAAF6, 1330 | 0xABE5,0xABE8,0xABED,0xFB1E,0xFE00,0xFE01,0xFE02,0xFE03, 1331 | 0xFE04,0xFE05,0xFE06,0xFE07,0xFE08,0xFE09,0xFE0A,0xFE0B, 1332 | 0xFE0C,0xFE0D,0xFE0E,0xFE0F,0xFE20,0xFE21,0xFE22,0xFE23, 1333 | 0xFE24,0xFE25,0xFE26,0xFE27,0xFE28,0xFE29,0xFE2A,0xFE2B, 1334 | 0xFE2C,0xFE2D,0xFE2E,0xFE2F, 1335 | 0x101FD,0x102E0,0x10376,0x10377,0x10378,0x10379,0x1037A,0x10A01, 1336 | 0x10A02,0x10A03,0x10A05,0x10A06,0x10A0C,0x10A0D,0x10A0E,0x10A0F, 1337 | 0x10A38,0x10A39,0x10A3A,0x10A3F,0x10AE5,0x10AE6,0x11001,0x11038, 1338 | 0x11039,0x1103A,0x1103B,0x1103C,0x1103D,0x1103E,0x1103F,0x11040, 1339 | 0x11041,0x11042,0x11043,0x11044,0x11045,0x11046,0x1107F,0x11080, 1340 | 0x11081,0x110B3,0x110B4,0x110B5,0x110B6,0x110B9,0x110BA,0x11100, 1341 | 0x11101,0x11102,0x11127,0x11128,0x11129,0x1112A,0x1112B,0x1112D, 1342 | 0x1112E,0x1112F,0x11130,0x11131,0x11132,0x11133,0x11134,0x11173, 1343 | 0x11180,0x11181,0x111B6,0x111B7,0x111B8,0x111B9,0x111BA,0x111BB, 1344 | 0x111BC,0x111BD,0x111BE,0x111CA,0x111CB,0x111CC,0x1122F,0x11230, 1345 | 0x11231,0x11234,0x11236,0x11237,0x112DF,0x112E3,0x112E4,0x112E5, 1346 | 0x112E6,0x112E7,0x112E8,0x112E9,0x112EA,0x11300,0x11301,0x1133C, 1347 | 0x11340,0x11366,0x11367,0x11368,0x11369,0x1136A,0x1136B,0x1136C, 1348 | 0x11370,0x11371,0x11372,0x11373,0x11374,0x114B3,0x114B4,0x114B5, 1349 | 0x114B6,0x114B7,0x114B8,0x114BA,0x114BF,0x114C0,0x114C2,0x114C3, 1350 | 0x115B2,0x115B3,0x115B4,0x115B5,0x115BC,0x115BD,0x115BF,0x115C0, 1351 | 0x115DC,0x115DD,0x11633,0x11634,0x11635,0x11636,0x11637,0x11638, 1352 | 0x11639,0x1163A,0x1163D,0x1163F,0x11640,0x116AB,0x116AD,0x116B0, 1353 | 0x116B1,0x116B2,0x116B3,0x116B4,0x116B5,0x116B7,0x1171D,0x1171E, 1354 | 0x1171F,0x11722,0x11723,0x11724,0x11725,0x11727,0x11728,0x11729, 1355 | 0x1172A,0x1172B,0x16AF0,0x16AF1,0x16AF2,0x16AF3,0x16AF4,0x16B30, 1356 | 0x16B31,0x16B32,0x16B33,0x16B34,0x16B35,0x16B36,0x16F8F,0x16F90, 1357 | 0x16F91,0x16F92,0x1BC9D,0x1BC9E,0x1D167,0x1D168,0x1D169,0x1D17B, 1358 | 0x1D17C,0x1D17D,0x1D17E,0x1D17F,0x1D180,0x1D181,0x1D182,0x1D185, 1359 | 0x1D186,0x1D187,0x1D188,0x1D189,0x1D18A,0x1D18B,0x1D1AA,0x1D1AB, 1360 | 0x1D1AC,0x1D1AD,0x1D242,0x1D243,0x1D244,0x1DA00,0x1DA01,0x1DA02, 1361 | 0x1DA03,0x1DA04,0x1DA05,0x1DA06,0x1DA07,0x1DA08,0x1DA09,0x1DA0A, 1362 | 0x1DA0B,0x1DA0C,0x1DA0D,0x1DA0E,0x1DA0F,0x1DA10,0x1DA11,0x1DA12, 1363 | 0x1DA13,0x1DA14,0x1DA15,0x1DA16,0x1DA17,0x1DA18,0x1DA19,0x1DA1A, 1364 | 0x1DA1B,0x1DA1C,0x1DA1D,0x1DA1E,0x1DA1F,0x1DA20,0x1DA21,0x1DA22, 1365 | 0x1DA23,0x1DA24,0x1DA25,0x1DA26,0x1DA27,0x1DA28,0x1DA29,0x1DA2A, 1366 | 0x1DA2B,0x1DA2C,0x1DA2D,0x1DA2E,0x1DA2F,0x1DA30,0x1DA31,0x1DA32, 1367 | 0x1DA33,0x1DA34,0x1DA35,0x1DA36,0x1DA3B,0x1DA3C,0x1DA3D,0x1DA3E, 1368 | 0x1DA3F,0x1DA40,0x1DA41,0x1DA42,0x1DA43,0x1DA44,0x1DA45,0x1DA46, 1369 | 0x1DA47,0x1DA48,0x1DA49,0x1DA4A,0x1DA4B,0x1DA4C,0x1DA4D,0x1DA4E, 1370 | 0x1DA4F,0x1DA50,0x1DA51,0x1DA52,0x1DA53,0x1DA54,0x1DA55,0x1DA56, 1371 | 0x1DA57,0x1DA58,0x1DA59,0x1DA5A,0x1DA5B,0x1DA5C,0x1DA5D,0x1DA5E, 1372 | 0x1DA5F,0x1DA60,0x1DA61,0x1DA62,0x1DA63,0x1DA64,0x1DA65,0x1DA66, 1373 | 0x1DA67,0x1DA68,0x1DA69,0x1DA6A,0x1DA6B,0x1DA6C,0x1DA75,0x1DA84, 1374 | 0x1DA9B,0x1DA9C,0x1DA9D,0x1DA9E,0x1DA9F,0x1DAA1,0x1DAA2,0x1DAA3, 1375 | 0x1DAA4,0x1DAA5,0x1DAA6,0x1DAA7,0x1DAA8,0x1DAA9,0x1DAAA,0x1DAAB, 1376 | 0x1DAAC,0x1DAAD,0x1DAAE,0x1DAAF,0x1E8D0,0x1E8D1,0x1E8D2,0x1E8D3, 1377 | 0x1E8D4,0x1E8D5,0x1E8D6,0xE0100,0xE0101,0xE0102,0xE0103,0xE0104, 1378 | 0xE0105,0xE0106,0xE0107,0xE0108,0xE0109,0xE010A,0xE010B,0xE010C, 1379 | 0xE010D,0xE010E,0xE010F,0xE0110,0xE0111,0xE0112,0xE0113,0xE0114, 1380 | 0xE0115,0xE0116,0xE0117,0xE0118,0xE0119,0xE011A,0xE011B,0xE011C, 1381 | 0xE011D,0xE011E,0xE011F,0xE0120,0xE0121,0xE0122,0xE0123,0xE0124, 1382 | 0xE0125,0xE0126,0xE0127,0xE0128,0xE0129,0xE012A,0xE012B,0xE012C, 1383 | 0xE012D,0xE012E,0xE012F,0xE0130,0xE0131,0xE0132,0xE0133,0xE0134, 1384 | 0xE0135,0xE0136,0xE0137,0xE0138,0xE0139,0xE013A,0xE013B,0xE013C, 1385 | 0xE013D,0xE013E,0xE013F,0xE0140,0xE0141,0xE0142,0xE0143,0xE0144, 1386 | 0xE0145,0xE0146,0xE0147,0xE0148,0xE0149,0xE014A,0xE014B,0xE014C, 1387 | 0xE014D,0xE014E,0xE014F,0xE0150,0xE0151,0xE0152,0xE0153,0xE0154, 1388 | 0xE0155,0xE0156,0xE0157,0xE0158,0xE0159,0xE015A,0xE015B,0xE015C, 1389 | 0xE015D,0xE015E,0xE015F,0xE0160,0xE0161,0xE0162,0xE0163,0xE0164, 1390 | 0xE0165,0xE0166,0xE0167,0xE0168,0xE0169,0xE016A,0xE016B,0xE016C, 1391 | 0xE016D,0xE016E,0xE016F,0xE0170,0xE0171,0xE0172,0xE0173,0xE0174, 1392 | 0xE0175,0xE0176,0xE0177,0xE0178,0xE0179,0xE017A,0xE017B,0xE017C, 1393 | 0xE017D,0xE017E,0xE017F,0xE0180,0xE0181,0xE0182,0xE0183,0xE0184, 1394 | 0xE0185,0xE0186,0xE0187,0xE0188,0xE0189,0xE018A,0xE018B,0xE018C, 1395 | 0xE018D,0xE018E,0xE018F,0xE0190,0xE0191,0xE0192,0xE0193,0xE0194, 1396 | 0xE0195,0xE0196,0xE0197,0xE0198,0xE0199,0xE019A,0xE019B,0xE019C, 1397 | 0xE019D,0xE019E,0xE019F,0xE01A0,0xE01A1,0xE01A2,0xE01A3,0xE01A4, 1398 | 0xE01A5,0xE01A6,0xE01A7,0xE01A8,0xE01A9,0xE01AA,0xE01AB,0xE01AC, 1399 | 0xE01AD,0xE01AE,0xE01AF,0xE01B0,0xE01B1,0xE01B2,0xE01B3,0xE01B4, 1400 | 0xE01B5,0xE01B6,0xE01B7,0xE01B8,0xE01B9,0xE01BA,0xE01BB,0xE01BC, 1401 | 0xE01BD,0xE01BE,0xE01BF,0xE01C0,0xE01C1,0xE01C2,0xE01C3,0xE01C4, 1402 | 0xE01C5,0xE01C6,0xE01C7,0xE01C8,0xE01C9,0xE01CA,0xE01CB,0xE01CC, 1403 | 0xE01CD,0xE01CE,0xE01CF,0xE01D0,0xE01D1,0xE01D2,0xE01D3,0xE01D4, 1404 | 0xE01D5,0xE01D6,0xE01D7,0xE01D8,0xE01D9,0xE01DA,0xE01DB,0xE01DC, 1405 | 0xE01DD,0xE01DE,0xE01DF,0xE01E0,0xE01E1,0xE01E2,0xE01E3,0xE01E4, 1406 | 0xE01E5,0xE01E6,0xE01E7,0xE01E8,0xE01E9,0xE01EA,0xE01EB,0xE01EC, 1407 | 0xE01ED,0xE01EE,0xE01EF, 1408 | }; 1409 | 1410 | static int unicodeCombiningCharTableSize = sizeof(unicodeCombiningCharTable) / sizeof(unicodeCombiningCharTable[0]); 1411 | 1412 | inline int unicodeIsCombiningChar(unsigned long cp) 1413 | { 1414 | int i; 1415 | for (i = 0; i < unicodeCombiningCharTableSize; i++) { 1416 | if (unicodeCombiningCharTable[i] == cp) { 1417 | return 1; 1418 | } 1419 | } 1420 | return 0; 1421 | } 1422 | 1423 | /* Get length of previous UTF8 character 1424 | */ 1425 | inline int unicodePrevUTF8CharLen(char* buf, int pos) 1426 | { 1427 | int end = pos--; 1428 | while (pos >= 0 && ((unsigned char)buf[pos] & 0xC0) == 0x80) { 1429 | pos--; 1430 | } 1431 | return end - pos; 1432 | } 1433 | 1434 | /* Get length of previous UTF8 character 1435 | */ 1436 | inline int unicodeUTF8CharLen(char* buf, int buf_len, int pos) 1437 | { 1438 | if (pos == buf_len) { return 0; } 1439 | unsigned char ch = buf[pos]; 1440 | if (ch < 0x80) { return 1; } 1441 | else if (ch < 0xE0) { return 2; } 1442 | else if (ch < 0xF0) { return 3; } 1443 | else { return 4; } 1444 | } 1445 | 1446 | /* Convert UTF8 to Unicode code point 1447 | */ 1448 | inline int unicodeUTF8CharToCodePoint( 1449 | const char* buf, 1450 | int len, 1451 | int* cp) 1452 | { 1453 | if (len) { 1454 | unsigned char byte = buf[0]; 1455 | if ((byte & 0x80) == 0) { 1456 | *cp = byte; 1457 | return 1; 1458 | } else if ((byte & 0xE0) == 0xC0) { 1459 | if (len >= 2) { 1460 | *cp = (((unsigned long)(buf[0] & 0x1F)) << 6) | 1461 | ((unsigned long)(buf[1] & 0x3F)); 1462 | return 2; 1463 | } 1464 | } else if ((byte & 0xF0) == 0xE0) { 1465 | if (len >= 3) { 1466 | *cp = (((unsigned long)(buf[0] & 0x0F)) << 12) | 1467 | (((unsigned long)(buf[1] & 0x3F)) << 6) | 1468 | ((unsigned long)(buf[2] & 0x3F)); 1469 | return 3; 1470 | } 1471 | } else if ((byte & 0xF8) == 0xF0) { 1472 | if (len >= 4) { 1473 | *cp = (((unsigned long)(buf[0] & 0x07)) << 18) | 1474 | (((unsigned long)(buf[1] & 0x3F)) << 12) | 1475 | (((unsigned long)(buf[2] & 0x3F)) << 6) | 1476 | ((unsigned long)(buf[3] & 0x3F)); 1477 | return 4; 1478 | } 1479 | } 1480 | } 1481 | return 0; 1482 | } 1483 | 1484 | /* Get length of grapheme 1485 | */ 1486 | inline int unicodeGraphemeLen(char* buf, int buf_len, int pos) 1487 | { 1488 | if (pos == buf_len) { 1489 | return 0; 1490 | } 1491 | int beg = pos; 1492 | pos += unicodeUTF8CharLen(buf, buf_len, pos); 1493 | while (pos < buf_len) { 1494 | int len = unicodeUTF8CharLen(buf, buf_len, pos); 1495 | int cp = 0; 1496 | unicodeUTF8CharToCodePoint(buf + pos, len, &cp); 1497 | if (!unicodeIsCombiningChar(cp)) { 1498 | return pos - beg; 1499 | } 1500 | pos += len; 1501 | } 1502 | return pos - beg; 1503 | } 1504 | 1505 | /* Get length of previous grapheme 1506 | */ 1507 | inline int unicodePrevGraphemeLen(char* buf, int pos) 1508 | { 1509 | if (pos == 0) { 1510 | return 0; 1511 | } 1512 | int end = pos; 1513 | while (pos > 0) { 1514 | int len = unicodePrevUTF8CharLen(buf, pos); 1515 | pos -= len; 1516 | int cp = 0; 1517 | unicodeUTF8CharToCodePoint(buf + pos, len, &cp); 1518 | if (!unicodeIsCombiningChar(cp)) { 1519 | return end - pos; 1520 | } 1521 | } 1522 | return 0; 1523 | } 1524 | 1525 | inline int isAnsiEscape(const char* buf, int buf_len, int* len) 1526 | { 1527 | if (buf_len > 2 && !memcmp("\033[", buf, 2)) { 1528 | int off = 2; 1529 | while (off < buf_len) { 1530 | switch (buf[off++]) { 1531 | case 'A': case 'B': case 'C': case 'D': 1532 | case 'E': case 'F': case 'G': case 'H': 1533 | case 'J': case 'K': case 'S': case 'T': 1534 | case 'f': case 'm': 1535 | *len = off; 1536 | return 1; 1537 | } 1538 | } 1539 | } 1540 | return 0; 1541 | } 1542 | 1543 | /* Get column position for the single line mode. 1544 | */ 1545 | inline int unicodeColumnPos(const char* buf, int buf_len) 1546 | { 1547 | int ret = 0; 1548 | 1549 | int off = 0; 1550 | while (off < buf_len) { 1551 | int len; 1552 | if (isAnsiEscape(buf + off, buf_len - off, &len)) { 1553 | off += len; 1554 | continue; 1555 | } 1556 | 1557 | int cp = 0; 1558 | len = unicodeUTF8CharToCodePoint(buf + off, buf_len - off, &cp); 1559 | 1560 | if (!unicodeIsCombiningChar(cp)) { 1561 | ret += unicodeIsWideChar(cp) ? 2 : 1; 1562 | } 1563 | 1564 | off += len; 1565 | } 1566 | 1567 | return ret; 1568 | } 1569 | 1570 | /* Get column position for the multi line mode. 1571 | */ 1572 | inline int unicodeColumnPosForMultiLine(char* buf, int buf_len, int pos, int cols, int ini_pos) 1573 | { 1574 | int ret = 0; 1575 | int colwid = ini_pos; 1576 | 1577 | int off = 0; 1578 | while (off < buf_len) { 1579 | int cp = 0; 1580 | int len = unicodeUTF8CharToCodePoint(buf + off, buf_len - off, &cp); 1581 | 1582 | int wid = 0; 1583 | if (!unicodeIsCombiningChar(cp)) { 1584 | wid = unicodeIsWideChar(cp) ? 2 : 1; 1585 | } 1586 | 1587 | int dif = (int)(colwid + wid) - (int)cols; 1588 | if (dif > 0) { 1589 | ret += dif; 1590 | colwid = wid; 1591 | } else if (dif == 0) { 1592 | colwid = 0; 1593 | } else { 1594 | colwid += wid; 1595 | } 1596 | 1597 | if (off >= pos) { 1598 | break; 1599 | } 1600 | 1601 | off += len; 1602 | ret += wid; 1603 | } 1604 | 1605 | return ret; 1606 | } 1607 | 1608 | /* Read UTF8 character from file. 1609 | */ 1610 | inline int unicodeReadUTF8Char(int fd, char* buf, int* cp) 1611 | { 1612 | int nread = read(fd,&buf[0],1); 1613 | 1614 | if (nread <= 0) { return nread; } 1615 | 1616 | unsigned char byte = buf[0]; 1617 | 1618 | if ((byte & 0x80) == 0) { 1619 | ; 1620 | } else if ((byte & 0xE0) == 0xC0) { 1621 | nread = read(fd,&buf[1],1); 1622 | if (nread <= 0) { return nread; } 1623 | } else if ((byte & 0xF0) == 0xE0) { 1624 | nread = read(fd,&buf[1],2); 1625 | if (nread <= 0) { return nread; } 1626 | } else if ((byte & 0xF8) == 0xF0) { 1627 | nread = read(fd,&buf[1],3); 1628 | if (nread <= 0) { return nread; } 1629 | } else { 1630 | return -1; 1631 | } 1632 | 1633 | return unicodeUTF8CharToCodePoint(buf, 4, cp); 1634 | } 1635 | 1636 | /* ======================= Low level terminal handling ====================== */ 1637 | 1638 | /* Return true if the terminal name is in the list of terminals we know are 1639 | * not able to understand basic escape sequences. */ 1640 | inline bool isUnsupportedTerm(void) { 1641 | static const char *unsupported_term[] = {"dumb","cons25","emacs",NULL}; 1642 | #ifndef _WIN32 1643 | char *term = getenv("TERM"); 1644 | int j; 1645 | 1646 | if (term == NULL) return false; 1647 | 1648 | std::string sterm(term); 1649 | // https://stackoverflow.com/a/313990 1650 | std::transform(sterm.begin(), sterm.end(), sterm.begin(), [](unsigned char c){ return std::tolower(c); }); 1651 | for (j = 0; unsupported_term[j]; j++) { 1652 | std::string uterm(unsupported_term[j]); 1653 | // https://stackoverflow.com/a/313990 1654 | std::transform(uterm.begin(), uterm.end(), uterm.begin(), [](unsigned char c){ return std::tolower(c); }); 1655 | if (uterm == sterm) 1656 | return true; 1657 | } 1658 | #endif 1659 | return false; 1660 | } 1661 | 1662 | /* Raw mode: 1960 magic shit. */ 1663 | inline bool enableRawMode(int fd) { 1664 | #ifndef _WIN32 1665 | struct termios raw; 1666 | 1667 | if (!isatty(STDIN_FILENO)) goto fatal; 1668 | if (!atexit_registered) { 1669 | atexit(linenoiseAtExit); 1670 | atexit_registered = true; 1671 | } 1672 | if (tcgetattr(fd,&orig_termios) == -1) goto fatal; 1673 | 1674 | raw = orig_termios; /* modify the original mode */ 1675 | /* input modes: no break, no CR to NL, no parity check, no strip char, 1676 | * no start/stop output control. */ 1677 | raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON); 1678 | /* output modes - disable post processing */ 1679 | // NOTE: Multithreaded issue #20 (https://github.com/yhirose/cpp-linenoise/issues/20) 1680 | // raw.c_oflag &= ~(OPOST); 1681 | /* control modes - set 8 bit chars */ 1682 | raw.c_cflag |= (CS8); 1683 | /* local modes - echoing off, canonical off, no extended functions, 1684 | * no signal chars (^Z,^C) */ 1685 | raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG); 1686 | /* control chars - set return condition: min number of bytes and timer. 1687 | * We want read to return every single byte, without timeout. */ 1688 | raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */ 1689 | 1690 | /* put terminal in raw mode after flushing */ 1691 | if (tcsetattr(fd,TCSAFLUSH,&raw) < 0) goto fatal; 1692 | rawmode = true; 1693 | #else 1694 | if (!atexit_registered) { 1695 | /* Cleanup them at exit */ 1696 | atexit(linenoiseAtExit); 1697 | atexit_registered = true; 1698 | 1699 | /* Init windows console handles only once */ 1700 | hOut = GetStdHandle(STD_OUTPUT_HANDLE); 1701 | if (hOut==INVALID_HANDLE_VALUE) goto fatal; 1702 | } 1703 | 1704 | DWORD consolemodeOut; 1705 | if (!GetConsoleMode(hOut, &consolemodeOut)) { 1706 | CloseHandle(hOut); 1707 | errno = ENOTTY; 1708 | return false; 1709 | }; 1710 | 1711 | hIn = GetStdHandle(STD_INPUT_HANDLE); 1712 | if (hIn == INVALID_HANDLE_VALUE) { 1713 | CloseHandle(hOut); 1714 | errno = ENOTTY; 1715 | return false; 1716 | } 1717 | 1718 | GetConsoleMode(hIn, &consolemodeIn); 1719 | /* Enable raw mode */ 1720 | SetConsoleMode(hIn, consolemodeIn & ~ENABLE_PROCESSED_INPUT); 1721 | 1722 | rawmode = true; 1723 | #endif 1724 | return true; 1725 | 1726 | fatal: 1727 | errno = ENOTTY; 1728 | return false; 1729 | } 1730 | 1731 | inline void disableRawMode(int fd) { 1732 | #ifdef _WIN32 1733 | if (consolemodeIn) { 1734 | SetConsoleMode(hIn, consolemodeIn); 1735 | consolemodeIn = 0; 1736 | } 1737 | rawmode = false; 1738 | #else 1739 | /* Don't even check the return value as it's too late. */ 1740 | if (rawmode && tcsetattr(fd,TCSAFLUSH,&orig_termios) != -1) 1741 | rawmode = false; 1742 | #endif 1743 | } 1744 | 1745 | /* Use the ESC [6n escape sequence to query the horizontal cursor position 1746 | * and return it. On error -1 is returned, on success the position of the 1747 | * cursor. */ 1748 | inline int getCursorPosition(int ifd, int ofd) { 1749 | char buf[32]; 1750 | int cols, rows; 1751 | unsigned int i = 0; 1752 | 1753 | /* Report cursor location */ 1754 | if (write(ofd, "\x1b[6n", 4) != 4) return -1; 1755 | 1756 | /* Read the response: ESC [ rows ; cols R */ 1757 | while (i < sizeof(buf)-1) { 1758 | if (read(ifd,buf+i,1) != 1) break; 1759 | if (buf[i] == 'R') break; 1760 | i++; 1761 | } 1762 | buf[i] = '\0'; 1763 | 1764 | /* Parse it. */ 1765 | if (buf[0] != ESC || buf[1] != '[') return -1; 1766 | if (sscanf(buf+2,"%d;%d",&rows,&cols) != 2) return -1; 1767 | return cols; 1768 | } 1769 | 1770 | /* Try to get the number of columns in the current terminal, or assume 80 1771 | * if it fails. */ 1772 | inline int getColumns(int ifd, int ofd) { 1773 | #ifdef _WIN32 1774 | CONSOLE_SCREEN_BUFFER_INFO b; 1775 | 1776 | if (!GetConsoleScreenBufferInfo(hOut, &b)) return 80; 1777 | return b.srWindow.Right - b.srWindow.Left; 1778 | #else 1779 | struct winsize ws; 1780 | 1781 | if (ioctl(1, TIOCGWINSZ, &ws) == -1 || ws.ws_col == 0) { 1782 | /* ioctl() failed. Try to query the terminal itself. */ 1783 | int start, cols; 1784 | 1785 | /* Get the initial position so we can restore it later. */ 1786 | start = getCursorPosition(ifd,ofd); 1787 | if (start == -1) goto failed; 1788 | 1789 | /* Go to right margin and get position. */ 1790 | if (write(ofd,"\x1b[999C",6) != 6) goto failed; 1791 | cols = getCursorPosition(ifd,ofd); 1792 | if (cols == -1) goto failed; 1793 | 1794 | /* Restore position. */ 1795 | if (cols > start) { 1796 | char seq[32]; 1797 | snprintf(seq,32,"\x1b[%dD",cols-start); 1798 | if (write(ofd,seq,strlen(seq)) == -1) { 1799 | /* Can't recover... */ 1800 | } 1801 | } 1802 | return cols; 1803 | } else { 1804 | return ws.ws_col; 1805 | } 1806 | 1807 | failed: 1808 | return 80; 1809 | #endif 1810 | } 1811 | 1812 | /* Clear the screen. Used to handle ctrl+l */ 1813 | inline void linenoiseClearScreen(void) { 1814 | if (write(STDOUT_FILENO,"\x1b[H\x1b[2J",7) <= 0) { 1815 | /* nothing to do, just to avoid warning. */ 1816 | } 1817 | } 1818 | 1819 | /* Temporarily clear the line from the screen, 1820 | * without resetting its state. Used for 1821 | * temporarily clearing prompt and input while 1822 | * printing other content. */ 1823 | inline void linenoiseWipeLine() { 1824 | // Clear line 1825 | if (write(STDOUT_FILENO, "\33[2K", 4) < 0) { 1826 | /* nothing to do, just to avoid warning. */ 1827 | } 1828 | // Move cursor to the left 1829 | if (write(STDOUT_FILENO, "\r", 1) < 0) { 1830 | /* nothing to do, just to avoid warning. */ 1831 | } 1832 | } 1833 | 1834 | /* Beep, used for completion when there is nothing to complete or when all 1835 | * the choices were already shown. */ 1836 | inline void linenoiseBeep(void) { 1837 | fprintf(stderr, "\x7"); 1838 | fflush(stderr); 1839 | } 1840 | 1841 | /* ============================== Completion ================================ */ 1842 | 1843 | /* This is an helper function for Edit() and is called when the 1844 | * user types the key in order to complete the string currently in the 1845 | * input. 1846 | * 1847 | * The state of the editing is encapsulated into the pointed linenoiseState 1848 | * structure as described in the structure definition. */ 1849 | inline int linenoiseState::completeLine(char *cbuf, int *c) { 1850 | std::vector lc; 1851 | int nread = 0, nwritten; 1852 | *c = 0; 1853 | 1854 | completionCallback(buf_,lc); 1855 | if (lc.empty()) { 1856 | linenoiseBeep(); 1857 | } else { 1858 | int stop = 0, i = 0; 1859 | 1860 | while(!stop) { 1861 | /* Show completion or original buffer */ 1862 | if (i < static_cast(lc.size())) { 1863 | int old_len = len_; 1864 | int old_pos = pos_; 1865 | char *old_buf = buf_; 1866 | len_ = pos_ = static_cast(lc[i].size()); 1867 | buf_ = &lc[i][0]; 1868 | RefreshLine(); 1869 | len_ = old_len; 1870 | pos_ = old_pos; 1871 | buf_ = old_buf; 1872 | } else { 1873 | RefreshLine(); 1874 | } 1875 | 1876 | //nread = read(ifd_,&c,1); 1877 | #ifdef _WIN32 1878 | nread = win32read(c); 1879 | if (nread == 1) { 1880 | cbuf[0] = *c; 1881 | } 1882 | #else 1883 | nread = unicodeReadUTF8Char(ifd_,cbuf,c); 1884 | #endif 1885 | if (nread <= 0) { 1886 | *c = -1; 1887 | return nread; 1888 | } 1889 | 1890 | switch(*c) { 1891 | case 9: /* tab */ 1892 | i = (i+1) % (lc.size()+1); 1893 | if (i == static_cast(lc.size())) linenoiseBeep(); 1894 | break; 1895 | case 27: /* escape */ 1896 | /* Re-show original buffer */ 1897 | if (i < static_cast(lc.size())) RefreshLine(); 1898 | stop = 1; 1899 | break; 1900 | default: 1901 | /* Update buffer and return */ 1902 | if (i < static_cast(lc.size())) { 1903 | nwritten = snprintf(buf_,buf_len_,"%s",&lc[i][0]); 1904 | len_ = pos_ = nwritten; 1905 | } 1906 | stop = 1; 1907 | break; 1908 | } 1909 | } 1910 | } 1911 | 1912 | return nread; 1913 | } 1914 | 1915 | /* =========================== Line editing ================================= */ 1916 | 1917 | /* Single line low level line refresh. 1918 | * 1919 | * Rewrite the currently edited line accordingly to the buffer content, 1920 | * cursor position, and number of columns of the terminal. */ 1921 | inline void linenoiseState::refreshSingleLine() { 1922 | char seq[64]; 1923 | int pcolwid = unicodeColumnPos(prompt_.c_str(), static_cast(prompt_.length())); 1924 | int fd = ofd_; 1925 | std::string ab; 1926 | 1927 | if (cols_ <= 0) 1928 | cols_ = getColumns(ifd_, ofd_); 1929 | 1930 | while((pcolwid+unicodeColumnPos(buf_, pos_)) >= cols_) { 1931 | int glen = unicodeGraphemeLen(buf_, len_, 0); 1932 | buf_ += glen; 1933 | len_ -= glen; 1934 | pos_ -= glen; 1935 | } 1936 | while (pcolwid+unicodeColumnPos(buf_, len_) > cols_) { 1937 | len_ -= unicodePrevGraphemeLen(buf_, len_); 1938 | } 1939 | 1940 | /* Cursor to left edge */ 1941 | snprintf(seq,64,"\r"); 1942 | ab += seq; 1943 | /* Write the prompt and the current buffer content */ 1944 | ab += prompt_; 1945 | ab.append(buf_, len_); 1946 | /* Erase to right */ 1947 | snprintf(seq,64,"\x1b[0K"); 1948 | ab += seq; 1949 | /* Move cursor to original position. */ 1950 | snprintf(seq,64,"\r\x1b[%dC", (int)(unicodeColumnPos(buf_, pos_)+pcolwid)); 1951 | ab += seq; 1952 | if (write(fd,ab.c_str(), static_cast(ab.length())) == -1) {} /* Can't recover from write error. */ 1953 | } 1954 | 1955 | /* Multi line low level line refresh. 1956 | * 1957 | * Rewrite the currently edited line accordingly to the buffer content, 1958 | * cursor position, and number of columns of the terminal. */ 1959 | inline void linenoiseState::refreshMultiLine() { 1960 | if (cols_ <= 0) 1961 | cols_ = getColumns(ifd_, ofd_); 1962 | 1963 | char seq[64]; 1964 | int pcolwid = unicodeColumnPos(prompt_.c_str(), static_cast(prompt_.length())); 1965 | int colpos = unicodeColumnPosForMultiLine(buf_, len_, len_, cols_, pcolwid); 1966 | int colpos2; /* cursor column position. */ 1967 | int rows = (pcolwid+colpos+cols_-1)/cols_; /* rows used by current buf. */ 1968 | int rpos = (pcolwid+oldcolpos_+cols_)/cols_; /* cursor relative row. */ 1969 | int rpos2; /* rpos after refresh. */ 1970 | int col; /* column position, zero-based. */ 1971 | int old_rows = (int)maxrows_; 1972 | int fd = ofd_; 1973 | std::string ab; 1974 | 1975 | /* Update maxrows if needed. */ 1976 | if (rows > (int)maxrows_) maxrows_ = rows; 1977 | 1978 | /* First step: clear all the lines used before. To do so start by 1979 | * going to the last row. */ 1980 | if (old_rows-rpos > 0) { 1981 | snprintf(seq,64,"\x1b[%dB", old_rows-rpos); 1982 | ab += seq; 1983 | } 1984 | 1985 | /* Now for every row clear it, go up. */ 1986 | for (int j = 0; j < old_rows-1; j++) { 1987 | snprintf(seq,64,"\r\x1b[0K\x1b[1A"); 1988 | ab += seq; 1989 | } 1990 | 1991 | /* Clean the top line. */ 1992 | snprintf(seq,64,"\r\x1b[0K"); 1993 | ab += seq; 1994 | 1995 | /* Write the prompt and the current buffer content */ 1996 | ab += prompt_; 1997 | ab.append(buf_, len_); 1998 | 1999 | /* Get text width to cursor position */ 2000 | colpos2 = unicodeColumnPosForMultiLine(buf_, len_, pos_, cols_, pcolwid); 2001 | 2002 | /* If we are at the very end of the screen with our prompt, we need to 2003 | * emit a newline and move the prompt to the first column. */ 2004 | if (pos_ && 2005 | pos_ == len_ && 2006 | (colpos2+pcolwid) % cols_ == 0) 2007 | { 2008 | ab += "\n"; 2009 | snprintf(seq,64,"\r"); 2010 | ab += seq; 2011 | rows++; 2012 | if (rows > (int)maxrows_) maxrows_ = rows; 2013 | } 2014 | 2015 | /* Move cursor to right position. */ 2016 | rpos2 = (pcolwid+colpos2+cols_)/cols_; /* current cursor relative row. */ 2017 | 2018 | /* Go up till we reach the expected position. */ 2019 | if (rows-rpos2 > 0) { 2020 | snprintf(seq,64,"\x1b[%dA", rows-rpos2); 2021 | ab += seq; 2022 | } 2023 | 2024 | /* Set column. */ 2025 | col = (pcolwid + colpos2) % cols_; 2026 | if (col) 2027 | snprintf(seq,64,"\r\x1b[%dC", col); 2028 | else 2029 | snprintf(seq,64,"\r"); 2030 | ab += seq; 2031 | 2032 | oldcolpos_ = colpos2; 2033 | 2034 | if (write(fd,ab.c_str(), static_cast(ab.length())) == -1) {} /* Can't recover from write error. */ 2035 | } 2036 | 2037 | /* Calls the two low level functions refreshSingleLine() or 2038 | * refreshMultiLine() according to the selected mode. */ 2039 | inline void linenoiseState::RefreshLine() { 2040 | mutex_.lock(); 2041 | if (mlmode_) 2042 | refreshMultiLine(); 2043 | else 2044 | refreshSingleLine(); 2045 | mutex_.unlock(); 2046 | } 2047 | 2048 | inline void linenoiseState::WipeLine() { linenoiseWipeLine(); } 2049 | 2050 | inline void linenoiseState::ClearScreen() { linenoiseClearScreen(); } 2051 | 2052 | inline void linenoiseState::SetPrompt(const char *p) { prompt_ = std::string(p); } 2053 | inline void linenoiseState::SetPrompt(std::string &p) { prompt_ = p; } 2054 | 2055 | /* Insert the character 'c' at cursor current position. 2056 | * 2057 | * On error writing to the terminal -1 is returned, otherwise 0. */ 2058 | inline int linenoiseState::EditInsert(const char* cbuf, int clen) { 2059 | if (len_ < buf_len_) { 2060 | if (len_ == pos_) { 2061 | memcpy(&buf_[pos_],cbuf,clen); 2062 | pos_+=clen; 2063 | len_+=clen;; 2064 | buf_[len_] = '\0'; 2065 | if ((!mlmode_ && unicodeColumnPos(prompt_.c_str(), static_cast(prompt_.length()))+unicodeColumnPos(buf_,len_) < cols_) /* || mlmode_ */) { 2066 | /* Avoid a full update of the line in the 2067 | * trivial case. */ 2068 | if (write(ofd_,cbuf,clen) == -1) return -1; 2069 | } else { 2070 | RefreshLine(); 2071 | } 2072 | } else { 2073 | memmove(buf_+pos_+clen,buf_+pos_,len_-pos_); 2074 | memcpy(&buf_[pos_],cbuf,clen); 2075 | pos_+=clen; 2076 | len_+=clen; 2077 | buf_[len_] = '\0'; 2078 | RefreshLine(); 2079 | } 2080 | } 2081 | return 0; 2082 | } 2083 | 2084 | /* Move cursor on the left. */ 2085 | inline void linenoiseState::EditMoveLeft() { 2086 | if (pos_ > 0) { 2087 | pos_ -= unicodePrevGraphemeLen(buf_, pos_); 2088 | RefreshLine(); 2089 | } 2090 | } 2091 | 2092 | /* Move cursor on the right. */ 2093 | inline void linenoiseState::EditMoveRight() { 2094 | if (pos_ != len_) { 2095 | pos_ += unicodeGraphemeLen(buf_, len_, pos_); 2096 | RefreshLine(); 2097 | } 2098 | } 2099 | 2100 | /* Move cursor to the start of the line. */ 2101 | inline void linenoiseState::EditMoveHome() { 2102 | if (pos_ != 0) { 2103 | pos_ = 0; 2104 | RefreshLine(); 2105 | } 2106 | } 2107 | 2108 | /* Move cursor to the end of the line. */ 2109 | inline void linenoiseState::EditMoveEnd() { 2110 | if (pos_ != len_) { 2111 | pos_ = len_; 2112 | RefreshLine(); 2113 | } 2114 | } 2115 | 2116 | /* Substitute the currently edited line with the next or previous history 2117 | * entry as specified by 'dir'. */ 2118 | #define LINENOISE_HISTORY_NEXT 0 2119 | #define LINENOISE_HISTORY_PREV 1 2120 | inline void linenoiseState::EditHistoryNext(int dir) { 2121 | if (history_.size() > 1) { 2122 | /* Update the current history entry before to 2123 | * overwrite it with the next one. */ 2124 | history_[history_.size() - 1 - history_index_] = buf_; 2125 | /* Show the new entry */ 2126 | history_index_ += (dir == LINENOISE_HISTORY_PREV) ? 1 : -1; 2127 | if (history_index_ < 0) { 2128 | history_index_ = 0; 2129 | return; 2130 | } else if (history_index_ >= (int)history_.size()) { 2131 | history_index_ = static_cast(history_.size())-1; 2132 | return; 2133 | } 2134 | memset(buf_, 0, buf_len_); 2135 | strcpy(buf_,history_[history_.size() - 1 - history_index_].c_str()); 2136 | len_ = pos_ = static_cast(strlen(buf_)); 2137 | RefreshLine(); 2138 | } 2139 | } 2140 | 2141 | /* Delete the character at the right of the cursor without altering the cursor 2142 | * position. Basically this is what happens with the "Delete" keyboard key. */ 2143 | inline void linenoiseState::EditDelete() { 2144 | if (len_ > 0 && pos_ < len_) { 2145 | int glen = unicodeGraphemeLen(buf_,len_,pos_); 2146 | memmove(buf_+pos_,buf_+pos_+glen,len_-pos_-glen); 2147 | len_-=glen; 2148 | buf_[len_] = '\0'; 2149 | RefreshLine(); 2150 | } 2151 | } 2152 | 2153 | /* Backspace implementation. */ 2154 | inline void linenoiseState::EditBackspace() { 2155 | if (pos_ > 0 && len_ > 0) { 2156 | int glen = unicodePrevGraphemeLen(buf_,pos_); 2157 | memmove(buf_+pos_-glen,buf_+pos_,len_-pos_); 2158 | pos_-=glen; 2159 | len_-=glen; 2160 | buf_[len_] = '\0'; 2161 | RefreshLine(); 2162 | } 2163 | } 2164 | 2165 | /* Delete the previous word, maintaining the cursor at the start of the 2166 | * current word. */ 2167 | inline void linenoiseState::EditDeletePrevWord() { 2168 | int old_pos = pos_; 2169 | int diff; 2170 | 2171 | while (pos_ > 0 && buf_[pos_-1] == ' ') 2172 | pos_--; 2173 | while (pos_ > 0 && buf_[pos_-1] != ' ') 2174 | pos_--; 2175 | diff = old_pos - pos_; 2176 | memmove(buf_+pos_,buf_+old_pos,len_-old_pos+1); 2177 | len_ -= diff; 2178 | RefreshLine(); 2179 | } 2180 | 2181 | /* This function is the core of the line editing capability of linenoise. 2182 | * It expects 'fd' to be already in "raw mode" so that every key pressed 2183 | * will be returned ASAP to read(). 2184 | * 2185 | * The resulting string is put into 'buf' when the user type enter, or 2186 | * when ctrl+d is typed. 2187 | * 2188 | * The function returns the length of the current buffer. */ 2189 | inline int linenoiseState::Edit() 2190 | { 2191 | /* The latest history entry is always our current buffer, that 2192 | * initially is just an empty string. */ 2193 | AddHistory(""); 2194 | 2195 | if (write(ofd_, prompt_.c_str(), static_cast(prompt_.length())) == -1) return -1; 2196 | while(1) { 2197 | int c; 2198 | char cbuf[4]; 2199 | int nread; 2200 | char seq[3]; 2201 | 2202 | #ifdef _WIN32 2203 | nread = win32read(&c); 2204 | if (nread == 1) { 2205 | cbuf[0] = c; 2206 | } 2207 | #else 2208 | nread = unicodeReadUTF8Char(ifd_,cbuf,&c); 2209 | #endif 2210 | if (nread <= 0) return (int)len_; 2211 | 2212 | /* Only autocomplete when the callback is set. It returns < 0 when 2213 | * there was an error reading from fd. Otherwise it will return the 2214 | * character that should be handled next. */ 2215 | if (c == 9 && completionCallback != NULL) { 2216 | nread = completeLine(cbuf,&c); 2217 | /* Return on errors */ 2218 | if (c < 0) return len_; 2219 | /* Read next character when 0 */ 2220 | if (c == 0) continue; 2221 | } 2222 | 2223 | switch(c) { 2224 | case ENTER: /* enter */ 2225 | if (!history_.empty()) history_.pop_back(); 2226 | if (mlmode_) EditMoveEnd(); 2227 | return (int)len_; 2228 | case CTRL_C: /* ctrl-c */ 2229 | errno = EAGAIN; 2230 | return -1; 2231 | case BACKSPACE: /* backspace */ 2232 | case 8: /* ctrl-h */ 2233 | EditBackspace(); 2234 | break; 2235 | case CTRL_D: /* ctrl-d, remove char at right of cursor, or if the 2236 | line is empty, act as end-of-file. */ 2237 | if (len_ > 0) { 2238 | EditDelete(); 2239 | } else { 2240 | history_.pop_back(); 2241 | return -1; 2242 | } 2243 | break; 2244 | case CTRL_T: /* ctrl-t, swaps current character with previous. */ 2245 | if (pos_ > 0 && pos_ < len_) { 2246 | char aux = wbuf_[pos_-1]; 2247 | wbuf_[pos_-1] = wbuf_[pos_]; 2248 | wbuf_[pos_] = aux; 2249 | if (pos_ != len_-1) pos_++; 2250 | RefreshLine(); 2251 | } 2252 | break; 2253 | case CTRL_B: /* ctrl-b */ 2254 | EditMoveLeft(); 2255 | break; 2256 | case CTRL_F: /* ctrl-f */ 2257 | EditMoveRight(); 2258 | break; 2259 | case CTRL_P: /* ctrl-p */ 2260 | EditHistoryNext(LINENOISE_HISTORY_PREV); 2261 | break; 2262 | case CTRL_N: /* ctrl-n */ 2263 | EditHistoryNext(LINENOISE_HISTORY_NEXT); 2264 | break; 2265 | case ESC: /* escape sequence */ 2266 | /* Read the next two bytes representing the escape sequence. 2267 | * Use two calls to handle slow terminals returning the two 2268 | * chars at different times. */ 2269 | if (read(ifd_,seq,1) == -1) break; 2270 | if (read(ifd_,seq+1,1) == -1) break; 2271 | 2272 | /* ESC [ sequences. */ 2273 | if (seq[0] == '[') { 2274 | if (seq[1] >= '0' && seq[1] <= '9') { 2275 | /* Extended escape, read additional byte. */ 2276 | if (read(ifd_,seq+2,1) == -1) break; 2277 | if (seq[2] == '~') { 2278 | switch(seq[1]) { 2279 | case '3': /* Delete key. */ 2280 | EditDelete(); 2281 | break; 2282 | } 2283 | } 2284 | } else { 2285 | switch(seq[1]) { 2286 | case 'A': /* Up */ 2287 | EditHistoryNext(LINENOISE_HISTORY_PREV); 2288 | break; 2289 | case 'B': /* Down */ 2290 | EditHistoryNext(LINENOISE_HISTORY_NEXT); 2291 | break; 2292 | case 'C': /* Right */ 2293 | EditMoveRight(); 2294 | break; 2295 | case 'D': /* Left */ 2296 | EditMoveLeft(); 2297 | break; 2298 | case 'H': /* Home */ 2299 | EditMoveHome(); 2300 | break; 2301 | case 'F': /* End*/ 2302 | EditMoveEnd(); 2303 | break; 2304 | } 2305 | } 2306 | } 2307 | 2308 | /* ESC O sequences. */ 2309 | else if (seq[0] == 'O') { 2310 | switch(seq[1]) { 2311 | case 'H': /* Home */ 2312 | EditMoveHome(); 2313 | break; 2314 | case 'F': /* End*/ 2315 | EditMoveEnd(); 2316 | break; 2317 | } 2318 | } 2319 | break; 2320 | default: 2321 | if (EditInsert(cbuf,nread)) return -1; 2322 | break; 2323 | case CTRL_U: /* Ctrl+u, delete the whole line. */ 2324 | wbuf_[0] = '\0'; 2325 | pos_ = len_ = 0; 2326 | RefreshLine(); 2327 | break; 2328 | case CTRL_K: /* Ctrl+k, delete from current to end of line. */ 2329 | wbuf_[pos_] = '\0'; 2330 | len_ = pos_; 2331 | RefreshLine(); 2332 | break; 2333 | case CTRL_A: /* Ctrl+a, go to the start of the line */ 2334 | EditMoveHome(); 2335 | break; 2336 | case CTRL_E: /* ctrl+e, go to the end of the line */ 2337 | EditMoveEnd(); 2338 | break; 2339 | case CTRL_L: /* ctrl+l, clear screen */ 2340 | linenoiseClearScreen(); 2341 | RefreshLine(); 2342 | break; 2343 | case CTRL_W: /* ctrl+w, delete previous word */ 2344 | EditDeletePrevWord(); 2345 | break; 2346 | } 2347 | } 2348 | return len_; 2349 | } 2350 | 2351 | /* This function calls the line editing function Edit() using 2352 | * the STDIN file descriptor set in raw mode. */ 2353 | inline bool linenoiseState::Raw(std::string& line) { 2354 | bool quit = false; 2355 | 2356 | if (!isatty(STDIN_FILENO)) { 2357 | /* Not a tty: read from file / pipe. */ 2358 | int c; 2359 | while ((c = getc(stdin)) != EOF) { 2360 | if (c == '\r') // CRLF -> LF 2361 | continue; 2362 | if (c == '\n' || c == '\r') // send command 2363 | break; 2364 | 2365 | line += c; 2366 | } 2367 | if (!line.length()) 2368 | quit = true; 2369 | 2370 | } else { 2371 | /* Interactive editing. */ 2372 | if (enableRawMode(STDIN_FILENO) == false) { 2373 | return quit; 2374 | } 2375 | 2376 | /* Buffer starts empty. Since we're potentially 2377 | * reusing the state, we need to reset these. */ 2378 | pos_ = 0; 2379 | len_ = 0; 2380 | buf_[0] = '\0'; 2381 | wbuf_[0] = '\0'; 2382 | 2383 | auto count = Edit(); 2384 | if (count == -1) { 2385 | quit = true; 2386 | } else { 2387 | line.assign(buf_, count); 2388 | } 2389 | 2390 | disableRawMode(STDIN_FILENO); 2391 | printf("\n"); 2392 | } 2393 | return quit; 2394 | } 2395 | 2396 | inline linenoiseState::linenoiseState(const char *prompt_str, int stdin_fd, int stdout_fd) { 2397 | /* Populate the linenoise state that we pass to functions implementing 2398 | * specific editing functionalities. */ 2399 | ifd_ = stdin_fd; 2400 | ofd_ = stdout_fd; 2401 | buf_ = wbuf_; 2402 | std::string p = (prompt_str) ? std::string(prompt_str) : std::string("> "); 2403 | SetPrompt(p); 2404 | 2405 | /* Buffer starts empty. */ 2406 | buf_[0] = '\0'; 2407 | buf_len_--; /* Make sure there is always space for the nulterm */ 2408 | } 2409 | 2410 | inline void linenoiseState::EnableMultiLine() { mlmode_ = true; } 2411 | inline void linenoiseState::DisableMultiLine() { mlmode_ = false; } 2412 | 2413 | /* The high level function that is the main API of the linenoise library. 2414 | * This function checks if the terminal has basic capabilities, just checking 2415 | * for a blacklist of stupid terminals, and later either calls the line 2416 | * editing function or uses dummy fgets() so that you will be able to type 2417 | * something even in the most desperate of the conditions. */ 2418 | inline bool linenoiseState::Readline(std::string& line) { 2419 | if (isUnsupportedTerm()) { 2420 | printf("%s", prompt_.c_str()); 2421 | fflush(stdout); 2422 | std::getline(std::cin, line); 2423 | return false; 2424 | } else { 2425 | return Raw(line); 2426 | } 2427 | 2428 | return false; 2429 | } 2430 | 2431 | inline std::string linenoiseState::Readline(bool& quit) { 2432 | std::string line; 2433 | quit = Readline(line); 2434 | return line; 2435 | } 2436 | 2437 | inline std::string linenoiseState::Readline() { 2438 | bool quit; // dummy 2439 | return Readline(quit); 2440 | } 2441 | 2442 | /* ================================ History ================================= */ 2443 | 2444 | /* At exit we'll try to fix the terminal to the initial conditions. */ 2445 | inline void linenoiseAtExit(void) { 2446 | disableRawMode(STDIN_FILENO); 2447 | 2448 | // If we're using the global, clean up 2449 | if (lglobal) 2450 | delete lglobal; 2451 | lglobal = NULL; 2452 | } 2453 | 2454 | /* This is the API call to add a new entry in the linenoise history. 2455 | * It uses a fixed array of char pointers that are shifted (memmoved) 2456 | * when the history max length is reached in order to remove the older 2457 | * entry and make room for the new one, so it is not exactly suitable for huge 2458 | * histories, but will work well for a few hundred of entries. 2459 | * 2460 | * Using a circular buffer is smarter, but a bit more complex to handle. */ 2461 | inline bool linenoiseState::AddHistory(const char* line) { 2462 | if (history_max_len_ == 0) return false; 2463 | 2464 | /* Don't add duplicated lines. */ 2465 | if (!history_.empty() && history_.back() == line) return false; 2466 | 2467 | /* If we reached the max length, remove the older line. */ 2468 | if (history_.size() == history_max_len_) { 2469 | history_.erase(history_.begin()); 2470 | } 2471 | history_.push_back(line); 2472 | 2473 | return true; 2474 | } 2475 | 2476 | /* Set the maximum length for the history. This function can be called even 2477 | * if there is already some history, the function will make sure to retain 2478 | * just the latest 'len' elements if the new history length value is smaller 2479 | * than the amount of items already inside the history. */ 2480 | inline bool linenoiseState::SetHistoryMaxLen(size_t mlen) { 2481 | if (mlen < 1) return false; 2482 | history_max_len_ = mlen; 2483 | if (mlen < history_.size()) { 2484 | history_.resize(mlen); 2485 | } 2486 | return true; 2487 | } 2488 | 2489 | /* Save the history in the specified file. On success *true* is returned 2490 | * otherwise *false* is returned. */ 2491 | inline bool linenoiseState::SaveHistory(const char* path) { 2492 | std::ofstream f(path); // TODO: need 'std::ios::binary'? 2493 | if (!f) return false; 2494 | for (const auto& h: history_) { 2495 | f << h << std::endl; 2496 | } 2497 | return true; 2498 | } 2499 | 2500 | /* Load the history from the specified file. If the file does not exist 2501 | * zero is returned and no operation is performed. 2502 | * 2503 | * If the file exists and the operation succeeded *true* is returned, otherwise 2504 | * on error *false* is returned. */ 2505 | inline bool linenoiseState::LoadHistory(const char* path) { 2506 | std::ifstream f(path); 2507 | if (!f) return false; 2508 | std::string line; 2509 | while (std::getline(f, line)) { 2510 | AddHistory(line.c_str()); 2511 | } 2512 | return true; 2513 | } 2514 | 2515 | 2516 | 2517 | /* Function style interface */ 2518 | inline void SetCompletionCallback(CompletionCallback fn){ 2519 | if (!lglobal) 2520 | lglobal = new linenoiseState(); 2521 | lglobal->SetCompletionCallback(fn); 2522 | }; 2523 | inline void SetMultiLine(bool ml){ 2524 | if (!lglobal) 2525 | lglobal = new linenoiseState(); 2526 | if (ml) { 2527 | lglobal->EnableMultiLine(); 2528 | } else { 2529 | lglobal->DisableMultiLine(); 2530 | } 2531 | }; 2532 | inline bool AddHistory(const char* line){ 2533 | if (!lglobal) 2534 | lglobal = new linenoiseState(); 2535 | return lglobal->AddHistory(line); 2536 | }; 2537 | inline bool SetHistoryMaxLen(size_t len){ 2538 | if (!lglobal) 2539 | lglobal = new linenoiseState(); 2540 | return lglobal->SetHistoryMaxLen(len); 2541 | }; 2542 | inline bool SaveHistory(const char* path){ 2543 | if (!lglobal) 2544 | lglobal = new linenoiseState(); 2545 | return lglobal->SaveHistory(path); 2546 | }; 2547 | inline bool LoadHistory(const char* path){ 2548 | if (!lglobal) 2549 | lglobal = new linenoiseState(); 2550 | return lglobal->LoadHistory(path); 2551 | }; 2552 | inline const std::vector& GetHistory(){ 2553 | if (!lglobal) 2554 | lglobal = new linenoiseState(); 2555 | return lglobal->GetHistory(); 2556 | }; 2557 | inline bool Readline(const char *prompt, std::string& line){ 2558 | if (!lglobal) 2559 | lglobal = new linenoiseState(); 2560 | lglobal->SetPrompt(prompt); 2561 | return lglobal->Readline(line); 2562 | }; 2563 | inline std::string Readline(const char *prompt, bool& quit){ 2564 | if (!lglobal) 2565 | lglobal = new linenoiseState(); 2566 | lglobal->SetPrompt(prompt); 2567 | std::string line; 2568 | quit = lglobal->Readline(line); 2569 | return line; 2570 | }; 2571 | inline std::string Readline(const char *prompt){ 2572 | bool quit; // dummy 2573 | return Readline(prompt, quit); 2574 | }; 2575 | 2576 | 2577 | 2578 | } // namespace linenoise 2579 | 2580 | #ifdef _WIN32 2581 | #undef isatty 2582 | #undef write 2583 | #undef read 2584 | #pragma warning(pop) 2585 | #endif 2586 | 2587 | #endif /* __LINENOISE_HPP */ 2588 | --------------------------------------------------------------------------------