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