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