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