]> git.lyx.org Git - lyx.git/blob - src/support/lstrings.cpp
Set correctly the spacing between atoms in MathData
[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 bool containsOnly(docstring const & s, string const & cset)
721 {
722         return s.find_first_not_of(from_ascii(cset)) == string::npos;
723 }
724
725
726 // ale970405+lasgoutt-970425
727 // rewritten to use new string (Lgb)
728 string const token(string const & a, char delim, int n)
729 {
730         if (a.empty())
731                 return string();
732
733         size_t k = 0;
734         size_t i = 0;
735
736         // Find delimiter or end of string
737         for (; n--;) {
738                 if ((i = a.find(delim, i)) == string::npos)
739                         break;
740                 else
741                         ++i; // step delim
742         }
743
744         // i is now the n'th delim (or string::npos)
745         if (i == string::npos)
746                 return string();
747
748         k = a.find(delim, i);
749         // k is now the n'th + 1 delim (or string::npos)
750
751         return a.substr(i, k - i);
752 }
753
754
755 docstring const token(docstring const & a, char_type delim, int n)
756 {
757         if (a.empty())
758                 return docstring();
759
760         size_t k = 0;
761         size_t i = 0;
762
763         // Find delimiter or end of string
764         for (; n--;) {
765                 if ((i = a.find(delim, i)) == docstring::npos)
766                         break;
767                 else
768                         ++i; // step delim
769         }
770
771         // i is now the n'th delim (or string::npos)
772         if (i == docstring::npos)
773                 return docstring();
774
775         k = a.find(delim, i);
776         // k is now the n'th + 1 delim (or string::npos)
777
778         return a.substr(i, k - i);
779 }
780
781
782 // this could probably be faster and/or cleaner, but it seems to work (JMarc)
783 // rewritten to use new string (Lgb)
784 int tokenPos(string const & a, char delim, string const & tok)
785 {
786         int i = 0;
787         string str = a;
788         string tmptok;
789
790         while (!str.empty()) {
791                 str = split(str, tmptok, delim);
792                 if (tok == tmptok)
793                         return i;
794                 ++i;
795         }
796         return -1;
797 }
798
799
800 // this could probably be faster and/or cleaner, but it seems to work (JMarc)
801 // rewritten to use new string (Lgb)
802 int tokenPos(docstring const & a, char_type delim, docstring const & tok)
803 {
804         int i = 0;
805         docstring str = a;
806         docstring tmptok;
807
808         while (!str.empty()) {
809                 str = split(str, tmptok, delim);
810                 if (tok == tmptok)
811                         return i;
812                 ++i;
813         }
814         return -1;
815 }
816
817
818 namespace {
819
820 /// Substitute all \a oldchar with \a newchar
821 template<typename Ch> inline
822 basic_string<Ch> const subst_char(basic_string<Ch> const & a,
823                 Ch oldchar, Ch newchar)
824 {
825         typedef basic_string<Ch> String;
826         String tmp(a);
827         typename String::iterator lit = tmp.begin();
828         typename String::iterator end = tmp.end();
829         for (; lit != end; ++lit)
830                 if ((*lit) == oldchar)
831                         (*lit) = newchar;
832         return tmp;
833 }
834
835
836 /// Substitute all \a oldchar with \a newchar
837 docstring const subst_char(docstring const & a,
838         docstring::value_type oldchar, docstring::value_type newchar)
839 {
840         docstring tmp(a);
841         docstring::iterator lit = tmp.begin();
842         docstring::iterator end = tmp.end();
843         for (; lit != end; ++lit)
844                 if ((*lit) == oldchar)
845                         (*lit) = newchar;
846         return tmp;
847 }
848
849
850 /// substitutes all instances of \a oldstr with \a newstr
851 template<typename String> inline
852 String const subst_string(String const & a,
853                 String const & oldstr, String const & newstr)
854 {
855         LASSERT(!oldstr.empty(), return a);
856         String lstr = a;
857         size_t i = 0;
858         size_t const olen = oldstr.length();
859         while ((i = lstr.find(oldstr, i)) != string::npos) {
860                 lstr.replace(i, olen, newstr);
861                 i += newstr.length(); // We need to be sure that we dont
862                 // use the same i over and over again.
863         }
864         return lstr;
865 }
866
867
868 docstring const subst_string(docstring const & a,
869                 docstring const & oldstr, docstring const & newstr)
870 {
871         LASSERT(!oldstr.empty(), return a);
872         docstring lstr = a;
873         size_t i = 0;
874         size_t const olen = oldstr.length();
875         while ((i = lstr.find(oldstr, i)) != string::npos) {
876                 lstr.replace(i, olen, newstr);
877                 i += newstr.length(); // We need to be sure that we dont
878                 // use the same i over and over again.
879         }
880         return lstr;
881 }
882
883 }
884
885
886 string const subst(string const & a, char oldchar, char newchar)
887 {
888         return subst_char(a, oldchar, newchar);
889 }
890
891
892 docstring const subst(docstring const & a,
893                 char_type oldchar, char_type newchar)
894 {
895         return subst_char(a, oldchar, newchar);
896 }
897
898
899 string const subst(string const & a,
900                 string const & oldstr, string const & newstr)
901 {
902         return subst_string(a, oldstr, newstr);
903 }
904
905
906 docstring const subst(docstring const & a,
907                 docstring const & oldstr, docstring const & newstr)
908 {
909         return subst_string(a, oldstr, newstr);
910 }
911
912
913 int count_char(string const & str, char chr)
914 {
915         int count = 0;
916         string::const_iterator lit = str.begin();
917         string::const_iterator end = str.end();
918         for (; lit != end; ++lit)
919                 if ((*lit) == chr)
920                         count++;
921         return count;
922 }
923
924
925 /// Count all occurences of char \a chr inside \a str
926 int count_char(docstring const & str, docstring::value_type chr)
927 {
928         int count = 0;
929         docstring::const_iterator lit = str.begin();
930         docstring::const_iterator end = str.end();
931         for (; lit != end; ++lit)
932                 if ((*lit) == chr)
933                         count++;
934         return count;
935 }
936
937
938 int count_bin_chars(string const & str)
939 {
940         QString const qstr = toqstr(str).simplified();
941         int count = 0;
942         QString::const_iterator cit = qstr.begin();
943         QString::const_iterator end = qstr.end();
944         for (; cit != end; ++cit)  {
945                 switch (cit->category()) {
946                 case QChar::Separator_Line:
947                 case QChar::Separator_Paragraph:
948                 case QChar::Other_Control:
949                 case QChar::Other_Format:
950                 case QChar::Other_Surrogate:
951                 case QChar::Other_PrivateUse:
952                 case QChar::Other_NotAssigned:
953                         ++count;
954                         break;
955                 default:
956                         break;
957                 }
958         }
959         return count;
960 }
961
962
963 docstring const trim(docstring const & a, char const * p)
964 {
965         LASSERT(p, return a);
966
967         if (a.empty() || !*p)
968                 return a;
969
970         docstring s = from_ascii(p);
971         size_t r = a.find_last_not_of(s);
972         size_t l = a.find_first_not_of(s);
973
974         // Is this the minimal test? (lgb)
975         if (r == docstring::npos && l == docstring::npos)
976                 return docstring();
977
978         return a.substr(l, r - l + 1);
979 }
980
981
982 string const trim(string const & a, char const * p)
983 {
984         LASSERT(p, return a);
985
986         if (a.empty() || !*p)
987                 return a;
988
989         size_t r = a.find_last_not_of(p);
990         size_t l = a.find_first_not_of(p);
991
992         // Is this the minimal test? (lgb)
993         if (r == string::npos && l == string::npos)
994                 return string();
995
996         return a.substr(l, r - l + 1);
997 }
998
999
1000 string const rtrim(string const & a, char const * p)
1001 {
1002         LASSERT(p, return a);
1003
1004         if (a.empty() || !*p)
1005                 return a;
1006
1007         size_t r = a.find_last_not_of(p);
1008
1009         // Is this test really needed? (Lgb)
1010         if (r == string::npos)
1011                 return string();
1012
1013         return a.substr(0, r + 1);
1014 }
1015
1016
1017 docstring const rtrim(docstring const & a, char const * p)
1018 {
1019         LASSERT(p, return a);
1020
1021         if (a.empty() || !*p)
1022                 return a;
1023
1024         size_t r = a.find_last_not_of(from_ascii(p));
1025
1026         // Is this test really needed? (Lgb)
1027         if (r == docstring::npos)
1028                 return docstring();
1029
1030         return a.substr(0, r + 1);
1031 }
1032
1033
1034 string const ltrim(string const & a, char const * p)
1035 {
1036         LASSERT(p, return a);
1037         if (a.empty() || !*p)
1038                 return a;
1039         size_t l = a.find_first_not_of(p);
1040         if (l == string::npos)
1041                 return string();
1042         return a.substr(l, string::npos);
1043 }
1044
1045
1046 docstring const ltrim(docstring const & a, char const * p)
1047 {
1048         LASSERT(p, return a);
1049         if (a.empty() || !*p)
1050                 return a;
1051         size_t l = a.find_first_not_of(from_ascii(p));
1052         if (l == docstring::npos)
1053                 return docstring();
1054         return a.substr(l, docstring::npos);
1055 }
1056
1057 namespace {
1058
1059 template<typename String, typename Char> inline
1060 String const doSplit(String const & a, String & piece, Char delim)
1061 {
1062         String tmp;
1063         size_t i = a.find(delim);
1064         if (i == a.length() - 1) {
1065                 piece = a.substr(0, i);
1066         } else if (i == 0) {
1067                 piece.erase();
1068                 tmp = a.substr(i + 1);
1069         } else if (i != String::npos) {
1070                 piece = a.substr(0, i);
1071                 tmp = a.substr(i + 1);
1072         } else {
1073                 piece = a;
1074         }
1075         return tmp;
1076 }
1077
1078
1079 // FIXME: why is this specialization needed?
1080 template<typename Char> inline
1081 docstring const doSplit(docstring const & a, docstring & piece, Char delim)
1082 {
1083         docstring tmp;
1084         size_t i = a.find(delim);
1085         if (i == a.length() - 1) {
1086                 piece = a.substr(0, i);
1087         } else if (i == 0) {
1088                 piece.erase();
1089                 tmp = a.substr(i + 1);
1090         } else if (i != docstring::npos) {
1091                 piece = a.substr(0, i);
1092                 tmp = a.substr(i + 1);
1093         } else {
1094                 piece = a;
1095         }
1096         return tmp;
1097 }
1098
1099 } // anon
1100
1101
1102 string const split(string const & a, string & piece, char delim)
1103 {
1104         return doSplit(a, piece, delim);
1105 }
1106
1107
1108 docstring const split(docstring const & a, docstring & piece, char_type delim)
1109 {
1110         return doSplit(a, piece, delim);
1111 }
1112
1113
1114 string const split(string const & a, char delim)
1115 {
1116         string tmp;
1117         size_t i = a.find(delim);
1118         if (i != string::npos) // found delim
1119                 tmp = a.substr(i + 1);
1120         return tmp;
1121 }
1122
1123
1124 // ale970521
1125 string const rsplit(string const & a, string & piece, char delim)
1126 {
1127         string tmp;
1128         size_t i = a.rfind(delim);
1129         if (i != string::npos) { // delimiter was found
1130                 piece = a.substr(0, i);
1131                 tmp = a.substr(i + 1);
1132         } else { // delimiter was not found
1133                 piece.erase();
1134         }
1135         return tmp;
1136 }
1137
1138
1139 docstring const rsplit(docstring const & a, docstring & piece, char_type delim)
1140 {
1141         docstring tmp;
1142         size_t i = a.rfind(delim);
1143         if (i != string::npos) { // delimiter was found
1144                 piece = a.substr(0, i);
1145                 tmp = a.substr(i + 1);
1146         } else { // delimiter was not found
1147                 piece.erase();
1148         }
1149         return tmp;
1150 }
1151
1152
1153 docstring const rsplit(docstring const & a, char_type delim)
1154 {
1155         docstring tmp;
1156         size_t i = a.rfind(delim);
1157         if (i != string::npos)
1158                 tmp = a.substr(i + 1);
1159         return tmp;
1160 }
1161
1162
1163 docstring const escape(docstring const & lab)
1164 {
1165         char_type hexdigit[16] = { '0', '1', '2', '3', '4', '5', '6', '7',
1166                                    '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
1167         docstring enc;
1168         for (size_t i = 0; i < lab.length(); ++i) {
1169                 char_type c = lab[i];
1170                 if (c >= 128 || c == '=' || c == '%' || c == '#' || c == '$'
1171                     || c == '}' || c == '{' || c == ']' || c == '[' || c == '&') {
1172                         // Although char_type is a 32 bit type we know that
1173                         // UCS4 occupies only 21 bits, so we don't need to
1174                         // encode bigger values. Test for 2^24 because we
1175                         // can encode that with the 6 hex digits that are
1176                         // needed for 21 bits anyway.
1177                         LASSERT(c < (1 << 24), continue);
1178                         enc += '=';
1179                         enc += hexdigit[(c>>20) & 15];
1180                         enc += hexdigit[(c>>16) & 15];
1181                         enc += hexdigit[(c>>12) & 15];
1182                         enc += hexdigit[(c>> 8) & 15];
1183                         enc += hexdigit[(c>> 4) & 15];
1184                         enc += hexdigit[ c      & 15];
1185                 } else {
1186                         enc += c;
1187                 }
1188         }
1189         return enc;
1190 }
1191
1192
1193 bool truncateWithEllipsis(docstring & str, size_t const len)
1194 {
1195         if (str.size() <= len)
1196                 return false;
1197         str.resize(len);
1198         if (len > 0)
1199                 str[len - 1] = 0x2026;// HORIZONTAL ELLIPSIS
1200         return true;
1201 }
1202
1203
1204 namespace {
1205
1206 // this doesn't check whether str is empty, so do that first.
1207 vector<docstring> wrapToVec(docstring const & str, int ind,
1208                             size_t const width)
1209 {
1210         docstring s = trim(str);
1211         if (s.empty())
1212                 return vector<docstring>();
1213
1214         docstring indent;
1215         if (ind < 0) {
1216                 indent.insert(0, -ind, ' ');
1217                 ind = 0;
1218         } else if (ind > 0)
1219                 s.insert(0, ind, ' ');
1220
1221         vector<docstring> retval;
1222         while (s.size() > width) {
1223                 // find the last space within the first 'width' chars
1224                 size_t const i = s.find_last_of(' ', width - 1);
1225                 if (i == docstring::npos || i <= size_t(ind)) {
1226                         // no space found
1227                         truncateWithEllipsis(s, width);
1228                         break;
1229                 }
1230                 retval.push_back(s.substr(0, i));
1231                 s = indent + s.substr(i);
1232                 ind = indent.size();
1233         }
1234         if (!s.empty())
1235                 retval.push_back(s);
1236         return retval;
1237 }
1238
1239 }
1240
1241
1242 docstring wrap(docstring const & str, int const ind, size_t const width)
1243 {
1244         docstring s = trim(str);
1245         if (s.empty())
1246                 return docstring();
1247
1248         vector<docstring> const svec = wrapToVec(str, ind, width);
1249         return getStringFromVector(svec, from_ascii("\n"));
1250 }
1251
1252
1253 docstring wrapParas(docstring const & str, int const indent,
1254                     size_t const width, size_t const maxlines)
1255 {
1256         if (str.empty())
1257                 return docstring();
1258
1259         vector<docstring> const pars = getVectorFromString(str, from_ascii("\n"), true);
1260         vector<docstring> retval;
1261
1262         vector<docstring>::const_iterator it = pars.begin();
1263         vector<docstring>::const_iterator const en = pars.end();
1264         for (; it != en; ++it) {
1265                 vector<docstring> tmp = wrapToVec(*it, indent, width);
1266                 size_t const nlines = tmp.size();
1267                 if (nlines == 0)
1268                         continue;
1269                 size_t const curlines = retval.size();
1270                 if (maxlines > 0 && curlines + nlines > maxlines) {
1271                         tmp.resize(maxlines - curlines);
1272                         docstring last = tmp.back();
1273                         size_t const lsize = last.size();
1274                         if (lsize > width - 1) {
1275                                 size_t const i = last.find_last_of(' ', width - 1);
1276                                 if (i == docstring::npos || i <= size_t(indent))
1277                                         // no space found
1278                                         truncateWithEllipsis(last, lsize);
1279                                 else
1280                                         truncateWithEllipsis(last, i);
1281                         } else
1282                                 last.push_back(0x2026);//HORIZONTAL ELLIPSIS
1283                         tmp.pop_back();
1284                         tmp.push_back(last);
1285                 }
1286                 retval.insert(retval.end(), tmp.begin(), tmp.end());
1287                 if (maxlines > 0 && retval.size() >= maxlines)
1288                         break;
1289         }
1290         return getStringFromVector(retval, from_ascii("\n"));
1291 }
1292
1293
1294 namespace {
1295
1296 template<typename String> vector<String> const
1297 getVectorFromStringT(String const & str, String const & delim, bool keepempty)
1298 {
1299 // Lars would like this code to go, but for now his replacement (below)
1300 // doesn't fullfil the same function. I have, therefore, reactivated the
1301 // old code for now. Angus 11 Nov 2002.
1302 #if 1
1303         vector<String> vec;
1304         if (str.empty())
1305                 return vec;
1306         String keys = rtrim(str);
1307         while (true) {
1308                 size_t const idx = keys.find(delim);
1309                 if (idx == String::npos) {
1310                         vec.push_back(ltrim(keys));
1311                         break;
1312                 }
1313                 String const key = trim(keys.substr(0, idx));
1314                 if (!key.empty() || keepempty)
1315                         vec.push_back(key);
1316                 size_t const start = idx + delim.size();
1317                 keys = keys.substr(start);
1318         }
1319         return vec;
1320 #else
1321         typedef boost::char_separator<typename String::value_type> Separator;
1322         typedef boost::tokenizer<Separator, typename String::const_iterator, String> Tokenizer;
1323         Separator sep(delim.c_str());
1324         Tokenizer tokens(str, sep);
1325         return vector<String>(tokens.begin(), tokens.end());
1326 #endif
1327 }
1328
1329
1330 template<typename String> const String
1331         getStringFromVector(vector<String> const & vec, String const & delim)
1332 {
1333         String str;
1334         typename vector<String>::const_iterator it = vec.begin();
1335         typename vector<String>::const_iterator en = vec.end();
1336         for (; it != en; ++it) {
1337                 String item = trim(*it);
1338                 if (item.empty())
1339                         continue;
1340                 if (!str.empty())
1341                         str += delim;
1342                 str += item;
1343         }
1344         return str;
1345 }
1346
1347 } // namespace anon
1348
1349
1350 vector<string> const getVectorFromString(string const & str,
1351                                          string const & delim,
1352                                          bool keepempty)
1353 {
1354         return getVectorFromStringT<string>(str, delim, keepempty);
1355 }
1356
1357
1358 vector<docstring> const getVectorFromString(docstring const & str,
1359                                             docstring const & delim,
1360                                             bool keepempty)
1361 {
1362         return getVectorFromStringT<docstring>(str, delim, keepempty);
1363 }
1364
1365
1366 string const getStringFromVector(vector<string> const & vec,
1367                                  string const & delim)
1368 {
1369         return getStringFromVector<string>(vec, delim);
1370 }
1371
1372
1373 docstring const getStringFromVector(vector<docstring> const & vec,
1374                                     docstring const & delim)
1375 {
1376         return getStringFromVector<docstring>(vec, delim);
1377 }
1378
1379
1380 int findToken(char const * const str[], string const & search_token)
1381 {
1382         int i = 0;
1383
1384         while (str[i][0] && str[i] != search_token)
1385                 ++i;
1386         if (!str[i][0])
1387                 i = -1;
1388         return i;
1389 }
1390
1391
1392 std::string formatFPNumber(double x)
1393 {
1394         // Need manual tweaking, QString::number(x, 'f', 16) does not work either
1395         ostringstream os;
1396         os << std::fixed;
1397         // Prevent outputs of 23.4200000000000017 but output small numbers
1398         // with at least 6 significant digits.
1399         double const logarithm = log10(fabs(x));
1400         os << std::setprecision(max(6 - iround(logarithm), 0)) << x;
1401         string result = os.str();
1402         if (result.find('.') != string::npos) {
1403                 result = rtrim(result, "0");
1404                 if (result[result.length()-1] == '.')
1405                         result = rtrim(result, ".");
1406         }
1407         return result;
1408 }
1409
1410
1411 template<>
1412 docstring bformat(docstring const & fmt, int arg1)
1413 {
1414         LATTEST(contains(fmt, from_ascii("%1$d")));
1415         docstring const str = subst(fmt, from_ascii("%1$d"), convert<docstring>(arg1));
1416         return subst(str, from_ascii("%%"), from_ascii("%"));
1417 }
1418
1419
1420 template<>
1421 docstring bformat(docstring const & fmt, long arg1)
1422 {
1423         LATTEST(contains(fmt, from_ascii("%1$d")));
1424         docstring const str = subst(fmt, from_ascii("%1$d"), convert<docstring>(arg1));
1425         return subst(str, from_ascii("%%"), from_ascii("%"));
1426 }
1427
1428
1429 #ifdef LYX_USE_LONG_LONG
1430 template<>
1431 docstring bformat(docstring const & fmt, long long arg1)
1432 {
1433         LATTEST(contains(fmt, from_ascii("%1$d")));
1434         docstring const str = subst(fmt, from_ascii("%1$d"), convert<docstring>(arg1));
1435         return subst(str, from_ascii("%%"), from_ascii("%"));
1436 }
1437 #endif
1438
1439
1440 template<>
1441 docstring bformat(docstring const & fmt, unsigned int arg1)
1442 {
1443         LATTEST(contains(fmt, from_ascii("%1$d")));
1444         docstring const str = subst(fmt, from_ascii("%1$d"), convert<docstring>(arg1));
1445         return subst(str, from_ascii("%%"), from_ascii("%"));
1446 }
1447
1448
1449 template<>
1450 docstring bformat(docstring const & fmt, docstring arg1)
1451 {
1452         LATTEST(contains(fmt, from_ascii("%1$s")));
1453         docstring const str = subst(fmt, from_ascii("%1$s"), arg1);
1454         return subst(str, from_ascii("%%"), from_ascii("%"));
1455 }
1456
1457
1458 template<>
1459 docstring bformat(docstring const & fmt, char * arg1)
1460 {
1461         LATTEST(contains(fmt, from_ascii("%1$s")));
1462         docstring const str = subst(fmt, from_ascii("%1$s"), from_ascii(arg1));
1463         return subst(str, from_ascii("%%"), from_ascii("%"));
1464 }
1465
1466
1467 template<>
1468 docstring bformat(docstring const & fmt, docstring arg1, docstring arg2)
1469 {
1470         LATTEST(contains(fmt, from_ascii("%1$s")));
1471         LATTEST(contains(fmt, from_ascii("%2$s")));
1472         docstring str = subst(fmt, from_ascii("%1$s"), arg1);
1473         str = subst(str, from_ascii("%2$s"), arg2);
1474         return subst(str, from_ascii("%%"), from_ascii("%"));
1475 }
1476
1477
1478 template<>
1479 docstring bformat(docstring const & fmt, docstring arg1, int arg2)
1480 {
1481         LATTEST(contains(fmt, from_ascii("%1$s")));
1482         LATTEST(contains(fmt, from_ascii("%2$d")));
1483         docstring str = subst(fmt, from_ascii("%1$s"), arg1);
1484         str = subst(str, from_ascii("%2$d"), convert<docstring>(arg2));
1485         return subst(str, from_ascii("%%"), from_ascii("%"));
1486 }
1487
1488
1489 template<>
1490 docstring bformat(docstring const & fmt, char const * arg1, docstring arg2)
1491 {
1492         LATTEST(contains(fmt, from_ascii("%1$s")));
1493         LATTEST(contains(fmt, from_ascii("%2$s")));
1494         docstring str = subst(fmt, from_ascii("%1$s"), from_ascii(arg1));
1495         str = subst(str, from_ascii("%2$s"), arg2);
1496         return subst(str, from_ascii("%%"), from_ascii("%"));
1497 }
1498
1499
1500 template<>
1501 docstring bformat(docstring const & fmt, int arg1, int arg2)
1502 {
1503         LATTEST(contains(fmt, from_ascii("%1$d")));
1504         LATTEST(contains(fmt, from_ascii("%2$d")));
1505         docstring str = subst(fmt, from_ascii("%1$d"), convert<docstring>(arg1));
1506         str = subst(str, from_ascii("%2$d"), convert<docstring>(arg2));
1507         return subst(str, from_ascii("%%"), from_ascii("%"));
1508 }
1509
1510
1511 template<>
1512 docstring bformat(docstring const & fmt, docstring arg1, docstring arg2, docstring arg3)
1513 {
1514         LATTEST(contains(fmt, from_ascii("%1$s")));
1515         LATTEST(contains(fmt, from_ascii("%2$s")));
1516         LATTEST(contains(fmt, from_ascii("%3$s")));
1517         docstring str = subst(fmt, from_ascii("%1$s"), arg1);
1518         str = subst(str, from_ascii("%2$s"), arg2);
1519         str = subst(str, from_ascii("%3$s"), arg3);
1520         return subst(str, from_ascii("%%"), from_ascii("%"));
1521 }
1522
1523
1524 template<>
1525 docstring bformat(docstring const & fmt,
1526                docstring arg1, docstring arg2, docstring arg3, docstring arg4)
1527 {
1528         LATTEST(contains(fmt, from_ascii("%1$s")));
1529         LATTEST(contains(fmt, from_ascii("%2$s")));
1530         LATTEST(contains(fmt, from_ascii("%3$s")));
1531         LATTEST(contains(fmt, from_ascii("%4$s")));
1532         docstring str = subst(fmt, from_ascii("%1$s"), arg1);
1533         str = subst(str, from_ascii("%2$s"), arg2);
1534         str = subst(str, from_ascii("%3$s"), arg3);
1535         str = subst(str, from_ascii("%4$s"), arg4);
1536         return subst(str, from_ascii("%%"), from_ascii("%"));
1537 }
1538
1539 } // namespace support
1540 } // namespace lyx