diff --git a/src/input_handler.cc b/src/input_handler.cc index 1dbb63bf..f3f6f710 100644 --- a/src/input_handler.cc +++ b/src/input_handler.cc @@ -420,7 +420,7 @@ public: void insert(Codepoint cp) { - m_line = m_line.substr(0, m_cursor_pos) + codepoint_to_str(cp) + m_line = m_line.substr(0, m_cursor_pos) + String{cp} + m_line.substr(m_cursor_pos); ++m_cursor_pos; } @@ -1187,7 +1187,7 @@ private: void insert(Codepoint key) { - auto str = codepoint_to_str(key); + String str{key}; context().selections().insert(str, InsertMode::InsertCursor); context().hooks().run_hook("InsertChar", str, context()); } diff --git a/src/keys.cc b/src/keys.cc index 3e0277e0..f98a5dc0 100644 --- a/src/keys.cc +++ b/src/keys.cc @@ -131,7 +131,7 @@ String key_to_str(Key key) res = "F" + to_string((int)(key.key - Key::F1 + 1)); } else - res = codepoint_to_str(key.key); + res = String{key.key}; switch (key.modifiers) { diff --git a/src/string.hh b/src/string.hh index 5b62bf12..638f30f9 100644 --- a/src/string.hh +++ b/src/string.hh @@ -102,6 +102,7 @@ public: String(const char* content, ByteCount len) : m_data(content, (size_t)(int)len) {} explicit String(Codepoint cp, CharCount count = 1) { + reserve(utf8::codepoint_size(cp) * (int)count); while (count-- > 0) utf8::dump(std::back_inserter(*this), cp); } @@ -252,13 +253,6 @@ inline String operator"" _str(const char* str, size_t) return String(str); } -inline String codepoint_to_str(Codepoint cp) -{ - String str; - utf8::dump(std::back_inserter(str), cp); - return str; -} - int str_to_int(StringView str); // throws on error Optional str_to_int_ifp(StringView str); diff --git a/src/utf8.hh b/src/utf8.hh index f38327eb..648c6011 100644 --- a/src/utf8.hh +++ b/src/utf8.hh @@ -178,6 +178,20 @@ ByteCount codepoint_size(char byte) struct invalid_codepoint{}; +inline ByteCount codepoint_size(Codepoint cp) +{ + if (cp <= 0x7F) + return 1; + else if (cp <= 0x7FF) + return 2; + else if (cp <= 0xFFFF) + return 3; + else if (cp <= 0x10FFFF) + return 4; + else + throw invalid_codepoint{}; +} + template void dump(OutputIterator&& it, Codepoint cp) {