3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Jean-Marc Lasgouttes
10 * Full author contact details are available in file CREDITS.
15 #include "support/lstrings.h"
17 #include "support/convert.h"
18 #include "support/qstring_helpers.h"
19 #include "support/textutils.h"
21 #include <boost/tokenizer.hpp>
22 #include "support/assert.h"
33 // Using this allows us to have docstring default arguments in headers
34 // without #include "support/docstring" there.
35 docstring const & empty_docstring()
41 // Using this allows us to have string default arguments in headers
42 // without #include <string>
43 string const & empty_string()
50 * Convert a QChar into a UCS4 character.
51 * This is a hack (it does only make sense for the common part of the UCS4
52 * and UTF16 encodings) and should not be used.
53 * This does only exist because of performance reasons (a real conversion
54 * using iconv is too slow on windows).
56 static inline char_type qchar_to_ucs4(QChar const & qchar)
58 LASSERT(is_utf16(static_cast<char_type>(qchar.unicode())), /**/);
59 return static_cast<char_type>(qchar.unicode());
64 QString toqstr(char const * str)
66 return QString::fromUtf8(str);
69 QString toqstr(std::string const & str)
71 return toqstr(str.c_str());
75 QString toqstr(docstring const & ucs4)
77 // If possible we let qt do the work, since this version does not
78 // need to be superfast.
79 return QString::fromUcs4((uint const *)ucs4.data(), ucs4.length());
82 QString toqstr(char_type ucs4)
84 union { char_type c; uint i; } u = { ucs4 };
85 return QString::fromUcs4(&u.i, 1);
88 docstring qstring_to_ucs4(QString const & qstr)
92 QVector<uint> const ucs4 = qstr.toUcs4();
93 return docstring((char_type const *)(ucs4.constData()), ucs4.size());
96 std::string fromqstr(QString const & str)
98 return str.isEmpty() ? std::string() : std::string(str.toUtf8());
103 * Convert a UCS4 character into a QChar.
104 * This is a hack (it does only make sense for the common part of the UCS4
105 * and UTF16 encodings) and should not be used.
106 * This does only exist because of performance reasons (a real conversion
107 * using iconv is too slow on windows).
109 static inline QChar const ucs4_to_qchar(char_type const ucs4)
111 LASSERT(is_utf16(ucs4), /**/);
112 return QChar(static_cast<unsigned short>(ucs4));
117 /// Maximum valid UCS4 code point
118 char_type const ucs4_max = 0x10ffff;
122 bool isLetterChar(char_type c)
126 // outside the UCS4 range
128 // assume that all non-utf16 characters are letters
131 return ucs4_to_qchar(c).isLetter();
135 bool isAlphaASCII(char_type c)
137 return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z');
141 bool isPrintable(char_type c)
145 // outside the UCS4 range
147 // assume that all non-utf16 characters are printable
150 return ucs4_to_qchar(c).isPrint();
154 bool isPrintableNonspace(char_type c)
158 // outside the UCS4 range
160 // assume that all non-utf16 characters are printable and
164 QChar const qc = ucs4_to_qchar(c);
165 return qc.isPrint() && !qc.isSpace();
169 bool isSpace(char_type c)
172 // assume that no non-utf16 character is a space
173 // c outside the UCS4 range is catched as well
176 QChar const qc = ucs4_to_qchar(c);
181 bool isDigit(char_type c)
184 // assume that no non-utf16 character is a digit
185 // c outside the UCS4 range is catched as well
187 return ucs4_to_qchar(c).isDigit();
191 bool isDigitASCII(char_type c)
193 return '0' <= c && c <= '9';
198 int compare_no_case(docstring const & s, docstring const & s2)
200 docstring::const_iterator p = s.begin();
201 docstring::const_iterator p2 = s2.begin();
203 while (p != s.end() && p2 != s2.end()) {
204 char_type const lc1 = lowercase(*p);
205 char_type const lc2 = lowercase(*p2);
207 return (lc1 < lc2) ? -1 : 1;
212 if (s.size() == s2.size())
214 if (s.size() < s2.size())
222 template<typename Char>
223 Char ascii_tolower(Char c) {
224 if (c >= 'A' && c <= 'Z')
225 return c - 'A' + 'a';
232 int compare_ascii_no_case(string const & s, string const & s2)
234 string::const_iterator p = s.begin();
235 string::const_iterator p2 = s2.begin();
237 while (p != s.end() && p2 != s2.end()) {
238 int const lc1 = ascii_tolower(*p);
239 int const lc2 = ascii_tolower(*p2);
241 return (lc1 < lc2) ? -1 : 1;
246 if (s.size() == s2.size())
248 if (s.size() < s2.size())
254 int compare_ascii_no_case(docstring const & s, docstring const & s2)
256 docstring::const_iterator p = s.begin();
257 docstring::const_iterator p2 = s2.begin();
259 while (p != s.end() && p2 != s2.end()) {
260 char_type const lc1 = ascii_tolower(*p);
261 char_type const lc2 = ascii_tolower(*p2);
263 return (lc1 < lc2) ? -1 : 1;
268 if (s.size() == s2.size())
270 if (s.size() < s2.size())
276 bool isStrInt(string const & str)
281 // Remove leading and trailing white space chars.
282 string const tmpstr = trim(str);
286 string::const_iterator cit = tmpstr.begin();
290 string::const_iterator end = tmpstr.end();
291 for (; cit != end; ++cit)
292 if (!isdigit((*cit)))
299 bool isStrUnsignedInt(string const & str)
304 // Remove leading and trailing white space chars.
305 string const tmpstr = trim(str);
309 string::const_iterator cit = tmpstr.begin();
310 string::const_iterator end = tmpstr.end();
311 for (; cit != end; ++cit)
312 if (!isdigit((*cit)))
319 bool isStrDbl(string const & str)
324 // Remove leading and trailing white space chars.
325 string const tmpstr = trim(str);
328 // if (tmpstr.count('.') > 1) return false;
330 string::const_iterator cit = tmpstr.begin();
331 bool found_dot = false;
334 string::const_iterator end = tmpstr.end();
335 for (; cit != end; ++cit) {
336 if (!isdigit(*cit) && *cit != '.')
348 static bool isHexChar(char_type c)
360 c == 'a' || c == 'A' ||
361 c == 'b' || c == 'B' ||
362 c == 'c' || c == 'C' ||
363 c == 'd' || c == 'D' ||
364 c == 'e' || c == 'E' ||
365 c == 'f' || c == 'F';
369 bool isHex(docstring const & str)
373 if (str.length() > 2 && str[0] == '0' &&
374 (str[1] == 'x' || str[1] == 'X'))
377 int const len = str.length();
379 for (; index < len; ++index) {
380 if (!isHexChar(str[index]))
387 int hexToInt(docstring const & str)
389 string s = to_ascii(str);
391 sscanf(s.c_str(), "%x", &h);
396 bool isAscii(docstring const & str)
398 int const len = str.length();
399 for (int i = 0; i < len; ++i)
406 bool isAscii(string const & str)
408 int const len = str.length();
409 for (int i = 0; i < len; ++i)
410 if (static_cast<unsigned char>(str[i]) >= 0x80)
416 char lowercase(char c)
418 LASSERT(static_cast<unsigned char>(c) < 0x80, /**/);
419 return char(tolower(c));
423 char uppercase(char c)
425 LASSERT(static_cast<unsigned char>(c) < 0x80, /**/);
426 return char(toupper(c));
430 char_type lowercase(char_type c)
433 // We don't know how to lowercase a non-utf16 char
435 return qchar_to_ucs4(ucs4_to_qchar(c).toLower());
439 char_type uppercase(char_type c)
442 // We don't know how to uppercase a non-utf16 char
444 return qchar_to_ucs4(ucs4_to_qchar(c).toUpper());
450 // since we cannot use tolower and toupper directly in the
451 // calls to transform yet, we use these helper clases. (Lgb)
453 struct local_lowercase {
454 char_type operator()(char_type c) const {
456 // We don't know how to lowercase a non-utf16 char
458 return qchar_to_ucs4(ucs4_to_qchar(c).toLower());
462 struct local_uppercase {
463 char_type operator()(char_type c) const {
465 // We don't know how to uppercase a non-utf16 char
467 return qchar_to_ucs4(ucs4_to_qchar(c).toUpper());
471 template<typename Char> struct local_ascii_lowercase {
472 Char operator()(Char c) const { return ascii_tolower(c); }
475 } // end of anon namespace
477 docstring const lowercase(docstring const & a)
480 transform(tmp.begin(), tmp.end(), tmp.begin(), local_lowercase());
485 docstring const uppercase(docstring const & a)
488 transform(tmp.begin(), tmp.end(), tmp.begin(), local_uppercase());
493 string const ascii_lowercase(string const & a)
496 transform(tmp.begin(), tmp.end(), tmp.begin(),
497 local_ascii_lowercase<char>());
502 docstring const ascii_lowercase(docstring const & a)
505 transform(tmp.begin(), tmp.end(), tmp.begin(),
506 local_ascii_lowercase<char_type>());
511 bool prefixIs(docstring const & a, char_type c)
519 bool prefixIs(string const & a, string const & pre)
521 size_t const prelen = pre.length();
522 size_t const alen = a.length();
523 return prelen <= alen && !a.empty() && a.compare(0, prelen, pre) == 0;
527 bool prefixIs(docstring const & a, docstring const & pre)
529 size_t const prelen = pre.length();
530 size_t const alen = a.length();
531 return prelen <= alen && !a.empty() && a.compare(0, prelen, pre) == 0;
535 bool suffixIs(string const & a, char c)
537 if (a.empty()) return false;
538 return a[a.length() - 1] == c;
542 bool suffixIs(docstring const & a, char_type c)
546 return a[a.length() - 1] == c;
550 bool suffixIs(string const & a, string const & suf)
552 size_t const suflen = suf.length();
553 size_t const alen = a.length();
554 return suflen <= alen && a.compare(alen - suflen, suflen, suf) == 0;
558 bool containsOnly(string const & s, string const & cset)
560 return s.find_first_not_of(cset) == string::npos;
564 // ale970405+lasgoutt-970425
565 // rewritten to use new string (Lgb)
566 string const token(string const & a, char delim, int n)
574 // Find delimiter or end of string
576 if ((i = a.find(delim, i)) == string::npos)
582 // i is now the n'th delim (or string::npos)
583 if (i == string::npos)
586 k = a.find(delim, i);
587 // k is now the n'th + 1 delim (or string::npos)
589 return a.substr(i, k - i);
593 docstring const token(docstring const & a, char_type delim, int n)
601 // Find delimiter or end of string
603 if ((i = a.find(delim, i)) == docstring::npos)
609 // i is now the n'th delim (or string::npos)
610 if (i == docstring::npos)
613 k = a.find(delim, i);
614 // k is now the n'th + 1 delim (or string::npos)
616 return a.substr(i, k - i);
620 // this could probably be faster and/or cleaner, but it seems to work (JMarc)
621 // rewritten to use new string (Lgb)
622 int tokenPos(string const & a, char delim, string const & tok)
628 while (!str.empty()) {
629 str = split(str, tmptok, delim);
638 // this could probably be faster and/or cleaner, but it seems to work (JMarc)
639 // rewritten to use new string (Lgb)
640 int tokenPos(docstring const & a, char_type delim, docstring const & tok)
646 while (!str.empty()) {
647 str = split(str, tmptok, delim);
658 /// Substitute all \a oldchar with \a newchar
659 template<typename Ch> inline
660 basic_string<Ch> const subst_char(basic_string<Ch> const & a,
661 Ch oldchar, Ch newchar)
663 typedef basic_string<Ch> String;
665 typename String::iterator lit = tmp.begin();
666 typename String::iterator end = tmp.end();
667 for (; lit != end; ++lit)
668 if ((*lit) == oldchar)
673 /// Substitute all \a oldchar with \a newchar
674 docstring const subst_char(docstring const & a,
675 docstring::value_type oldchar, docstring::value_type newchar)
678 docstring::iterator lit = tmp.begin();
679 docstring::iterator end = tmp.end();
680 for (; lit != end; ++lit)
681 if ((*lit) == oldchar)
687 /// substitutes all instances of \a oldstr with \a newstr
688 template<typename String> inline
689 String const subst_string(String const & a,
690 String const & oldstr, String const & newstr)
692 LASSERT(!oldstr.empty(), /**/);
695 size_t const olen = oldstr.length();
696 while ((i = lstr.find(oldstr, i)) != string::npos) {
697 lstr.replace(i, olen, newstr);
698 i += newstr.length(); // We need to be sure that we dont
699 // use the same i over and over again.
704 docstring const subst_string(docstring const & a,
705 docstring const & oldstr, docstring const & newstr)
707 LASSERT(!oldstr.empty(), /**/);
710 size_t const olen = oldstr.length();
711 while ((i = lstr.find(oldstr, i)) != string::npos) {
712 lstr.replace(i, olen, newstr);
713 i += newstr.length(); // We need to be sure that we dont
714 // use the same i over and over again.
722 string const subst(string const & a, char oldchar, char newchar)
724 return subst_char(a, oldchar, newchar);
728 docstring const subst(docstring const & a,
729 char_type oldchar, char_type newchar)
731 return subst_char(a, oldchar, newchar);
735 string const subst(string const & a,
736 string const & oldstr, string const & newstr)
738 return subst_string(a, oldstr, newstr);
742 docstring const subst(docstring const & a,
743 docstring const & oldstr, docstring const & newstr)
745 return subst_string(a, oldstr, newstr);
749 docstring const trim(docstring const & a, char const * p)
753 if (a.empty() || !*p)
756 docstring s = from_ascii(p);
757 size_t r = a.find_last_not_of(s);
758 size_t l = a.find_first_not_of(s);
760 // Is this the minimal test? (lgb)
761 if (r == docstring::npos && l == docstring::npos)
764 return a.substr(l, r - l + 1);
768 string const trim(string const & a, char const * p)
772 if (a.empty() || !*p)
775 size_t r = a.find_last_not_of(p);
776 size_t l = a.find_first_not_of(p);
778 // Is this the minimal test? (lgb)
779 if (r == string::npos && l == string::npos)
782 return a.substr(l, r - l + 1);
786 string const rtrim(string const & a, char const * p)
790 if (a.empty() || !*p)
793 size_t r = a.find_last_not_of(p);
795 // Is this test really needed? (Lgb)
796 if (r == string::npos)
799 return a.substr(0, r + 1);
803 docstring const rtrim(docstring const & a, char const * p)
807 if (a.empty() || !*p)
810 size_t r = a.find_last_not_of(from_ascii(p));
812 // Is this test really needed? (Lgb)
813 if (r == docstring::npos)
816 return a.substr(0, r + 1);
820 string const ltrim(string const & a, char const * p)
823 if (a.empty() || !*p)
825 size_t l = a.find_first_not_of(p);
826 if (l == string::npos)
828 return a.substr(l, string::npos);
832 docstring const ltrim(docstring const & a, char const * p)
835 if (a.empty() || !*p)
837 size_t l = a.find_first_not_of(from_ascii(p));
838 if (l == docstring::npos)
840 return a.substr(l, docstring::npos);
845 template<typename String, typename Char> inline
846 String const doSplit(String const & a, String & piece, Char delim)
849 size_t i = a.find(delim);
850 if (i == a.length() - 1) {
851 piece = a.substr(0, i);
852 } else if (i != String::npos) {
853 piece = a.substr(0, i);
854 tmp = a.substr(i + 1);
857 tmp = a.substr(i + 1);
864 template<typename Char> inline
865 docstring const doSplit(docstring const & a, docstring & piece, Char delim)
868 size_t i = a.find(delim);
869 if (i == a.length() - 1) {
870 piece = a.substr(0, i);
871 } else if (i != docstring::npos) {
872 piece = a.substr(0, i);
873 tmp = a.substr(i + 1);
876 tmp = a.substr(i + 1);
886 string const split(string const & a, string & piece, char delim)
888 return doSplit(a, piece, delim);
892 docstring const split(docstring const & a, docstring & piece, char_type delim)
894 return doSplit(a, piece, delim);
898 string const split(string const & a, char delim)
901 size_t i = a.find(delim);
902 if (i != string::npos) // found delim
903 tmp = a.substr(i + 1);
909 string const rsplit(string const & a, string & piece, char delim)
912 size_t i = a.rfind(delim);
913 if (i != string::npos) { // delimiter was found
914 piece = a.substr(0, i);
915 tmp = a.substr(i + 1);
916 } else { // delimiter was not found
923 docstring const escape(docstring const & lab)
925 char_type hexdigit[16] = { '0', '1', '2', '3', '4', '5', '6', '7',
926 '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
928 for (size_t i = 0; i < lab.length(); ++i) {
929 char_type c = lab[i];
930 if (c >= 128 || c == '=' || c == '%') {
931 // Although char_type is a 32 bit type we know that
932 // UCS4 occupies only 21 bits, so we don't need to
933 // encode bigger values. Test for 2^24 because we
934 // can encode that with the 6 hex digits that are
935 // needed for 21 bits anyway.
936 LASSERT(c < (1 << 24), /**/);
938 enc += hexdigit[(c>>20) & 15];
939 enc += hexdigit[(c>>16) & 15];
940 enc += hexdigit[(c>>12) & 15];
941 enc += hexdigit[(c>> 8) & 15];
942 enc += hexdigit[(c>> 4) & 15];
943 enc += hexdigit[ c & 15];
954 template<typename String> vector<String> const
955 getVectorFromStringT(String const & str, String const & delim)
957 // Lars would like this code to go, but for now his replacement (below)
958 // doesn't fullfil the same function. I have, therefore, reactivated the
959 // old code for now. Angus 11 Nov 2002.
964 String keys = rtrim(str);
966 size_t const idx = keys.find(delim);
967 if (idx == String::npos) {
968 vec.push_back(ltrim(keys));
971 String const key = trim(keys.substr(0, idx));
974 size_t const start = idx + delim.size();
975 keys = keys.substr(start);
979 typedef boost::char_separator<typename String::value_type> Separator;
980 typedef boost::tokenizer<Separator, typename String::const_iterator, String> Tokenizer;
981 Separator sep(delim.c_str());
982 Tokenizer tokens(str, sep);
983 return vector<String>(tokens.begin(), tokens.end());
990 vector<string> const getVectorFromString(string const & str,
991 string const & delim)
993 return getVectorFromStringT<string>(str, delim);
997 vector<docstring> const getVectorFromString(docstring const & str,
998 docstring const & delim)
1000 return getVectorFromStringT<docstring>(str, delim);
1004 // the same vice versa
1005 string const getStringFromVector(vector<string> const & vec,
1006 string const & delim)
1010 for (vector<string>::const_iterator it = vec.begin();
1011 it != vec.end(); ++it) {
1012 string item = trim(*it);
1023 int findToken(char const * const str[], string const & search_token)
1027 while (str[i][0] && str[i] != search_token)
1035 docstring const externalLineEnding(docstring const & str)
1037 #if defined(__APPLE__)
1038 // The MAC clipboard uses \r for lineendings, and we use \n
1039 return subst(str, '\n', '\r');
1040 #elif defined (_WIN32) || (defined (__CYGWIN__) && defined (X_DISPLAY_MISSING))
1041 // Windows clipboard uses \r\n for lineendings, and we use \n
1042 return subst(str, from_ascii("\n"), from_ascii("\r\n"));
1049 docstring const internalLineEnding(docstring const & str)
1051 docstring const s = subst(str, from_ascii("\r\n"), from_ascii("\n"));
1052 return subst(s, '\r', '\n');
1057 docstring bformat(docstring const & fmt, int arg1)
1059 LASSERT(contains(fmt, from_ascii("%1$d")), /**/);
1060 docstring const str = subst(fmt, from_ascii("%1$d"), convert<docstring>(arg1));
1061 return subst(str, from_ascii("%%"), from_ascii("%"));
1066 docstring bformat(docstring const & fmt, long arg1)
1068 LASSERT(contains(fmt, from_ascii("%1$d")), /**/);
1069 docstring const str = subst(fmt, from_ascii("%1$d"), convert<docstring>(arg1));
1070 return subst(str, from_ascii("%%"), from_ascii("%"));
1075 docstring bformat(docstring const & fmt, unsigned int arg1)
1077 LASSERT(contains(fmt, from_ascii("%1$d")), /**/);
1078 docstring const str = subst(fmt, from_ascii("%1$d"), convert<docstring>(arg1));
1079 return subst(str, from_ascii("%%"), from_ascii("%"));
1084 docstring bformat(docstring const & fmt, docstring arg1)
1086 LASSERT(contains(fmt, from_ascii("%1$s")), /**/);
1087 docstring const str = subst(fmt, from_ascii("%1$s"), arg1);
1088 return subst(str, from_ascii("%%"), from_ascii("%"));
1093 docstring bformat(docstring const & fmt, char * arg1)
1095 LASSERT(contains(fmt, from_ascii("%1$s")), /**/);
1096 docstring const str = subst(fmt, from_ascii("%1$s"), from_ascii(arg1));
1097 return subst(str, from_ascii("%%"), from_ascii("%"));
1102 docstring bformat(docstring const & fmt, docstring arg1, docstring arg2)
1104 LASSERT(contains(fmt, from_ascii("%1$s")), /**/);
1105 LASSERT(contains(fmt, from_ascii("%2$s")), /**/);
1106 docstring str = subst(fmt, from_ascii("%1$s"), arg1);
1107 str = subst(str, from_ascii("%2$s"), arg2);
1108 return subst(str, from_ascii("%%"), from_ascii("%"));
1113 docstring bformat(docstring const & fmt, char const * arg1, docstring arg2)
1115 LASSERT(contains(fmt, from_ascii("%1$s")), /**/);
1116 LASSERT(contains(fmt, from_ascii("%2$s")), /**/);
1117 docstring str = subst(fmt, from_ascii("%1$s"), from_ascii(arg1));
1118 str = subst(fmt, from_ascii("%2$s"), arg2);
1119 return subst(str, from_ascii("%%"), from_ascii("%"));
1124 docstring bformat(docstring const & fmt, int arg1, int arg2)
1126 LASSERT(contains(fmt, from_ascii("%1$d")), /**/);
1127 LASSERT(contains(fmt, from_ascii("%2$d")), /**/);
1128 docstring str = subst(fmt, from_ascii("%1$d"), convert<docstring>(arg1));
1129 str = subst(str, from_ascii("%2$d"), convert<docstring>(arg2));
1130 return subst(str, from_ascii("%%"), from_ascii("%"));
1135 docstring bformat(docstring const & fmt, docstring arg1, docstring arg2, docstring arg3)
1137 LASSERT(contains(fmt, from_ascii("%1$s")), /**/);
1138 LASSERT(contains(fmt, from_ascii("%2$s")), /**/);
1139 LASSERT(contains(fmt, from_ascii("%3$s")), /**/);
1140 docstring str = subst(fmt, from_ascii("%1$s"), arg1);
1141 str = subst(str, from_ascii("%2$s"), arg2);
1142 str = subst(str, from_ascii("%3$s"), arg3);
1143 return subst(str, from_ascii("%%"), from_ascii("%"));
1148 docstring bformat(docstring const & fmt,
1149 docstring arg1, docstring arg2, docstring arg3, docstring arg4)
1151 LASSERT(contains(fmt, from_ascii("%1$s")), /**/);
1152 LASSERT(contains(fmt, from_ascii("%2$s")), /**/);
1153 LASSERT(contains(fmt, from_ascii("%3$s")), /**/);
1154 LASSERT(contains(fmt, from_ascii("%4$s")), /**/);
1155 docstring str = subst(fmt, from_ascii("%1$s"), arg1);
1156 str = subst(str, from_ascii("%2$s"), arg2);
1157 str = subst(str, from_ascii("%3$s"), arg3);
1158 str = subst(str, from_ascii("%4$s"), arg4);
1159 return subst(str, from_ascii("%%"), from_ascii("%"));
1162 } // namespace support