]> git.lyx.org Git - lyx.git/blob - src/support/lstrings.h
Less expensive OP first as this might be called often.
[lyx.git] / src / support / lstrings.h
1 // -*- C++ -*-
2 /**
3  * \file lstrings.h
4  * This file is part of LyX, the document processor.
5  * Licence details can be found in the file COPYING.
6  *
7  * \author Lars Gullik Bjønnes
8  * \author Jean-Marc Lasgouttes
9  *
10  * Full author contact details are available in file CREDITS.
11  *
12  * A collection of string helper functions that works with string.
13  * Some of these would certainly benefit from a rewrite/optimization.
14  */
15
16 #ifndef LSTRINGS_H
17 #define LSTRINGS_H
18
19 #include "support/docstring.h"
20
21 #include <vector>
22
23
24 namespace lyx {
25 namespace support {
26
27 /// Compare \p s and \p s2, ignoring the case.
28 /// Does not depend on the locale.
29 int compare_no_case(docstring const & s, docstring const & s2);
30
31 /// Compare \p s and \p s2 using the collating rules of the current locale.
32 int compare_locale(docstring const & s, docstring const & s2);
33
34 /// Compare \p s and \p s2, ignoring the case of ASCII characters only.
35 int compare_ascii_no_case(std::string const & s, std::string const & s2);
36
37 /// Compare \p s and \p s2, ignoring the case of ASCII characters only.
38 int compare_ascii_no_case(docstring const & s, docstring const & s2);
39
40 ///
41 bool isStrInt(std::string const & str);
42
43 /// does the std::string represent an unsigned integer value ?
44 bool isStrUnsignedInt(std::string const & str);
45
46 ///
47 bool isStrDbl(std::string const & str);
48
49 /// does the string contain a digit?
50 bool hasDigitASCII(docstring const & str);
51
52 bool isHexChar(char_type);
53
54 bool isHex(docstring const & str);
55
56 unsigned int hexToInt(docstring const & str);
57
58 /// is \p str pure ascii?
59 bool isAscii(docstring const & str);
60
61 /// is \p str pure ascii?
62 bool isAscii(std::string const & str);
63
64 /**
65  * Changes the case of \p c to lowercase.
66  * Don't use this for non-ASCII characters, since it depends on the locale.
67  * This overloaded function is only implemented because the char_type variant
68  * would be used otherwise, and we assert in this function that \p c is in
69  * the ASCII range.
70  */
71 char lowercase(char c);
72
73 /**
74  * Changes the case of \p c to uppercase.
75  * Don't use this for non-ASCII characters, since it depends on the locale.
76  * This overloaded function is only implemented because the char_type variant
77  * would be used otherwise, and we assert in this function that \p c is in
78  * the ASCII range.
79  */
80 char uppercase(char c);
81
82 /// Changes the case of \p c to lowercase.
83 /// Does not depend on the locale.
84 char_type lowercase(char_type c);
85
86 /// Changes the case of \p c to uppercase.
87 /// Does not depend on the locale.
88 char_type uppercase(char_type c);
89
90 /// Checks if the supplied character is lower-case
91 bool isLowerCase(char_type ch);
92
93 /// Checks if the supplied character is upper-case
94 bool isUpperCase(char_type ch);
95
96 /// same as lowercase(), but ignores locale
97 std::string const ascii_lowercase(std::string const &);
98 docstring const ascii_lowercase(docstring const &);
99
100 /// Changes the case of \p s to lowercase.
101 /// Does not depend on the locale.
102 docstring const lowercase(docstring const & s);
103 // Currently unused, but the code is there if needed.
104 // std::string const lowercase(std::string const & s);
105
106 /// Changes the case of \p s to uppercase.
107 /// Does not depend on the locale.
108 docstring const uppercase(docstring const & s);
109
110 /// Returns the superscript of \p c or \p c if no superscript exists.
111 /// Does not depend on the locale.
112 char_type superscript(char_type c);
113
114 /// Returns the subscript of \p c or \p c if no subscript exists.
115 /// Does not depend on the locale.
116 char_type subscript(char_type c);
117
118 /// Does str start with c?
119 bool prefixIs(docstring const & str, char_type c);
120
121 /// Does str start with pre?
122 bool prefixIs(std::string const & str, std::string const & pre);
123 bool prefixIs(docstring const & str, docstring const & pre);
124
125 /// Does the string end with this char?
126 bool suffixIs(std::string const &, char);
127 bool suffixIs(docstring const &, char_type);
128
129 /// Does the string end with this suffix?
130 bool suffixIs(std::string const &, std::string const &);
131 bool suffixIs(docstring const &, docstring const &);
132
133 /// Is b contained in a?
134 inline bool contains(std::string const & a, std::string const & b)
135 {
136         return a.find(b) != std::string::npos;
137 }
138
139 inline bool contains(docstring const & a, docstring const & b)
140 {
141         return a.find(b) != docstring::npos;
142 }
143
144 inline bool contains(std::string const & a, char b)
145 {
146         return a.find(b) != std::string::npos;
147 }
148
149 inline bool contains(docstring const & a, char_type b)
150 {
151         return a.find(b) != docstring::npos;
152 }
153
154 /// Returns true if the first argument is made of ascii chars given in the
155 /// second argument.
156 bool containsOnly(std::string const &, std::string const &);
157 ///
158 bool containsOnly(docstring const &, std::string const &);
159
160 /** Extracts a token from this string at the nth delim.
161     Doesn't modify the original string. Similar to strtok.
162     Example:
163     \code
164     token("a;bc;d", ';', 1) == "bc";
165     token("a;bc;d", ';', 2) == "d";
166     \endcode
167 */
168 std::string const token(std::string const & a, char delim, int n);
169
170 docstring const token(docstring const & a, char_type delim, int n);
171
172 /** Search a token in this string using the delim.
173     Doesn't modify the original string. Returns -1 in case of
174     failure.
175     Example:
176     \code
177     tokenPos("a;bc;d", ';', "bc") == 1;
178     tokenPos("a;bc;d", ';', "d") == 2;
179     \endcode
180 */
181 int tokenPos(std::string const & a, char delim, std::string const & tok);
182 int tokenPos(docstring const & a, char_type delim, docstring const & tok);
183
184 ///
185 docstring capitalize(docstring const & s);
186
187 /// Substitute all \a oldchar with \a newchar
188 std::string const subst(std::string const & a, char oldchar, char newchar);
189
190 /// Substitute all \a oldchar with \a newchar
191 docstring const subst(docstring const & a, char_type oldchar, char_type newchar);
192
193 /// substitutes all instances of \a oldstr with \a newstr
194 std::string const subst(std::string const & a,
195                    std::string const & oldstr, std::string const & newstr);
196
197 /// substitutes all instances of \a oldstr with \a newstr
198 docstring const subst(docstring const & a,
199                 docstring const & oldstr, docstring const & newstr);
200
201 /// Count all occurrences of char \a chr inside \a str
202 int count_char(std::string const & str, char chr);
203
204 /// Count all occurrences of char \a chr inside \a str
205 int count_char(docstring const & str, docstring::value_type chr);
206
207 /// get an approximate word count
208 int wordCount(docstring const &);
209
210 /** Count all occurrences of binary chars inside \a str.
211     It is assumed that \a str is utf-8 encoded and that a binary char
212     belongs to the unicode class names Zl, Zp, Cc, Cf, Cs, Co, or Cn
213     (excluding white space characters such as '\t', '\n', '\v', '\f', '\r').
214     See http://www.unicode.org/Public/6.2.0/ucd/UnicodeData.txt
215 */
216 int count_bin_chars(std::string const & str);
217
218 /** Trims characters off the end and beginning of a string.
219     \code
220     trim("ccabccc", "c") == "ab".
221     \endcode
222 */
223 docstring const trim(docstring const & a, char const * p = " ");
224
225 /** Trims characters off the end and beginning of a string.
226     \code
227     trim("ccabccc", "c") == "ab".
228     \endcode
229 */
230 std::string const trim(std::string const & a, char const * p = " ");
231
232 /** Trims characters off the end of a string, removing any character
233     in p.
234     \code
235     rtrim("abcde", "dec") == "ab".
236     \endcode
237 */
238 std::string const rtrim(std::string const & a, char const * p = " ");
239 docstring const rtrim(docstring const & a, char const * p = " ");
240
241 /** Trims characters off the beginning of a string.
242     \code
243    ("abbabcdef", "ab") = "cdef"
244     \endcode
245 */
246 std::string const ltrim(std::string const & a, char const * p = " ");
247 docstring const ltrim(docstring const & a, char const * p = " ");
248
249 /** Splits the string given in the first argument at the first occurrence
250     of the third argument, delim.
251     What precedes delim is returned in the second argument, piece; this
252     will be the whole of the string if no delimiter is found.
253     The return value is what follows delim, if anything. So the return
254     value is the null string if no delimiter is found.
255     'a' and 'piece' must be different variables.
256     Examples:
257     \code
258     s1= "a;bc"; s2= ""
259     ret = split(s1, s2, ';') -> ret = "bc", s2 == "a"
260     \endcode
261  */
262 std::string const split(std::string const & a, std::string & piece, char delim);
263 docstring const split(docstring const & a, docstring & piece, char_type delim);
264
265 /// Same as split but does not return a piece
266 std::string const split(std::string const & a, char delim);
267
268 /// Same as split but uses the last delim.
269 std::string const rsplit(std::string const & a, std::string & piece, char delim);
270 docstring const rsplit(docstring const & a, docstring & piece, char_type delim);
271 docstring const rsplit(docstring const & a, char_type delim);
272
273 /// Escapes non ASCII chars and other problematic characters that cause
274 /// problems in latex labels.
275 docstring const escape(docstring const & lab);
276
277 /// Group contents of an argument if needed
278 docstring const protectArgument(docstring & arg, char const l = '[',
279                           char const r = ']');
280
281 /// Truncates a string with an ellipsis at the end.  Leaves str unchanged and
282 /// returns false if it is shorter than len. Otherwise resizes str to len, with
283 /// U+2026 HORIZONTAL ELLIPSIS at the end, and returns true.
284 /// If mid is true, the ellipsis will be put to the mid of the string, and the first
285 /// and last half is appended/prepended. 
286 ///
287 /// Warning (Unicode): The cases where we want to truncate the text and it does
288 /// not end up converted into a QString for UI display must be really
289 /// rare. Whenever possible, we should prefer calling QFontMetrics::elidedText()
290 /// instead, which takes into account the actual length on the screen and the
291 /// layout direction (RTL or LTR). Or a similar function taking into account the
292 /// font metrics from the buffer view, which still has to be defined. Or set up
293 /// the widgets such that Qt elides the string automatically with the exact
294 /// needed width. Recall that not only graphemes vary greatly in width, but also
295 /// can be made of several code points. See:
296 /// <http://utf8everywhere.org/#myth.strlen>
297 ///
298 /// What is acceptable is when we know that the string is probably going to be
299 /// elided by Qt anyway, and len is chosen such that our own ellipsis will only
300 /// be displayed in worst-case scenarios.
301 ///
302 /// FIXME: apply those principles in the current code.
303 ///
304 bool truncateWithEllipsis(docstring & str, size_t const len,
305                           bool const mid = false);
306
307 /// Word-wraps the provided docstring, returning a line-broken string
308 /// of width no wider than width, with the string broken at spaces.
309 /// If the string cannot be broken appropriately, it returns something
310 /// with "..." at the end, again no wider than width.
311 /// We assume here that str does not contain newlines.
312 /// If indent is positive, then the first line is indented that many
313 /// spaces. If it is negative, then successive lines are indented, as
314 /// if the first line were "outdented".
315 ///
316 /// Warning (Unicode): uses truncateWithEllipsis() internally. Therefore it is
317 /// subject to the same warning and FIXME as above.
318 ///
319 docstring wrap(docstring const & str, int const indent = 0,
320                size_t const width = 80);
321
322 /// Like the preceding, except it is intended to operate on strings
323 /// that may contain embedded newlines.
324 /// \param numlines Don't return more than numlines lines. If numlines
325 ///    is 0, we return everything.
326 ///
327 /// Warning (Unicode): uses truncateWithEllipsis() internally. Therefore it is
328 /// subject to the same warning and FIXME as above.
329 ///
330 docstring wrapParas(docstring const & str, int const indent = 0,
331                     size_t const width = 80, size_t const maxlines = 10);
332
333 /// gives a vector of stringparts which have the delimiter delim
334 /// If \p keepempty is true, empty strings will be pushed to the vector as well
335 /// If \p trimit is true, leading and trailing whitespace will be trimmed from
336 /// all values. Note that this can affect what counts as "empty".
337 /// NOTE: If you want to split a string on whitespace, then do:
338 ///    getVectorFromString(str, " ", false, true);
339 std::vector<std::string> const getVectorFromString(std::string const & str,
340         std::string const & delim = std::string(","),
341         bool keepempty = false, bool trimit = true);
342 std::vector<docstring> const getVectorFromString(docstring const & str,
343         docstring const & delim = from_ascii(","),
344         bool keepempty = false, bool trimit = true);
345
346 /// the same vice versa
347 std::string const getStringFromVector(std::vector<std::string> const & vec,
348                                  std::string const & delim = std::string(","));
349 docstring const getStringFromVector(std::vector<docstring> const & vec,
350                                  docstring const & delim = from_ascii(","));
351
352 /// Search \p search_token in \p str and return the position if it is
353 /// found, else -1. The last item in \p str must be "".
354 int findToken(char const * const str[], std::string const & search_token);
355
356
357 /// Format a floating point number with at least 6 significant digits, but
358 /// without scientific notation.
359 /// Scientific notation would be invalid in some contexts, such as lengths for
360 /// LaTeX. Simply using std::ostream with std::fixed would produce results
361 /// like "1000000.000000", and precision control would not be that easy either.
362 std::string formatFPNumber(double);
363
364 /// Returns an URI/URL-style percent-encoded copy of the string \p in.
365 /// \p ex defines a string of characters that are excluded from the transformation
366 docstring to_percent_encoding(docstring const & in, docstring const & ex = docstring());
367
368 /// Returns a string decoded from an URI/URL-style percent-encoded string \p in.
369 std::string from_percent_encoding(std::string const & in);
370
371 /// returns the number of expanding characters taken into account for
372 /// increased inter-word spacing during justification
373 int countExpanders(docstring const & str);
374
375
376 docstring bformat(docstring const & fmt, int arg1);
377 docstring bformat(docstring const & fmt, long arg1);
378 #ifdef HAVE_LONG_LONG_INT
379 docstring bformat(docstring const & fmt, long long arg1);
380 #endif
381 docstring bformat(docstring const & fmt, unsigned int arg1);
382 docstring bformat(docstring const & fmt, docstring const & arg1);
383 docstring bformat(docstring const & fmt, char * arg1);
384 docstring bformat(docstring const & fmt, docstring const & arg1, docstring const & arg2);
385 docstring bformat(docstring const & fmt, docstring const & arg1, int arg2);
386 docstring bformat(docstring const & fmt, char const * arg1, docstring const & arg2);
387 docstring bformat(docstring const & fmt, int arg1, int arg2);
388 docstring bformat(docstring const & fmt, docstring const & arg1, docstring const & arg2, docstring const & arg3);
389 docstring bformat(docstring const & fmt, docstring const & arg1, docstring const & arg2, docstring const & arg3, docstring const & arg4);
390 docstring bformat(docstring const & fmt, docstring const & arg1, docstring const & arg2, docstring const & arg3, docstring const & arg4, docstring const & arg5);
391
392
393 } // namespace support
394 } // namespace lyx
395
396 #endif