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