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