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