]> git.lyx.org Git - lyx.git/blob - src/support/lstrings.cpp
656f82ee1119b7010d0f41f5b350304077efec60
[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 const 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 const 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 /* Uncomment here and in lstrings.h if you should need this.
485 string const lowercase(string const & a)
486 {
487         string tmp(a);
488         transform(tmp.begin(), tmp.end(), tmp.begin(), local_lowercase());
489         return tmp;
490 }
491 */
492
493
494 docstring const uppercase(docstring const & a)
495 {
496         docstring tmp(a);
497         transform(tmp.begin(), tmp.end(), tmp.begin(), local_uppercase());
498         return tmp;
499 }
500
501
502 string const ascii_lowercase(string const & a)
503 {
504         string tmp(a);
505         transform(tmp.begin(), tmp.end(), tmp.begin(),
506                   local_ascii_lowercase<char>());
507         return tmp;
508 }
509
510
511 docstring const ascii_lowercase(docstring const & a)
512 {
513         docstring tmp(a);
514         transform(tmp.begin(), tmp.end(), tmp.begin(),
515                   local_ascii_lowercase<char_type>());
516         return tmp;
517 }
518
519
520 char_type superscript(char_type c)
521 {
522         switch (c) {
523                 case    '2': return 0x00b2;
524                 case    '3': return 0x00b3;
525                 case    '1': return 0x00b9;
526                 case    '0': return 0x2070;
527                 case    'i': return 0x2071;
528                 case    '4': return 0x2074;
529                 case    '5': return 0x2075;
530                 case    '6': return 0x2076;
531                 case    '7': return 0x2077;
532                 case    '8': return 0x2078;
533                 case    '9': return 0x2079;
534                 case    '+': return 0x207a;
535                 case    '-': return 0x207b;
536                 case    '=': return 0x207c;
537                 case    '(': return 0x207d;
538                 case    ')': return 0x207e;
539                 case    'n': return 0x207f;
540                 case    'h': return 0x02b0;
541                 case 0x0266: return 0x02b1; // LATIN SMALL LETTER H WITH HOOK
542                 case    'j': return 0x02b2;
543                 case    'r': return 0x02b3;
544                 case 0x0279: return 0x02b4; // LATIN SMALL LETTER TURNED R
545                 case 0x027b: return 0x02b5; // LATIN SMALL LETTER TURNED R WITH HOOK
546                 case 0x0281: return 0x02b6; // LATIN SMALL LETTER CAPITAL INVERTED R
547                 case    'w': return 0x02b7;
548                 case    'y': return 0x02b8;
549 //              case 0x0294: return 0x02c0; // LATIN LETTER GLOTTAL STOP)
550 //              case 0x0295: return 0x02c1; // LATIN LETTER PHARYNGEAL VOICED FRICATIVE
551                                             // (= LATIN LETTER REVERSED GLOTTAL STOP)
552                 case    'l': return 0x02e1;
553                 case    's': return 0x02e2;
554                 case    'x': return 0x02e3;
555 //              case 0x0295: return 0x02e4; // LATIN SMALL LETTER REVERSED GLOTTAL STOP
556                 case    'A': return 0x1d2c;
557                 case 0x00c6: return 0x1d2d; // LATIN CAPITAL LETTER AE
558                 case    'B': return 0x1d2e;
559                 case    'D': return 0x1d30;
560                 case    'E': return 0x1d31;
561                 case    'G': return 0x1d33;
562                 case    'H': return 0x1d34;
563                 case    'I': return 0x1d35;
564                 case    'J': return 0x1d36;
565                 case    'K': return 0x1d37;
566                 case    'L': return 0x1d38;
567                 case    'M': return 0x1d39;
568                 case    'N': return 0x1d3a;
569                 case    'O': return 0x1d3c;
570                 case    'P': return 0x1d3e;
571                 case    'R': return 0x1d3f;
572                 case    'T': return 0x1d40;
573                 case    'U': return 0x1d41;
574                 case    'W': return 0x1d42;
575                 case    'a': return 0x1d43;
576                 case 0x0250: return 0x1d44; // LATIN SMALL LETTER TURNED A
577                 case 0x0251: return 0x1d45; // LATIN SMALL LETTER ALPHA
578                 case    'b': return 0x1d47;
579                 case    'd': return 0x1d48;
580                 case    'e': return 0x1d49;
581                 case 0x0259: return 0x1d4a; // LATIN SMALL LETTER SCHWA
582                 case 0x025b: return 0x1d4b; // LATIN SMALL LETTER OPEN E
583                 case 0x1d08: return 0x1d4c; // LATIN SMALL LETTER TURNED OPEN E
584                 case    'g': return 0x1d4d;
585                 case 0x1d09: return 0x1d4e; // LATIN SMALL LETTER TURNED I
586                 case    'k': return 0x1d4f;
587                 case    'm': return 0x1d50;
588                 case 0x014b: return 0x1d51; // LATIN SMALL LETTER ENG
589                 case    'o': return 0x1d52;
590                 case 0x0254: return 0x1d53; // LATIN SMALL LETTER OPEN O
591                 case 0x1d16: return 0x1d54; // LATIN SMALL LETTER TOP HALF O
592                 case 0x1d17: return 0x1d55; // LATIN SMALL LETTER BOTTOM HALF O
593                 case    'p': return 0x1d56;
594                 case    't': return 0x1d57;
595                 case    'u': return 0x1d58;
596                 case 0x1d1d: return 0x1d59; // LATIN SMALL LETTER SIDEWAYS U
597                 case 0x1d1f: return 0x1d5a; // LATIN SMALL LETTER SIDEWAYS TURNED M
598                 case    'v': return 0x1d5b;
599                 case 0x03b2: return 0x1d5d; // GREEK SMALL LETTER BETA
600                 case 0x03b3: return 0x1d5e; // GREEK SMALL LETTER GAMMA
601                 case 0x03b4: return 0x1d5f; // GREEK SMALL LETTER DELTA
602                 case 0x03c6: return 0x1d60; // GREEK SMALL LETTER PHI
603                 case 0x03c7: return 0x1d61; // GREEK SMALL LETTER CHI
604         }
605         return c;
606 }
607
608
609 char_type subscript(char_type c)
610 {
611         switch (c) {
612                 case    'i': return 0x1d62;
613                 case    'r': return 0x1d63;
614                 case    'u': return 0x1d64;
615                 case    'v': return 0x1d65;
616                 case 0x03b2: return 0x1d66; // GREEK SMALL LETTER BETA
617                 case 0x03b3: return 0x1d67; // GREEK SMALL LETTER GAMMA
618                 case 0x03c1: return 0x1d68; // GREEK SMALL LETTER RHO
619                 case 0x03c6: return 0x1d69; // GREEK SMALL LETTER PHI
620                 case 0x03c7: return 0x1d6a; // GREEK SMALL LETTER CHI
621                 case    '0': return 0x2080;
622                 case    '1': return 0x2081;
623                 case    '2': return 0x2082;
624                 case    '3': return 0x2083;
625                 case    '4': return 0x2084;
626                 case    '5': return 0x2085;
627                 case    '6': return 0x2086;
628                 case    '7': return 0x2087;
629                 case    '8': return 0x2088;
630                 case    '9': return 0x2089;
631                 case    '+': return 0x208a;
632                 case    '-': return 0x208b;
633                 case    '=': return 0x208c;
634                 case    '(': return 0x208d;
635                 case    ')': return 0x208e;
636                 case    'a': return 0x2090;
637                 case    'e': return 0x2091;
638                 case    'o': return 0x2092;
639                 case    'x': return 0x2093;
640                 case 0x0259: return 0x2093; // LATIN SMALL LETTER SCHWA
641         }
642         return c;
643 }
644
645
646 bool prefixIs(docstring const & a, char_type c)
647 {
648         if (a.empty())
649                 return false;
650         return a[0] == c;
651 }
652
653
654 bool prefixIs(string const & a, string const & pre)
655 {
656         size_t const prelen = pre.length();
657         size_t const alen = a.length();
658         return prelen <= alen && !a.empty() && a.compare(0, prelen, pre) == 0;
659 }
660
661
662 bool prefixIs(docstring const & a, docstring const & pre)
663 {
664         size_t const prelen = pre.length();
665         size_t const alen = a.length();
666         return prelen <= alen && !a.empty() && a.compare(0, prelen, pre) == 0;
667 }
668
669
670 bool suffixIs(string const & a, char c)
671 {
672         if (a.empty())
673                 return false;
674         return a[a.length() - 1] == c;
675 }
676
677
678 bool suffixIs(docstring const & a, char_type c)
679 {
680         if (a.empty())
681                 return false;
682         return a[a.length() - 1] == c;
683 }
684
685
686 bool suffixIs(string const & a, string const & suf)
687 {
688         size_t const suflen = suf.length();
689         size_t const alen = a.length();
690         return suflen <= alen && a.compare(alen - suflen, suflen, suf) == 0;
691 }
692
693
694 bool suffixIs(docstring const & a, docstring const & suf)
695 {
696         size_t const suflen = suf.length();
697         size_t const alen = a.length();
698         return suflen <= alen && a.compare(alen - suflen, suflen, suf) == 0;
699 }
700
701
702 bool containsOnly(string const & s, string const & cset)
703 {
704         return s.find_first_not_of(cset) == string::npos;
705 }
706
707
708 // ale970405+lasgoutt-970425
709 // rewritten to use new string (Lgb)
710 string const token(string const & a, char delim, int n)
711 {
712         if (a.empty())
713                 return string();
714
715         size_t k = 0;
716         size_t i = 0;
717
718         // Find delimiter or end of string
719         for (; n--;) {
720                 if ((i = a.find(delim, i)) == string::npos)
721                         break;
722                 else
723                         ++i; // step delim
724         }
725
726         // i is now the n'th delim (or string::npos)
727         if (i == string::npos)
728                 return string();
729
730         k = a.find(delim, i);
731         // k is now the n'th + 1 delim (or string::npos)
732
733         return a.substr(i, k - i);
734 }
735
736
737 docstring const token(docstring const & a, char_type delim, int n)
738 {
739         if (a.empty())
740                 return docstring();
741
742         size_t k = 0;
743         size_t i = 0;
744
745         // Find delimiter or end of string
746         for (; n--;) {
747                 if ((i = a.find(delim, i)) == docstring::npos)
748                         break;
749                 else
750                         ++i; // step delim
751         }
752
753         // i is now the n'th delim (or string::npos)
754         if (i == docstring::npos)
755                 return docstring();
756
757         k = a.find(delim, i);
758         // k is now the n'th + 1 delim (or string::npos)
759
760         return a.substr(i, k - i);
761 }
762
763
764 // this could probably be faster and/or cleaner, but it seems to work (JMarc)
765 // rewritten to use new string (Lgb)
766 int tokenPos(string const & a, char delim, string const & tok)
767 {
768         int i = 0;
769         string str = a;
770         string tmptok;
771
772         while (!str.empty()) {
773                 str = split(str, tmptok, delim);
774                 if (tok == tmptok)
775                         return i;
776                 ++i;
777         }
778         return -1;
779 }
780
781
782 // this could probably be faster and/or cleaner, but it seems to work (JMarc)
783 // rewritten to use new string (Lgb)
784 int tokenPos(docstring const & a, char_type delim, docstring const & tok)
785 {
786         int i = 0;
787         docstring str = a;
788         docstring tmptok;
789
790         while (!str.empty()) {
791                 str = split(str, tmptok, delim);
792                 if (tok == tmptok)
793                         return i;
794                 ++i;
795         }
796         return -1;
797 }
798
799
800 namespace {
801
802 /// Substitute all \a oldchar with \a newchar
803 template<typename Ch> inline
804 basic_string<Ch> const subst_char(basic_string<Ch> const & a,
805                 Ch oldchar, Ch newchar)
806 {
807         typedef basic_string<Ch> String;
808         String tmp(a);
809         typename String::iterator lit = tmp.begin();
810         typename String::iterator end = tmp.end();
811         for (; lit != end; ++lit)
812                 if ((*lit) == oldchar)
813                         (*lit) = newchar;
814         return tmp;
815 }
816
817
818 /// Substitute all \a oldchar with \a newchar
819 docstring const subst_char(docstring const & a,
820         docstring::value_type oldchar, docstring::value_type newchar)
821 {
822         docstring tmp(a);
823         docstring::iterator lit = tmp.begin();
824         docstring::iterator end = tmp.end();
825         for (; lit != end; ++lit)
826                 if ((*lit) == oldchar)
827                         (*lit) = newchar;
828         return tmp;
829 }
830
831
832 /// substitutes all instances of \a oldstr with \a newstr
833 template<typename String> inline
834 String const subst_string(String const & a,
835                 String const & oldstr, String const & newstr)
836 {
837         LASSERT(!oldstr.empty(), return a);
838         String lstr = a;
839         size_t i = 0;
840         size_t const olen = oldstr.length();
841         while ((i = lstr.find(oldstr, i)) != string::npos) {
842                 lstr.replace(i, olen, newstr);
843                 i += newstr.length(); // We need to be sure that we dont
844                 // use the same i over and over again.
845         }
846         return lstr;
847 }
848
849
850 docstring const subst_string(docstring const & a,
851                 docstring const & oldstr, docstring const & newstr)
852 {
853         LASSERT(!oldstr.empty(), return a);
854         docstring lstr = a;
855         size_t i = 0;
856         size_t const olen = oldstr.length();
857         while ((i = lstr.find(oldstr, i)) != string::npos) {
858                 lstr.replace(i, olen, newstr);
859                 i += newstr.length(); // We need to be sure that we dont
860                 // use the same i over and over again.
861         }
862         return lstr;
863 }
864
865 }
866
867
868 string const subst(string const & a, char oldchar, char newchar)
869 {
870         return subst_char(a, oldchar, newchar);
871 }
872
873
874 docstring const subst(docstring const & a,
875                 char_type oldchar, char_type newchar)
876 {
877         return subst_char(a, oldchar, newchar);
878 }
879
880
881 string const subst(string const & a,
882                 string const & oldstr, string const & newstr)
883 {
884         return subst_string(a, oldstr, newstr);
885 }
886
887
888 docstring const subst(docstring const & a,
889                 docstring const & oldstr, docstring const & newstr)
890 {
891         return subst_string(a, oldstr, newstr);
892 }
893
894
895 int count_char(string const & str, char chr)
896 {
897         int count = 0;
898         string::const_iterator lit = str.begin();
899         string::const_iterator end = str.end();
900         for (; lit != end; ++lit)
901                 if ((*lit) == chr)
902                         count++;
903         return count;
904 }
905
906
907 /// Count all occurences of char \a chr inside \a str
908 int count_char(docstring const & str, docstring::value_type chr)
909 {
910         int count = 0;
911         docstring::const_iterator lit = str.begin();
912         docstring::const_iterator end = str.end();
913         for (; lit != end; ++lit)
914                 if ((*lit) == chr)
915                         count++;
916         return count;
917 }
918
919
920 docstring const trim(docstring const & a, char const * p)
921 {
922         LASSERT(p, return a);
923
924         if (a.empty() || !*p)
925                 return a;
926
927         docstring s = from_ascii(p);
928         size_t r = a.find_last_not_of(s);
929         size_t l = a.find_first_not_of(s);
930
931         // Is this the minimal test? (lgb)
932         if (r == docstring::npos && l == docstring::npos)
933                 return docstring();
934
935         return a.substr(l, r - l + 1);
936 }
937
938
939 string const trim(string const & a, char const * p)
940 {
941         LASSERT(p, return a);
942
943         if (a.empty() || !*p)
944                 return a;
945
946         size_t r = a.find_last_not_of(p);
947         size_t l = a.find_first_not_of(p);
948
949         // Is this the minimal test? (lgb)
950         if (r == string::npos && l == string::npos)
951                 return string();
952
953         return a.substr(l, r - l + 1);
954 }
955
956
957 string const rtrim(string const & a, char const * p)
958 {
959         LASSERT(p, return a);
960
961         if (a.empty() || !*p)
962                 return a;
963
964         size_t r = a.find_last_not_of(p);
965
966         // Is this test really needed? (Lgb)
967         if (r == string::npos)
968                 return string();
969
970         return a.substr(0, r + 1);
971 }
972
973
974 docstring const rtrim(docstring const & a, char const * p)
975 {
976         LASSERT(p, return a);
977
978         if (a.empty() || !*p)
979                 return a;
980
981         size_t r = a.find_last_not_of(from_ascii(p));
982
983         // Is this test really needed? (Lgb)
984         if (r == docstring::npos)
985                 return docstring();
986
987         return a.substr(0, r + 1);
988 }
989
990
991 string const ltrim(string const & a, char const * p)
992 {
993         LASSERT(p, return a);
994         if (a.empty() || !*p)
995                 return a;
996         size_t l = a.find_first_not_of(p);
997         if (l == string::npos)
998                 return string();
999         return a.substr(l, string::npos);
1000 }
1001
1002
1003 docstring const ltrim(docstring const & a, char const * p)
1004 {
1005         LASSERT(p, return a);
1006         if (a.empty() || !*p)
1007                 return a;
1008         size_t l = a.find_first_not_of(from_ascii(p));
1009         if (l == docstring::npos)
1010                 return docstring();
1011         return a.substr(l, docstring::npos);
1012 }
1013
1014 namespace {
1015
1016 template<typename String, typename Char> inline
1017 String const doSplit(String const & a, String & piece, Char delim)
1018 {
1019         String tmp;
1020         size_t i = a.find(delim);
1021         if (i == a.length() - 1) {
1022                 piece = a.substr(0, i);
1023         } else if (i != String::npos) {
1024                 piece = a.substr(0, i);
1025                 tmp = a.substr(i + 1);
1026         } else if (i == 0) {
1027                 piece.erase();
1028                 tmp = a.substr(i + 1);
1029         } else {
1030                 piece = a;
1031         }
1032         return tmp;
1033 }
1034
1035 template<typename Char> inline
1036 docstring const doSplit(docstring const & a, docstring & piece, Char delim)
1037 {
1038         docstring tmp;
1039         size_t i = a.find(delim);
1040         if (i == a.length() - 1) {
1041                 piece = a.substr(0, i);
1042         } else if (i != docstring::npos) {
1043                 piece = a.substr(0, i);
1044                 tmp = a.substr(i + 1);
1045         } else if (i == 0) {
1046                 piece.erase();
1047                 tmp = a.substr(i + 1);
1048         } else {
1049                 piece = a;
1050         }
1051         return tmp;
1052 }
1053
1054 } // anon
1055
1056
1057 string const split(string const & a, string & piece, char delim)
1058 {
1059         return doSplit(a, piece, delim);
1060 }
1061
1062
1063 docstring const split(docstring const & a, docstring & piece, char_type delim)
1064 {
1065         return doSplit(a, piece, delim);
1066 }
1067
1068
1069 string const split(string const & a, char delim)
1070 {
1071         string tmp;
1072         size_t i = a.find(delim);
1073         if (i != string::npos) // found delim
1074                 tmp = a.substr(i + 1);
1075         return tmp;
1076 }
1077
1078
1079 // ale970521
1080 string const rsplit(string const & a, string & piece, char delim)
1081 {
1082         string tmp;
1083         size_t i = a.rfind(delim);
1084         if (i != string::npos) { // delimiter was found
1085                 piece = a.substr(0, i);
1086                 tmp = a.substr(i + 1);
1087         } else { // delimiter was not found
1088                 piece.erase();
1089         }
1090         return tmp;
1091 }
1092
1093
1094 docstring const rsplit(docstring const & a, docstring & piece, char_type delim)
1095 {
1096         docstring tmp;
1097         size_t i = a.rfind(delim);
1098         if (i != string::npos) { // delimiter was found
1099                 piece = a.substr(0, i);
1100                 tmp = a.substr(i + 1);
1101         } else { // delimiter was not found
1102                 piece.erase();
1103         }
1104         return tmp;
1105 }
1106
1107
1108 docstring const rsplit(docstring const & a, char_type delim)
1109 {
1110         docstring tmp;
1111         size_t i = a.rfind(delim);
1112         if (i != string::npos)
1113                 tmp = a.substr(i + 1);
1114         return tmp;
1115 }
1116
1117
1118 docstring const escape(docstring const & lab)
1119 {
1120         char_type hexdigit[16] = { '0', '1', '2', '3', '4', '5', '6', '7',
1121                                    '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
1122         docstring enc;
1123         for (size_t i = 0; i < lab.length(); ++i) {
1124                 char_type c = lab[i];
1125                 if (c >= 128 || c == '=' || c == '%' || c == '#' || c == '$'
1126                     || c == '}' || c == '{' || c == ']' || c == '[' || c == '&') {
1127                         // Although char_type is a 32 bit type we know that
1128                         // UCS4 occupies only 21 bits, so we don't need to
1129                         // encode bigger values. Test for 2^24 because we
1130                         // can encode that with the 6 hex digits that are
1131                         // needed for 21 bits anyway.
1132                         LASSERT(c < (1 << 24), continue);
1133                         enc += '=';
1134                         enc += hexdigit[(c>>20) & 15];
1135                         enc += hexdigit[(c>>16) & 15];
1136                         enc += hexdigit[(c>>12) & 15];
1137                         enc += hexdigit[(c>> 8) & 15];
1138                         enc += hexdigit[(c>> 4) & 15];
1139                         enc += hexdigit[ c      & 15];
1140                 } else {
1141                         enc += c;
1142                 }
1143         }
1144         return enc;
1145 }
1146
1147
1148 namespace {
1149
1150 // this doesn't check whether str is empty, so do that first.
1151 vector<docstring> wrapToVec(docstring const & str, int ind,
1152                             size_t const width)
1153 {
1154         docstring s = trim(str);
1155         if (s.empty())
1156                 return vector<docstring>();
1157
1158         docstring indent;
1159         if (ind < 0) {
1160                 indent.insert(0, -ind, ' ');
1161                 ind = 0;
1162         } else if (ind > 0)
1163                 s.insert(0, ind, ' ');
1164
1165         vector<docstring> retval;
1166         while (s.size() > width) {
1167                 // find the last space within the first 'width' chars
1168                 size_t const i = s.find_last_of(' ', width - 1);
1169                 if (i == docstring::npos || i <= size_t(ind)) {
1170                         // no space found
1171                         s = s.substr(0, width - 3) + "...";
1172                         break;
1173                 }
1174                 retval.push_back(s.substr(0, i));
1175                 s = indent + s.substr(i);
1176                 ind = indent.size();
1177         }
1178         if (!s.empty())
1179                 retval.push_back(s);
1180         return retval;
1181 }
1182
1183 }
1184
1185
1186 docstring wrap(docstring const & str, int const ind, size_t const width)
1187 {
1188         docstring s = trim(str);
1189         if (s.empty())
1190                 return docstring();
1191
1192         vector<docstring> const svec = wrapToVec(str, ind, width);
1193         return getStringFromVector(svec, from_ascii("\n"));
1194 }
1195
1196
1197 docstring wrapParas(docstring const & str, int const indent,
1198                     size_t const width, size_t const maxlines)
1199 {
1200         docstring const dots = from_ascii("...");
1201         if (str.empty())
1202                 return docstring();
1203
1204         vector<docstring> const pars = getVectorFromString(str, from_ascii("\n"), true);
1205         vector<docstring> retval;
1206
1207         vector<docstring>::const_iterator it = pars.begin();
1208         vector<docstring>::const_iterator const en = pars.end();
1209         for (; it != en; ++it) {
1210                 vector<docstring> tmp = wrapToVec(*it, indent, width);
1211                 size_t const nlines = tmp.size();
1212                 if (nlines == 0)
1213                         continue;
1214                 size_t const curlines = retval.size();
1215                 if (maxlines > 0 && curlines + nlines > maxlines) {
1216                         tmp.resize(maxlines - curlines);
1217                         docstring last = tmp.back();
1218                         size_t const lsize = last.size();
1219                         if (lsize > width - 3) {
1220                                 size_t const i = last.find_last_of(' ', width - 3);
1221                                 if (i == docstring::npos || i <= size_t(indent))
1222                                         // no space found
1223                                         last = last.substr(0, lsize - 3) + dots;
1224                                 else
1225                                         last = last.substr(0, i) + dots;
1226                         } else
1227                                 last += dots;
1228                         tmp.pop_back();
1229                         tmp.push_back(last);
1230                 }
1231                 retval.insert(retval.end(), tmp.begin(), tmp.end());
1232                 if (maxlines > 0 && retval.size() >= maxlines)
1233                         break;
1234         }
1235         return getStringFromVector(retval, from_ascii("\n"));
1236 }
1237
1238
1239 namespace {
1240
1241 template<typename String> vector<String> const
1242 getVectorFromStringT(String const & str, String const & delim, bool keepempty)
1243 {
1244 // Lars would like this code to go, but for now his replacement (below)
1245 // doesn't fullfil the same function. I have, therefore, reactivated the
1246 // old code for now. Angus 11 Nov 2002.
1247 #if 1
1248         vector<String> vec;
1249         if (str.empty())
1250                 return vec;
1251         String keys = rtrim(str);
1252         while (true) {
1253                 size_t const idx = keys.find(delim);
1254                 if (idx == String::npos) {
1255                         vec.push_back(ltrim(keys));
1256                         break;
1257                 }
1258                 String const key = trim(keys.substr(0, idx));
1259                 if (!key.empty() || keepempty)
1260                         vec.push_back(key);
1261                 size_t const start = idx + delim.size();
1262                 keys = keys.substr(start);
1263         }
1264         return vec;
1265 #else
1266         typedef boost::char_separator<typename String::value_type> Separator;
1267         typedef boost::tokenizer<Separator, typename String::const_iterator, String> Tokenizer;
1268         Separator sep(delim.c_str());
1269         Tokenizer tokens(str, sep);
1270         return vector<String>(tokens.begin(), tokens.end());
1271 #endif
1272 }
1273
1274
1275 template<typename String> const String
1276         getStringFromVector(vector<String> const & vec, String const & delim)
1277 {
1278         String str;
1279         typename vector<String>::const_iterator it = vec.begin();
1280         typename vector<String>::const_iterator en = vec.end();
1281         for (; it != en; ++it) {
1282                 String item = trim(*it);
1283                 if (item.empty())
1284                         continue;
1285                 if (!str.empty())
1286                         str += delim;
1287                 str += item;
1288         }
1289         return str;
1290 }
1291
1292 } // namespace anon
1293
1294
1295 vector<string> const getVectorFromString(string const & str,
1296                                          string const & delim,
1297                                          bool keepempty)
1298 {
1299         return getVectorFromStringT<string>(str, delim, keepempty);
1300 }
1301
1302
1303 vector<docstring> const getVectorFromString(docstring const & str,
1304                                             docstring const & delim,
1305                                             bool keepempty)
1306 {
1307         return getVectorFromStringT<docstring>(str, delim, keepempty);
1308 }
1309
1310
1311 string const getStringFromVector(vector<string> const & vec,
1312                                  string const & delim)
1313 {
1314         return getStringFromVector<string>(vec, delim);
1315 }
1316
1317
1318 docstring const getStringFromVector(vector<docstring> const & vec,
1319                                     docstring const & delim)
1320 {
1321         return getStringFromVector<docstring>(vec, delim);
1322 }
1323
1324
1325 int findToken(char const * const str[], string const & search_token)
1326 {
1327         int i = 0;
1328
1329         while (str[i][0] && str[i] != search_token)
1330                 ++i;
1331         if (!str[i][0])
1332                 i = -1;
1333         return i;
1334 }
1335
1336
1337 template<>
1338 docstring bformat(docstring const & fmt, int arg1)
1339 {
1340         LATTEST(contains(fmt, from_ascii("%1$d")));
1341         docstring const str = subst(fmt, from_ascii("%1$d"), convert<docstring>(arg1));
1342         return subst(str, from_ascii("%%"), from_ascii("%"));
1343 }
1344
1345
1346 template<>
1347 docstring bformat(docstring const & fmt, long arg1)
1348 {
1349         LATTEST(contains(fmt, from_ascii("%1$d")));
1350         docstring const str = subst(fmt, from_ascii("%1$d"), convert<docstring>(arg1));
1351         return subst(str, from_ascii("%%"), from_ascii("%"));
1352 }
1353
1354
1355 template<>
1356 docstring bformat(docstring const & fmt, unsigned int arg1)
1357 {
1358         LATTEST(contains(fmt, from_ascii("%1$d")));
1359         docstring const str = subst(fmt, from_ascii("%1$d"), convert<docstring>(arg1));
1360         return subst(str, from_ascii("%%"), from_ascii("%"));
1361 }
1362
1363
1364 template<>
1365 docstring bformat(docstring const & fmt, docstring arg1)
1366 {
1367         LATTEST(contains(fmt, from_ascii("%1$s")));
1368         docstring const str = subst(fmt, from_ascii("%1$s"), arg1);
1369         return subst(str, from_ascii("%%"), from_ascii("%"));
1370 }
1371
1372
1373 template<>
1374 docstring bformat(docstring const & fmt, char * arg1)
1375 {
1376         LATTEST(contains(fmt, from_ascii("%1$s")));
1377         docstring const str = subst(fmt, from_ascii("%1$s"), from_ascii(arg1));
1378         return subst(str, from_ascii("%%"), from_ascii("%"));
1379 }
1380
1381
1382 template<>
1383 docstring bformat(docstring const & fmt, docstring arg1, docstring arg2)
1384 {
1385         LATTEST(contains(fmt, from_ascii("%1$s")));
1386         LATTEST(contains(fmt, from_ascii("%2$s")));
1387         docstring str = subst(fmt, from_ascii("%1$s"), arg1);
1388         str = subst(str, from_ascii("%2$s"), arg2);
1389         return subst(str, from_ascii("%%"), from_ascii("%"));
1390 }
1391
1392
1393 template<>
1394 docstring bformat(docstring const & fmt, docstring arg1, int arg2)
1395 {
1396         LATTEST(contains(fmt, from_ascii("%1$s")));
1397         LATTEST(contains(fmt, from_ascii("%2$d")));
1398         docstring str = subst(fmt, from_ascii("%1$s"), arg1);
1399         str = subst(str, from_ascii("%2$d"), convert<docstring>(arg2));
1400         return subst(str, from_ascii("%%"), from_ascii("%"));
1401 }
1402
1403
1404 template<>
1405 docstring bformat(docstring const & fmt, char const * arg1, docstring arg2)
1406 {
1407         LATTEST(contains(fmt, from_ascii("%1$s")));
1408         LATTEST(contains(fmt, from_ascii("%2$s")));
1409         docstring str = subst(fmt, from_ascii("%1$s"), from_ascii(arg1));
1410         str = subst(fmt, from_ascii("%2$s"), arg2);
1411         return subst(str, from_ascii("%%"), from_ascii("%"));
1412 }
1413
1414
1415 template<>
1416 docstring bformat(docstring const & fmt, int arg1, int arg2)
1417 {
1418         LATTEST(contains(fmt, from_ascii("%1$d")));
1419         LATTEST(contains(fmt, from_ascii("%2$d")));
1420         docstring str = subst(fmt, from_ascii("%1$d"), convert<docstring>(arg1));
1421         str = subst(str, from_ascii("%2$d"), convert<docstring>(arg2));
1422         return subst(str, from_ascii("%%"), from_ascii("%"));
1423 }
1424
1425
1426 template<>
1427 docstring bformat(docstring const & fmt, docstring arg1, docstring arg2, docstring arg3)
1428 {
1429         LATTEST(contains(fmt, from_ascii("%1$s")));
1430         LATTEST(contains(fmt, from_ascii("%2$s")));
1431         LATTEST(contains(fmt, from_ascii("%3$s")));
1432         docstring str = subst(fmt, from_ascii("%1$s"), arg1);
1433         str = subst(str, from_ascii("%2$s"), arg2);
1434         str = subst(str, from_ascii("%3$s"), arg3);
1435         return subst(str, from_ascii("%%"), from_ascii("%"));
1436 }
1437
1438
1439 template<>
1440 docstring bformat(docstring const & fmt,
1441                docstring arg1, docstring arg2, docstring arg3, docstring arg4)
1442 {
1443         LATTEST(contains(fmt, from_ascii("%1$s")));
1444         LATTEST(contains(fmt, from_ascii("%2$s")));
1445         LATTEST(contains(fmt, from_ascii("%3$s")));
1446         LATTEST(contains(fmt, from_ascii("%4$s")));
1447         docstring str = subst(fmt, from_ascii("%1$s"), arg1);
1448         str = subst(str, from_ascii("%2$s"), arg2);
1449         str = subst(str, from_ascii("%3$s"), arg3);
1450         str = subst(str, from_ascii("%4$s"), arg4);
1451         return subst(str, from_ascii("%%"), from_ascii("%"));
1452 }
1453
1454 } // namespace support
1455 } // namespace lyx