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