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