]> git.lyx.org Git - lyx.git/blob - src/support/lstrings.cpp
Adjust debug output for fonts
[lyx.git] / src / support / lstrings.cpp
1 /**
2  * \file lstrings.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Jean-Marc Lasgouttes
8  * \author Dekel Tsur
9  *
10  * Full author contact details are available in file CREDITS.
11  */
12
13 #include <config.h>
14
15 #include "support/lstrings.h"
16
17 #include "support/convert.h"
18 #include "support/debug.h"
19 #include "support/lyxlib.h"
20 #include "support/qstring_helpers.h"
21
22 #include "support/lassert.h"
23
24 #include <QString>
25
26 #include <cstdio>
27 #include <cstring>
28 #include <algorithm>
29 #include <iomanip>
30 #include <sstream>
31 #include <typeinfo>
32
33 using namespace std;
34
35 namespace lyx {
36
37 // Using this allows us to have docstring default arguments in headers
38 // without #include "support/docstring" there.
39 docstring const & empty_docstring()
40 {
41         static const docstring s;
42         return s;
43 }
44
45 // Using this allows us to have string default arguments in headers
46 // without #include <string>
47 string const & empty_string()
48 {
49         static const string s;
50         return s;
51 }
52
53 namespace {
54 /**
55  * Convert a QChar into a UCS4 character.
56  * This is a hack (it does only make sense for the common part of the UCS4
57  * and UTF16 encodings) and should not be used.
58  * This does only exist because of performance reasons (a real conversion
59  * using iconv is too slow on windows).
60  */
61 inline char_type qchar_to_ucs4(QChar const & qchar)
62 {
63         LASSERT(is_utf16(static_cast<char_type>(qchar.unicode())), return '?');
64         return static_cast<char_type>(qchar.unicode());
65 }
66
67 /**
68  * Convert a UCS4 character into a QChar.
69  * This is a hack (it does only make sense for the common part of the UCS4
70  * and UTF16 encodings) and should not be used.
71  * This does only exist because of performance reasons (a real conversion
72  * using iconv is too slow on windows).
73  */
74 inline QChar const ucs4_to_qchar(char_type const ucs4)
75 {
76         LASSERT(is_utf16(ucs4), return QChar('?'));
77         return QChar(static_cast<unsigned short>(ucs4));
78 }
79
80 /// Maximum valid UCS4 code point
81 char_type const ucs4_max = 0x10ffff;
82 } // namespace
83
84
85 bool isLetterChar(char_type c)
86 {
87         if (!is_utf16(c)) {
88                 if (c > ucs4_max)
89                         // outside the UCS4 range
90                         return false;
91                 // assume that all non-utf16 characters are letters
92                 return true;
93         }
94         return ucs4_to_qchar(c).isLetter();
95 }
96
97
98 bool isLower(char_type c)
99 {
100         if (!is_utf16(c))
101                 return false;
102         return ucs4_to_qchar(c).isLower();
103 }
104
105
106 bool isAlphaASCII(char_type c)
107 {
108         return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z');
109 }
110
111
112 bool isPrintable(char_type c)
113 {
114         if (!is_utf16(c)) {
115                 if (c > ucs4_max)
116                         // outside the UCS4 range
117                         return false;
118                 // assume that all non-utf16 characters are printable
119                 return true;
120         }
121         // Not yet recognized by QChar::isPrint()
122         // See https://bugreports.qt-project.org/browse/QTBUG-12144
123         // LATIN CAPITAL LETTER SHARP S
124         else if (c == 0x1e9e)
125                 return true;
126         return ucs4_to_qchar(c).isPrint();
127 }
128
129
130 bool isPrintableNonspace(char_type c)
131 {
132         if (!is_utf16(c)) {
133                 if (c > ucs4_max)
134                         // outside the UCS4 range
135                         return false;
136                 // assume that all non-utf16 characters are printable and
137                 // no space
138                 return true;
139         }
140         QChar const qc = ucs4_to_qchar(c);
141         return qc.isPrint() && !qc.isSpace();
142 }
143
144
145 bool isSpace(char_type c)
146 {
147         if (!is_utf16(c)) {
148                 // assume that no non-utf16 character is a space
149                 // c outside the UCS4 range is catched as well
150                 return false;
151         }
152         QChar const qc = ucs4_to_qchar(c);
153         return qc.isSpace();
154 }
155
156
157 bool isNumber(char_type c)
158 {
159         if (!is_utf16(c))
160                 // assume that no non-utf16 character is a numeral
161                 // c outside the UCS4 range is catched as well
162                 return false;
163         return ucs4_to_qchar(c).isNumber();
164 }
165
166
167 bool isCommonNumberSeparator(char_type c)
168 {
169         if (!is_utf16(c))
170                 // assume that no non-utf16 character is a numeral
171                 // c outside the UCS4 range is catched as well
172                 return false;
173         return ucs4_to_qchar(c).direction() == QChar::DirCS;
174 }
175
176
177 bool isEuropeanNumberTerminator(char_type c)
178 {
179         if (!is_utf16(c))
180                 // assume that no non-utf16 character is a numeral
181                 // c outside the UCS4 range is catched as well
182                 return false;
183         return ucs4_to_qchar(c).direction() == QChar::DirET;
184 }
185
186
187 bool isDigitASCII(char_type c)
188 {
189         return '0' <= c && c <= '9';
190 }
191
192
193 bool isAlnumASCII(char_type c)
194 {
195         return isAlphaASCII(c) || isDigitASCII(c);
196 }
197
198
199 bool isASCII(char_type c)
200 {
201         return c < 0x80;
202 }
203
204
205 bool isOpenPunctuation(char_type c)
206 {
207         if (!is_utf16(c)) {
208                 // assume that no non-utf16 character is an op
209                 // c outside the UCS4 range is catched as well
210                 return false;
211         }
212         QChar const qc = ucs4_to_qchar(c);
213         return qc.category() == QChar::Punctuation_Open;
214 }
215
216
217 namespace support {
218
219 int compare_no_case(docstring const & s, docstring const & s2)
220 {
221         docstring::const_iterator p = s.begin();
222         docstring::const_iterator p2 = s2.begin();
223
224         while (p != s.end() && p2 != s2.end()) {
225                 char_type const lc1 = lowercase(*p);
226                 char_type const lc2 = lowercase(*p2);
227                 if (lc1 != lc2)
228                         return (lc1 < lc2) ? -1 : 1;
229                 ++p;
230                 ++p2;
231         }
232
233         if (s.size() == s2.size())
234                 return 0;
235         if (s.size() < s2.size())
236                 return -1;
237         return 1;
238 }
239
240
241 int compare_locale(docstring const & s, docstring const & s2)
242 {
243         return QString::localeAwareCompare(toqstr(s), toqstr(s2));
244 }
245
246
247 namespace {
248
249 template<typename Char>
250 Char ascii_tolower(Char c) {
251         if (c >= 'A' && c <= 'Z')
252                 return c - 'A' + 'a';
253         return c;
254 }
255
256 } // namespace
257
258
259 int compare_ascii_no_case(string const & s, string const & s2)
260 {
261         string::const_iterator p = s.begin();
262         string::const_iterator p2 = s2.begin();
263
264         while (p != s.end() && p2 != s2.end()) {
265                 int const lc1 = ascii_tolower(*p);
266                 int const lc2 = ascii_tolower(*p2);
267                 if (lc1 != lc2)
268                         return (lc1 < lc2) ? -1 : 1;
269                 ++p;
270                 ++p2;
271         }
272
273         if (s.size() == s2.size())
274                 return 0;
275         if (s.size() < s2.size())
276                 return -1;
277         return 1;
278 }
279
280
281 int compare_ascii_no_case(docstring const & s, docstring const & s2)
282 {
283         docstring::const_iterator p = s.begin();
284         docstring::const_iterator p2 = s2.begin();
285
286         while (p != s.end() && p2 != s2.end()) {
287                 char_type const lc1 = ascii_tolower(*p);
288                 char_type const lc2 = ascii_tolower(*p2);
289                 if (lc1 != lc2)
290                         return (lc1 < lc2) ? -1 : 1;
291                 ++p;
292                 ++p2;
293         }
294
295         if (s.size() == s2.size())
296                 return 0;
297         if (s.size() < s2.size())
298                 return -1;
299         return 1;
300 }
301
302
303 bool isStrInt(string const & str)
304 {
305         if (str.empty())
306                 return false;
307
308         // Remove leading and trailing white space chars.
309         string const tmpstr = trim(str);
310         if (tmpstr.empty())
311                 return false;
312
313         string::const_iterator cit = tmpstr.begin();
314         if ((*cit) == '-')
315                 ++cit;
316
317         string::const_iterator end = tmpstr.end();
318         for (; cit != end; ++cit)
319                 if (!isDigitASCII(*cit))
320                         return false;
321
322         return true;
323 }
324
325
326 bool isStrUnsignedInt(string const & str)
327 {
328         if (str.empty())
329                 return false;
330
331         // Remove leading and trailing white space chars.
332         string const tmpstr = trim(str);
333         if (tmpstr.empty())
334                 return false;
335
336         string::const_iterator cit = tmpstr.begin();
337         string::const_iterator end = tmpstr.end();
338         for (; cit != end; ++cit)
339                 if (!isDigitASCII(*cit))
340                         return false;
341
342         return true;
343 }
344
345
346 bool isStrDbl(string const & str)
347 {
348         if (str.empty())
349                 return false;
350
351         // Remove leading and trailing white space chars.
352         string const tmpstr = trim(str);
353         if (tmpstr.empty())
354                 return false;
355         //      if (tmpstr.count('.') > 1) return false;
356
357         string::const_iterator cit = tmpstr.begin();
358         bool found_dot = false;
359         if (*cit == '-')
360                 ++cit;
361         string::const_iterator end = tmpstr.end();
362         for (; cit != end; ++cit) {
363                 if (!isDigitASCII(*cit) && *cit != '.')
364                         return false;
365                 if ('.' == (*cit)) {
366                         if (found_dot)
367                                 return false;
368                         found_dot = true;
369                 }
370         }
371         return true;
372 }
373
374
375 bool hasDigitASCII(docstring const & str)
376 {
377         docstring::const_iterator cit = str.begin();
378         docstring::const_iterator const end = str.end();
379         for (; cit != end; ++cit)
380                 if (isDigitASCII(*cit))
381                         return true;
382         return false;
383 }
384
385
386 bool isHexChar(char_type c)
387 {
388         return c == '0' ||
389                 c == '1' ||
390                 c == '2' ||
391                 c == '3' ||
392                 c == '4' ||
393                 c == '5' ||
394                 c == '6' ||
395                 c == '7' ||
396                 c == '8' ||
397                 c == '9' ||
398                 c == 'a' || c == 'A' ||
399                 c == 'b' || c == 'B' ||
400                 c == 'c' || c == 'C' ||
401                 c == 'd' || c == 'D' ||
402                 c == 'e' || c == 'E' ||
403                 c == 'f' || c == 'F';
404 }
405
406
407 bool isHex(docstring const & str)
408 {
409         int index = 0;
410
411         if (str.length() > 2 && str[0] == '0' &&
412             (str[1] == 'x' || str[1] == 'X'))
413                 index = 2;
414
415         int const len = str.length();
416
417         for (; index < len; ++index) {
418                 if (!isHexChar(str[index]))
419                         return false;
420         }
421         return true;
422 }
423
424
425 int hexToInt(docstring const & str)
426 {
427         string s = to_ascii(str);
428         int h;
429         sscanf(s.c_str(), "%x", &h);
430         return h;
431 }
432
433
434 bool isAscii(docstring const & str)
435 {
436         int const len = str.length();
437         for (int i = 0; i < len; ++i)
438                 if (str[i] >= 0x80)
439                         return false;
440         return true;
441 }
442
443
444 bool isAscii(string const & str)
445 {
446         int const len = str.length();
447         for (int i = 0; i < len; ++i)
448                 if (static_cast<unsigned char>(str[i]) >= 0x80)
449                         return false;
450         return true;
451 }
452
453
454 char lowercase(char c)
455 {
456         LASSERT(isASCII(c), return '?');
457         return char(tolower(c));
458 }
459
460
461 char uppercase(char c)
462 {
463         LASSERT(isASCII(c), return '?');
464         return char(toupper(c));
465 }
466
467
468 char_type lowercase(char_type c)
469 {
470         if (!is_utf16(c))
471                 // We don't know how to lowercase a non-utf16 char
472                 return c;
473         return qchar_to_ucs4(ucs4_to_qchar(c).toLower());
474 }
475
476
477 char_type uppercase(char_type c)
478 {
479         if (!is_utf16(c))
480                 // We don't know how to uppercase a non-utf16 char
481                 return c;
482         return qchar_to_ucs4(ucs4_to_qchar(c).toUpper());
483 }
484
485
486 bool isLowerCase(char_type ch) {
487         return lowercase(ch) == ch;
488 }
489
490
491 bool isUpperCase(char_type ch) {
492         return uppercase(ch) == ch;
493 }
494
495
496 namespace {
497
498 // since we cannot use tolower and toupper directly in the
499 // calls to transform yet, we use these helper clases. (Lgb)
500
501 struct local_lowercase {
502         char_type operator()(char_type c) const {
503                 return lowercase(c);
504         }
505 };
506
507 struct local_uppercase {
508         char_type operator()(char_type c) const {
509                 return uppercase(c);
510         }
511 };
512
513 template<typename Char> struct local_ascii_lowercase {
514         Char operator()(Char c) const { return ascii_tolower(c); }
515 };
516
517 } // namespace
518
519
520 docstring const lowercase(docstring const & a)
521 {
522         docstring tmp(a);
523         transform(tmp.begin(), tmp.end(), tmp.begin(), local_lowercase());
524         return tmp;
525 }
526
527
528 /* Uncomment here and in lstrings.h if you should need this.
529 string const lowercase(string const & a)
530 {
531         string tmp(a);
532         transform(tmp.begin(), tmp.end(), tmp.begin(), local_lowercase());
533         return tmp;
534 }
535 */
536
537
538 docstring const uppercase(docstring const & a)
539 {
540         docstring tmp(a);
541         transform(tmp.begin(), tmp.end(), tmp.begin(), local_uppercase());
542         return tmp;
543 }
544
545
546 string const ascii_lowercase(string const & a)
547 {
548         string tmp(a);
549         transform(tmp.begin(), tmp.end(), tmp.begin(),
550                   local_ascii_lowercase<char>());
551         return tmp;
552 }
553
554
555 docstring const ascii_lowercase(docstring const & a)
556 {
557         docstring tmp(a);
558         transform(tmp.begin(), tmp.end(), tmp.begin(),
559                   local_ascii_lowercase<char_type>());
560         return tmp;
561 }
562
563
564 char_type superscript(char_type c)
565 {
566         switch (c) {
567                 case    '2': return 0x00b2;
568                 case    '3': return 0x00b3;
569                 case    '1': return 0x00b9;
570                 case    '0': return 0x2070;
571                 case    'i': return 0x2071;
572                 case    '4': return 0x2074;
573                 case    '5': return 0x2075;
574                 case    '6': return 0x2076;
575                 case    '7': return 0x2077;
576                 case    '8': return 0x2078;
577                 case    '9': return 0x2079;
578                 case    '+': return 0x207a;
579                 case    '-': return 0x207b;
580                 case    '=': return 0x207c;
581                 case    '(': return 0x207d;
582                 case    ')': return 0x207e;
583                 case    'n': return 0x207f;
584                 case    'h': return 0x02b0;
585                 case 0x0266: return 0x02b1; // LATIN SMALL LETTER H WITH HOOK
586                 case    'j': return 0x02b2;
587                 case    'r': return 0x02b3;
588                 case 0x0279: return 0x02b4; // LATIN SMALL LETTER TURNED R
589                 case 0x027b: return 0x02b5; // LATIN SMALL LETTER TURNED R WITH HOOK
590                 case 0x0281: return 0x02b6; // LATIN SMALL LETTER CAPITAL INVERTED R
591                 case    'w': return 0x02b7;
592                 case    'y': return 0x02b8;
593 //              case 0x0294: return 0x02c0; // LATIN LETTER GLOTTAL STOP)
594 //              case 0x0295: return 0x02c1; // LATIN LETTER PHARYNGEAL VOICED FRICATIVE
595                                             // (= LATIN LETTER REVERSED GLOTTAL STOP)
596                 case    'l': return 0x02e1;
597                 case    's': return 0x02e2;
598                 case    'x': return 0x02e3;
599 //              case 0x0295: return 0x02e4; // LATIN SMALL LETTER REVERSED GLOTTAL STOP
600                 case    'A': return 0x1d2c;
601                 case 0x00c6: return 0x1d2d; // LATIN CAPITAL LETTER AE
602                 case    'B': return 0x1d2e;
603                 case    'D': return 0x1d30;
604                 case    'E': return 0x1d31;
605                 case    'G': return 0x1d33;
606                 case    'H': return 0x1d34;
607                 case    'I': return 0x1d35;
608                 case    'J': return 0x1d36;
609                 case    'K': return 0x1d37;
610                 case    'L': return 0x1d38;
611                 case    'M': return 0x1d39;
612                 case    'N': return 0x1d3a;
613                 case    'O': return 0x1d3c;
614                 case    'P': return 0x1d3e;
615                 case    'R': return 0x1d3f;
616                 case    'T': return 0x1d40;
617                 case    'U': return 0x1d41;
618                 case    'W': return 0x1d42;
619                 case    'a': return 0x1d43;
620                 case 0x0250: return 0x1d44; // LATIN SMALL LETTER TURNED A
621                 case 0x0251: return 0x1d45; // LATIN SMALL LETTER ALPHA
622                 case    'b': return 0x1d47;
623                 case    'd': return 0x1d48;
624                 case    'e': return 0x1d49;
625                 case 0x0259: return 0x1d4a; // LATIN SMALL LETTER SCHWA
626                 case 0x025b: return 0x1d4b; // LATIN SMALL LETTER OPEN E
627                 case 0x1d08: return 0x1d4c; // LATIN SMALL LETTER TURNED OPEN E
628                 case    'g': return 0x1d4d;
629                 case 0x1d09: return 0x1d4e; // LATIN SMALL LETTER TURNED I
630                 case    'k': return 0x1d4f;
631                 case    'm': return 0x1d50;
632                 case 0x014b: return 0x1d51; // LATIN SMALL LETTER ENG
633                 case    'o': return 0x1d52;
634                 case 0x0254: return 0x1d53; // LATIN SMALL LETTER OPEN O
635                 case 0x1d16: return 0x1d54; // LATIN SMALL LETTER TOP HALF O
636                 case 0x1d17: return 0x1d55; // LATIN SMALL LETTER BOTTOM HALF O
637                 case    'p': return 0x1d56;
638                 case    't': return 0x1d57;
639                 case    'u': return 0x1d58;
640                 case 0x1d1d: return 0x1d59; // LATIN SMALL LETTER SIDEWAYS U
641                 case 0x1d1f: return 0x1d5a; // LATIN SMALL LETTER SIDEWAYS TURNED M
642                 case    'v': return 0x1d5b;
643                 case 0x03b2: return 0x1d5d; // GREEK SMALL LETTER BETA
644                 case 0x03b3: return 0x1d5e; // GREEK SMALL LETTER GAMMA
645                 case 0x03b4: return 0x1d5f; // GREEK SMALL LETTER DELTA
646                 case 0x03c6: return 0x1d60; // GREEK SMALL LETTER PHI
647                 case 0x03c7: return 0x1d61; // GREEK SMALL LETTER CHI
648         }
649         return c;
650 }
651
652
653 char_type subscript(char_type c)
654 {
655         switch (c) {
656                 case    'i': return 0x1d62;
657                 case    'r': return 0x1d63;
658                 case    'u': return 0x1d64;
659                 case    'v': return 0x1d65;
660                 case 0x03b2: return 0x1d66; // GREEK SMALL LETTER BETA
661                 case 0x03b3: return 0x1d67; // GREEK SMALL LETTER GAMMA
662                 case 0x03c1: return 0x1d68; // GREEK SMALL LETTER RHO
663                 case 0x03c6: return 0x1d69; // GREEK SMALL LETTER PHI
664                 case 0x03c7: return 0x1d6a; // GREEK SMALL LETTER CHI
665                 case    '0': return 0x2080;
666                 case    '1': return 0x2081;
667                 case    '2': return 0x2082;
668                 case    '3': return 0x2083;
669                 case    '4': return 0x2084;
670                 case    '5': return 0x2085;
671                 case    '6': return 0x2086;
672                 case    '7': return 0x2087;
673                 case    '8': return 0x2088;
674                 case    '9': return 0x2089;
675                 case    '+': return 0x208a;
676                 case    '-': return 0x208b;
677                 case    '=': return 0x208c;
678                 case    '(': return 0x208d;
679                 case    ')': return 0x208e;
680                 case    'a': return 0x2090;
681                 case    'e': return 0x2091;
682                 case    'o': return 0x2092;
683                 case    'x': return 0x2093;
684                 case 0x0259: return 0x2093; // LATIN SMALL LETTER SCHWA
685         }
686         return c;
687 }
688
689
690 bool prefixIs(docstring const & a, char_type c)
691 {
692         if (a.empty())
693                 return false;
694         return a[0] == c;
695 }
696
697
698 bool prefixIs(string const & a, string const & pre)
699 {
700         size_t const prelen = pre.length();
701         size_t const alen = a.length();
702         return prelen <= alen && !a.empty() && a.compare(0, prelen, pre) == 0;
703 }
704
705
706 bool prefixIs(docstring const & a, docstring const & pre)
707 {
708         size_t const prelen = pre.length();
709         size_t const alen = a.length();
710         return prelen <= alen && !a.empty() && a.compare(0, prelen, pre) == 0;
711 }
712
713
714 bool suffixIs(string const & a, char c)
715 {
716         if (a.empty())
717                 return false;
718         return a[a.length() - 1] == c;
719 }
720
721
722 bool suffixIs(docstring const & a, char_type c)
723 {
724         if (a.empty())
725                 return false;
726         return a[a.length() - 1] == c;
727 }
728
729
730 bool suffixIs(string const & a, string const & suf)
731 {
732         size_t const suflen = suf.length();
733         size_t const alen = a.length();
734         return suflen <= alen && a.compare(alen - suflen, suflen, suf) == 0;
735 }
736
737
738 bool suffixIs(docstring const & a, docstring const & suf)
739 {
740         size_t const suflen = suf.length();
741         size_t const alen = a.length();
742         return suflen <= alen && a.compare(alen - suflen, suflen, suf) == 0;
743 }
744
745
746 bool containsOnly(string const & s, string const & cset)
747 {
748         return s.find_first_not_of(cset) == string::npos;
749 }
750
751
752 bool containsOnly(docstring const & s, string const & cset)
753 {
754         return s.find_first_not_of(from_ascii(cset)) == string::npos;
755 }
756
757
758 // ale970405+lasgoutt-970425
759 // rewritten to use new string (Lgb)
760 string const token(string const & a, char delim, int n)
761 {
762         if (a.empty())
763                 return string();
764
765         size_t k = 0;
766         size_t i = 0;
767
768         // Find delimiter or end of string
769         for (; n--;) {
770                 if ((i = a.find(delim, i)) == string::npos)
771                         break;
772                 else
773                         ++i; // step delim
774         }
775
776         // i is now the n'th delim (or string::npos)
777         if (i == string::npos)
778                 return string();
779
780         k = a.find(delim, i);
781         // k is now the n'th + 1 delim (or string::npos)
782
783         return a.substr(i, k - i);
784 }
785
786
787 docstring const token(docstring const & a, char_type delim, int n)
788 {
789         if (a.empty())
790                 return docstring();
791
792         size_t k = 0;
793         size_t i = 0;
794
795         // Find delimiter or end of string
796         for (; n--;) {
797                 if ((i = a.find(delim, i)) == docstring::npos)
798                         break;
799                 else
800                         ++i; // step delim
801         }
802
803         // i is now the n'th delim (or string::npos)
804         if (i == docstring::npos)
805                 return docstring();
806
807         k = a.find(delim, i);
808         // k is now the n'th + 1 delim (or string::npos)
809
810         return a.substr(i, k - i);
811 }
812
813
814 // this could probably be faster and/or cleaner, but it seems to work (JMarc)
815 // rewritten to use new string (Lgb)
816 int tokenPos(string const & a, char delim, string const & tok)
817 {
818         int i = 0;
819         string str = a;
820         string tmptok;
821
822         while (!str.empty()) {
823                 str = split(str, tmptok, delim);
824                 if (tok == tmptok)
825                         return i;
826                 ++i;
827         }
828         return -1;
829 }
830
831
832 // this could probably be faster and/or cleaner, but it seems to work (JMarc)
833 // rewritten to use new string (Lgb)
834 int tokenPos(docstring const & a, char_type delim, docstring const & tok)
835 {
836         int i = 0;
837         docstring str = a;
838         docstring tmptok;
839
840         while (!str.empty()) {
841                 str = split(str, tmptok, delim);
842                 if (tok == tmptok)
843                         return i;
844                 ++i;
845         }
846         return -1;
847 }
848
849
850 namespace {
851
852 /// Substitute all \a oldchar with \a newchar
853 template<typename Ch> inline
854 basic_string<Ch> const subst_char(basic_string<Ch> const & a,
855                 Ch oldchar, Ch newchar)
856 {
857         typedef basic_string<Ch> String;
858         String tmp(a);
859         typename String::iterator lit = tmp.begin();
860         typename String::iterator end = tmp.end();
861         for (; lit != end; ++lit)
862                 if ((*lit) == oldchar)
863                         (*lit) = newchar;
864         return tmp;
865 }
866
867
868 /// Substitute all \a oldchar with \a newchar
869 docstring const subst_char(docstring const & a,
870         docstring::value_type oldchar, docstring::value_type newchar)
871 {
872         docstring tmp(a);
873         docstring::iterator lit = tmp.begin();
874         docstring::iterator end = tmp.end();
875         for (; lit != end; ++lit)
876                 if ((*lit) == oldchar)
877                         (*lit) = newchar;
878         return tmp;
879 }
880
881
882 /// substitutes all instances of \a oldstr with \a newstr
883 template<typename String> inline
884 String const subst_string(String const & a,
885                 String const & oldstr, String const & newstr)
886 {
887         LASSERT(!oldstr.empty(), return a);
888         String lstr = a;
889         size_t i = 0;
890         size_t const olen = oldstr.length();
891         while ((i = lstr.find(oldstr, i)) != string::npos) {
892                 lstr.replace(i, olen, newstr);
893                 i += newstr.length(); // We need to be sure that we dont
894                 // use the same i over and over again.
895         }
896         return lstr;
897 }
898
899
900 docstring const subst_string(docstring const & a,
901                 docstring const & oldstr, docstring const & newstr)
902 {
903         LASSERT(!oldstr.empty(), return a);
904         docstring lstr = a;
905         size_t i = 0;
906         size_t const olen = oldstr.length();
907         while ((i = lstr.find(oldstr, i)) != string::npos) {
908                 lstr.replace(i, olen, newstr);
909                 i += newstr.length(); // We need to be sure that we dont
910                 // use the same i over and over again.
911         }
912         return lstr;
913 }
914
915 } // namespace
916
917
918 string const subst(string const & a, char oldchar, char newchar)
919 {
920         return subst_char(a, oldchar, newchar);
921 }
922
923
924 docstring const subst(docstring const & a,
925                 char_type oldchar, char_type newchar)
926 {
927         return subst_char(a, oldchar, newchar);
928 }
929
930
931 string const subst(string const & a,
932                 string const & oldstr, string const & newstr)
933 {
934         return subst_string(a, oldstr, newstr);
935 }
936
937
938 docstring const subst(docstring const & a,
939                 docstring const & oldstr, docstring const & newstr)
940 {
941         return subst_string(a, oldstr, newstr);
942 }
943
944
945 int count_char(string const & str, char chr)
946 {
947         int count = 0;
948         string::const_iterator lit = str.begin();
949         string::const_iterator end = str.end();
950         for (; lit != end; ++lit)
951                 if ((*lit) == chr)
952                         count++;
953         return count;
954 }
955
956
957 /// Count all occurrences of char \a chr inside \a str
958 int count_char(docstring const & str, docstring::value_type chr)
959 {
960         int count = 0;
961         docstring::const_iterator lit = str.begin();
962         docstring::const_iterator end = str.end();
963         for (; lit != end; ++lit)
964                 if ((*lit) == chr)
965                         count++;
966         return count;
967 }
968
969
970 int count_bin_chars(string const & str)
971 {
972         QString const qstr = toqstr(str).simplified();
973         int count = 0;
974         QString::const_iterator cit = qstr.begin();
975         QString::const_iterator end = qstr.end();
976         for (; cit != end; ++cit)  {
977                 switch (cit->category()) {
978                 case QChar::Separator_Line:
979                 case QChar::Separator_Paragraph:
980                 case QChar::Other_Control:
981                 case QChar::Other_Format:
982                 case QChar::Other_Surrogate:
983                 case QChar::Other_PrivateUse:
984                 case QChar::Other_NotAssigned:
985                         ++count;
986                         break;
987                 default:
988                         break;
989                 }
990         }
991         return count;
992 }
993
994
995 docstring const trim(docstring const & a, char const * p)
996 {
997         LASSERT(p, return a);
998
999         if (a.empty() || !*p)
1000                 return a;
1001
1002         docstring s = from_ascii(p);
1003         size_t r = a.find_last_not_of(s);
1004         size_t l = a.find_first_not_of(s);
1005
1006         // Is this the minimal test? (lgb)
1007         if (r == docstring::npos && l == docstring::npos)
1008                 return docstring();
1009
1010         return a.substr(l, r - l + 1);
1011 }
1012
1013
1014 string const trim(string const & a, char const * p)
1015 {
1016         LASSERT(p, return a);
1017
1018         if (a.empty() || !*p)
1019                 return a;
1020
1021         size_t r = a.find_last_not_of(p);
1022         size_t l = a.find_first_not_of(p);
1023
1024         // Is this the minimal test? (lgb)
1025         if (r == string::npos && l == string::npos)
1026                 return string();
1027
1028         return a.substr(l, r - l + 1);
1029 }
1030
1031
1032 string const rtrim(string const & a, char const * p)
1033 {
1034         LASSERT(p, return a);
1035
1036         if (a.empty() || !*p)
1037                 return a;
1038
1039         size_t r = a.find_last_not_of(p);
1040
1041         // Is this test really needed? (Lgb)
1042         if (r == string::npos)
1043                 return string();
1044
1045         return a.substr(0, r + 1);
1046 }
1047
1048
1049 docstring const rtrim(docstring const & a, char const * p)
1050 {
1051         LASSERT(p, return a);
1052
1053         if (a.empty() || !*p)
1054                 return a;
1055
1056         size_t r = a.find_last_not_of(from_ascii(p));
1057
1058         // Is this test really needed? (Lgb)
1059         if (r == docstring::npos)
1060                 return docstring();
1061
1062         return a.substr(0, r + 1);
1063 }
1064
1065
1066 string const ltrim(string const & a, char const * p)
1067 {
1068         LASSERT(p, return a);
1069         if (a.empty() || !*p)
1070                 return a;
1071         size_t l = a.find_first_not_of(p);
1072         if (l == string::npos)
1073                 return string();
1074         return a.substr(l, string::npos);
1075 }
1076
1077
1078 docstring const ltrim(docstring const & a, char const * p)
1079 {
1080         LASSERT(p, return a);
1081         if (a.empty() || !*p)
1082                 return a;
1083         size_t l = a.find_first_not_of(from_ascii(p));
1084         if (l == docstring::npos)
1085                 return docstring();
1086         return a.substr(l, docstring::npos);
1087 }
1088
1089 namespace {
1090
1091 template<typename String, typename Char> inline
1092 String const doSplit(String const & a, String & piece, Char delim)
1093 {
1094         String tmp;
1095         size_t i = a.find(delim);
1096         if (i == a.length() - 1) {
1097                 piece = a.substr(0, i);
1098         } else if (i == 0) {
1099                 piece.erase();
1100                 tmp = a.substr(i + 1);
1101         } else if (i != String::npos) {
1102                 piece = a.substr(0, i);
1103                 tmp = a.substr(i + 1);
1104         } else {
1105                 piece = a;
1106         }
1107         return tmp;
1108 }
1109
1110
1111 // FIXME: why is this specialization needed?
1112 template<typename Char> inline
1113 docstring const doSplit(docstring const & a, docstring & piece, Char delim)
1114 {
1115         docstring tmp;
1116         size_t i = a.find(delim);
1117         if (i == a.length() - 1) {
1118                 piece = a.substr(0, i);
1119         } else if (i == 0) {
1120                 piece.erase();
1121                 tmp = a.substr(i + 1);
1122         } else if (i != docstring::npos) {
1123                 piece = a.substr(0, i);
1124                 tmp = a.substr(i + 1);
1125         } else {
1126                 piece = a;
1127         }
1128         return tmp;
1129 }
1130
1131 } // namespace
1132
1133
1134 string const split(string const & a, string & piece, char delim)
1135 {
1136         return doSplit(a, piece, delim);
1137 }
1138
1139
1140 docstring const split(docstring const & a, docstring & piece, char_type delim)
1141 {
1142         return doSplit(a, piece, delim);
1143 }
1144
1145
1146 string const split(string const & a, char delim)
1147 {
1148         string tmp;
1149         size_t i = a.find(delim);
1150         if (i != string::npos) // found delim
1151                 tmp = a.substr(i + 1);
1152         return tmp;
1153 }
1154
1155
1156 // ale970521
1157 string const rsplit(string const & a, string & piece, char delim)
1158 {
1159         string tmp;
1160         size_t i = a.rfind(delim);
1161         if (i != string::npos) { // delimiter was found
1162                 piece = a.substr(0, i);
1163                 tmp = a.substr(i + 1);
1164         } else { // delimiter was not found
1165                 piece.erase();
1166         }
1167         return tmp;
1168 }
1169
1170
1171 docstring const rsplit(docstring const & a, docstring & piece, char_type delim)
1172 {
1173         docstring tmp;
1174         size_t i = a.rfind(delim);
1175         if (i != string::npos) { // delimiter was found
1176                 piece = a.substr(0, i);
1177                 tmp = a.substr(i + 1);
1178         } else { // delimiter was not found
1179                 piece.erase();
1180         }
1181         return tmp;
1182 }
1183
1184
1185 docstring const rsplit(docstring const & a, char_type delim)
1186 {
1187         docstring tmp;
1188         size_t i = a.rfind(delim);
1189         if (i != string::npos)
1190                 tmp = a.substr(i + 1);
1191         return tmp;
1192 }
1193
1194
1195 docstring const escape(docstring const & lab)
1196 {
1197         char_type hexdigit[16] = { '0', '1', '2', '3', '4', '5', '6', '7',
1198                                    '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
1199         docstring enc;
1200         for (size_t i = 0; i < lab.length(); ++i) {
1201                 char_type c = lab[i];
1202                 if (c >= 128 || c == '=' || c == '%' || c == '#' || c == '$'
1203                     || c == '}' || c == '{' || c == ']' || c == '[' || c == '&'
1204                     || c == '\\') {
1205                         // Although char_type is a 32 bit type we know that
1206                         // UCS4 occupies only 21 bits, so we don't need to
1207                         // encode bigger values. Test for 2^24 because we
1208                         // can encode that with the 6 hex digits that are
1209                         // needed for 21 bits anyway.
1210                         LASSERT(c < (1 << 24), continue);
1211                         enc += '=';
1212                         enc += hexdigit[(c>>20) & 15];
1213                         enc += hexdigit[(c>>16) & 15];
1214                         enc += hexdigit[(c>>12) & 15];
1215                         enc += hexdigit[(c>> 8) & 15];
1216                         enc += hexdigit[(c>> 4) & 15];
1217                         enc += hexdigit[ c      & 15];
1218                 } else {
1219                         enc += c;
1220                 }
1221         }
1222         return enc;
1223 }
1224
1225
1226 docstring const protectArgument(docstring & arg, char const l,
1227                           char const r)
1228 {
1229         if (contains(arg, l) || contains(arg, r))
1230                 // protect brackets
1231                 arg = '{' + arg + '}';
1232         return arg;
1233 }
1234
1235
1236 bool truncateWithEllipsis(docstring & str, size_t const len)
1237 {
1238         if (str.size() <= len)
1239                 return false;
1240         str.resize(len);
1241         if (len > 0)
1242                 str[len - 1] = 0x2026;// HORIZONTAL ELLIPSIS
1243         return true;
1244 }
1245
1246
1247 namespace {
1248
1249 // this doesn't check whether str is empty, so do that first.
1250 vector<docstring> wrapToVec(docstring const & str, int ind,
1251                             size_t const width)
1252 {
1253         docstring s = trim(str);
1254         if (s.empty())
1255                 return vector<docstring>();
1256
1257         docstring indent;
1258         if (ind < 0) {
1259                 indent.insert(0, -ind, ' ');
1260                 ind = 0;
1261         } else if (ind > 0)
1262                 s.insert(0, ind, ' ');
1263
1264         vector<docstring> retval;
1265         while (s.size() > width) {
1266                 // find the last space within the first 'width' chars
1267                 size_t const i = s.find_last_of(' ', width - 1);
1268                 if (i == docstring::npos || i <= size_t(ind)) {
1269                         // no space found
1270                         truncateWithEllipsis(s, width);
1271                         break;
1272                 }
1273                 retval.push_back(s.substr(0, i));
1274                 s = indent + s.substr(i);
1275                 ind = indent.size();
1276         }
1277         if (!s.empty())
1278                 retval.push_back(s);
1279         return retval;
1280 }
1281
1282 } // namespace
1283
1284
1285 docstring wrap(docstring const & str, int const ind, size_t const width)
1286 {
1287         docstring s = trim(str);
1288         if (s.empty())
1289                 return docstring();
1290
1291         vector<docstring> const svec = wrapToVec(str, ind, width);
1292         return getStringFromVector(svec, from_ascii("\n"));
1293 }
1294
1295
1296 docstring wrapParas(docstring const & str, int const indent,
1297                     size_t const width, size_t const maxlines)
1298 {
1299         if (str.empty())
1300                 return docstring();
1301
1302         vector<docstring> const pars = getVectorFromString(str, from_ascii("\n"), true);
1303         vector<docstring> retval;
1304
1305         vector<docstring>::const_iterator it = pars.begin();
1306         vector<docstring>::const_iterator const en = pars.end();
1307         for (; it != en; ++it) {
1308                 vector<docstring> tmp = wrapToVec(*it, indent, width);
1309                 size_t const nlines = tmp.size();
1310                 if (nlines == 0)
1311                         continue;
1312                 size_t const curlines = retval.size();
1313                 if (maxlines > 0 && curlines + nlines > maxlines) {
1314                         tmp.resize(maxlines - curlines);
1315                         docstring last = tmp.back();
1316                         size_t const lsize = last.size();
1317                         if (lsize > width - 1) {
1318                                 size_t const i = last.find_last_of(' ', width - 1);
1319                                 if (i == docstring::npos || i <= size_t(indent))
1320                                         // no space found
1321                                         truncateWithEllipsis(last, lsize);
1322                                 else
1323                                         truncateWithEllipsis(last, i);
1324                         } else
1325                                 last.push_back(0x2026);//HORIZONTAL ELLIPSIS
1326                         tmp.pop_back();
1327                         tmp.push_back(last);
1328                 }
1329                 retval.insert(retval.end(), tmp.begin(), tmp.end());
1330                 if (maxlines > 0 && retval.size() >= maxlines)
1331                         break;
1332         }
1333         return getStringFromVector(retval, from_ascii("\n"));
1334 }
1335
1336
1337 namespace {
1338
1339 template<typename String> vector<String> const
1340 getVectorFromStringT(String const & str, String const & delim,
1341                      bool keepempty, bool trimit)
1342 {
1343 // Lars would like this code to go, but for now his replacement (below)
1344 // doesn't fullfil the same function. I have, therefore, reactivated the
1345 // old code for now. Angus 11 Nov 2002.
1346 #if 1
1347         vector<String> vec;
1348         if (str.empty())
1349                 return vec;
1350         String keys = trimit ? rtrim(str) : str;
1351         while (true) {
1352                 size_t const idx = keys.find(delim);
1353                 if (idx == String::npos) {
1354                         vec.push_back(trimit ? ltrim(keys) : keys);
1355                         break;
1356                 }
1357                 String const key = trimit ?
1358                         trim(keys.substr(0, idx)) : keys.substr(0, idx);
1359                 if (!key.empty() || keepempty)
1360                         vec.push_back(key);
1361                 size_t const start = idx + delim.size();
1362                 keys = keys.substr(start);
1363         }
1364         return vec;
1365 #else
1366         typedef boost::char_separator<typename String::value_type> Separator;
1367         typedef boost::tokenizer<Separator, typename String::const_iterator, String> Tokenizer;
1368         Separator sep(delim.c_str());
1369         Tokenizer tokens(str, sep);
1370         return vector<String>(tokens.begin(), tokens.end());
1371 #endif
1372 }
1373
1374
1375 template<typename String> const String
1376         getStringFromVector(vector<String> const & vec, String const & delim)
1377 {
1378         String str;
1379         typename vector<String>::const_iterator it = vec.begin();
1380         typename vector<String>::const_iterator en = vec.end();
1381         for (; it != en; ++it) {
1382                 String item = trim(*it);
1383                 if (item.empty())
1384                         continue;
1385                 if (!str.empty())
1386                         str += delim;
1387                 str += item;
1388         }
1389         return str;
1390 }
1391
1392 } // namespace
1393
1394
1395 vector<string> const getVectorFromString(string const & str,
1396         string const & delim, bool keepempty, bool trimit)
1397 {
1398         return getVectorFromStringT<string>(str, delim, keepempty, trimit);
1399 }
1400
1401
1402 vector<docstring> const getVectorFromString(docstring const & str,
1403         docstring const & delim, bool keepempty, bool trimit)
1404 {
1405         return getVectorFromStringT<docstring>(str, delim, keepempty, trimit);
1406 }
1407
1408
1409 string const getStringFromVector(vector<string> const & vec,
1410                                  string const & delim)
1411 {
1412         return getStringFromVector<string>(vec, delim);
1413 }
1414
1415
1416 docstring const getStringFromVector(vector<docstring> const & vec,
1417                                     docstring const & delim)
1418 {
1419         return getStringFromVector<docstring>(vec, delim);
1420 }
1421
1422
1423 int findToken(char const * const str[], string const & search_token)
1424 {
1425         int i = 0;
1426
1427         while (str[i][0] && str[i] != search_token)
1428                 ++i;
1429         if (!str[i][0])
1430                 i = -1;
1431         return i;
1432 }
1433
1434
1435 std::string formatFPNumber(double x)
1436 {
1437         // Need manual tweaking, QString::number(x, 'f', 16) does not work either
1438         ostringstream os;
1439         os << std::fixed;
1440         // Prevent outputs of 23.4200000000000017 but output small numbers
1441         // with at least 6 significant digits.
1442         double const logarithm = log10(fabs(x));
1443         os << std::setprecision(max(6 - iround(logarithm), 0)) << x;
1444         string result = os.str();
1445         if (result.find('.') != string::npos) {
1446                 result = rtrim(result, "0");
1447                 if (result[result.length()-1] == '.')
1448                         result = rtrim(result, ".");
1449         }
1450         return result;
1451 }
1452
1453
1454 docstring to_percent_encoding(docstring const & in, docstring const & ex)
1455 {
1456         QByteArray input = toqstr(in).toUtf8();
1457         QByteArray excludes = toqstr(ex).toUtf8();
1458         return qstring_to_ucs4(QString(input.toPercentEncoding(excludes)));
1459 }
1460
1461
1462 docstring bformat(docstring const & fmt, int arg1)
1463 {
1464         LATTEST(contains(fmt, from_ascii("%1$d")));
1465         docstring const str = subst(fmt, from_ascii("%1$d"), convert<docstring>(arg1));
1466         return subst(str, from_ascii("%%"), from_ascii("%"));
1467 }
1468
1469
1470 docstring bformat(docstring const & fmt, long arg1)
1471 {
1472         LATTEST(contains(fmt, from_ascii("%1$d")));
1473         docstring const str = subst(fmt, from_ascii("%1$d"), convert<docstring>(arg1));
1474         return subst(str, from_ascii("%%"), from_ascii("%"));
1475 }
1476
1477
1478 #ifdef LYX_USE_LONG_LONG
1479 docstring bformat(docstring const & fmt, long long arg1)
1480 {
1481         LATTEST(contains(fmt, from_ascii("%1$d")));
1482         docstring const str = subst(fmt, from_ascii("%1$d"), convert<docstring>(arg1));
1483         return subst(str, from_ascii("%%"), from_ascii("%"));
1484 }
1485 #endif
1486
1487
1488 docstring bformat(docstring const & fmt, unsigned int arg1)
1489 {
1490         LATTEST(contains(fmt, from_ascii("%1$d")));
1491         docstring const str = subst(fmt, from_ascii("%1$d"), convert<docstring>(arg1));
1492         return subst(str, from_ascii("%%"), from_ascii("%"));
1493 }
1494
1495
1496 docstring bformat(docstring const & fmt, docstring const & arg1)
1497 {
1498         LATTEST(contains(fmt, from_ascii("%1$s")));
1499         docstring const str = subst(fmt, from_ascii("%1$s"), arg1);
1500         return subst(str, from_ascii("%%"), from_ascii("%"));
1501 }
1502
1503
1504 docstring bformat(docstring const & fmt, char * arg1)
1505 {
1506         LATTEST(contains(fmt, from_ascii("%1$s")));
1507         docstring const str = subst(fmt, from_ascii("%1$s"), from_ascii(arg1));
1508         return subst(str, from_ascii("%%"), from_ascii("%"));
1509 }
1510
1511
1512 docstring bformat(docstring const & fmt, docstring const & arg1, docstring const & arg2)
1513 {
1514         LATTEST(contains(fmt, from_ascii("%1$s")));
1515         LATTEST(contains(fmt, from_ascii("%2$s")));
1516         docstring str = subst(fmt, from_ascii("%1$s"), arg1);
1517         str = subst(str, from_ascii("%2$s"), arg2);
1518         return subst(str, from_ascii("%%"), from_ascii("%"));
1519 }
1520
1521
1522 docstring bformat(docstring const & fmt, docstring const & arg1, int arg2)
1523 {
1524         LATTEST(contains(fmt, from_ascii("%1$s")));
1525         LATTEST(contains(fmt, from_ascii("%2$d")));
1526         docstring str = subst(fmt, from_ascii("%1$s"), arg1);
1527         str = subst(str, from_ascii("%2$d"), convert<docstring>(arg2));
1528         return subst(str, from_ascii("%%"), from_ascii("%"));
1529 }
1530
1531
1532 docstring bformat(docstring const & fmt, char const * arg1, docstring const & arg2)
1533 {
1534         LATTEST(contains(fmt, from_ascii("%1$s")));
1535         LATTEST(contains(fmt, from_ascii("%2$s")));
1536         docstring str = subst(fmt, from_ascii("%1$s"), from_ascii(arg1));
1537         str = subst(str, from_ascii("%2$s"), arg2);
1538         return subst(str, from_ascii("%%"), from_ascii("%"));
1539 }
1540
1541
1542 docstring bformat(docstring const & fmt, int arg1, int arg2)
1543 {
1544         LATTEST(contains(fmt, from_ascii("%1$d")));
1545         LATTEST(contains(fmt, from_ascii("%2$d")));
1546         docstring str = subst(fmt, from_ascii("%1$d"), convert<docstring>(arg1));
1547         str = subst(str, from_ascii("%2$d"), convert<docstring>(arg2));
1548         return subst(str, from_ascii("%%"), from_ascii("%"));
1549 }
1550
1551
1552 docstring bformat(docstring const & fmt, docstring const & arg1, docstring const & arg2, docstring const & arg3)
1553 {
1554         LATTEST(contains(fmt, from_ascii("%1$s")));
1555         LATTEST(contains(fmt, from_ascii("%2$s")));
1556         LATTEST(contains(fmt, from_ascii("%3$s")));
1557         docstring str = subst(fmt, from_ascii("%1$s"), arg1);
1558         str = subst(str, from_ascii("%2$s"), arg2);
1559         str = subst(str, from_ascii("%3$s"), arg3);
1560         return subst(str, from_ascii("%%"), from_ascii("%"));
1561 }
1562
1563
1564 docstring bformat(docstring const & fmt,
1565                docstring const & arg1, docstring const & arg2, docstring const & arg3, docstring const & arg4)
1566 {
1567         LATTEST(contains(fmt, from_ascii("%1$s")));
1568         LATTEST(contains(fmt, from_ascii("%2$s")));
1569         LATTEST(contains(fmt, from_ascii("%3$s")));
1570         LATTEST(contains(fmt, from_ascii("%4$s")));
1571         docstring str = subst(fmt, from_ascii("%1$s"), arg1);
1572         str = subst(str, from_ascii("%2$s"), arg2);
1573         str = subst(str, from_ascii("%3$s"), arg3);
1574         str = subst(str, from_ascii("%4$s"), arg4);
1575         return subst(str, from_ascii("%%"), from_ascii("%"));
1576 }
1577
1578 } // namespace support
1579 } // namespace lyx