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