The Battle for Wesnoth  1.15.0+dev
string_utils.hpp
Go to the documentation of this file.
1 /*
2  Copyright (C) 2003 by David White <dave@whitevine.net>
3  Copyright (C) 2005 - 2018 by Guillaume Melquiond <guillaume.melquiond@gmail.com>
4  Part of the Battle for Wesnoth Project https://www.wesnoth.org/
5 
6  This program is free software; you can redistribute it and/or modify
7  it under the terms of the GNU General Public License as published by
8  the Free Software Foundation; either version 2 of the License, or
9  (at your option) any later version.
10  This program is distributed in the hope that it will be useful,
11  but WITHOUT ANY WARRANTY.
12 
13  See the COPYING file for more details.
14 */
15 
16 #pragma once
17 
18 #include "font/constants.hpp"
20 
21 #include <algorithm>
22 #include <map>
23 #include <ostream>
24 #include <set>
25 #include <sstream>
26 #include <string>
27 #include <utility>
28 #include <vector>
29 
30 class t_string;
31 
32 namespace utils {
33 
34 using string_map = std::map<std::string, t_string>;
35 
36 bool isnewline(const char c);
37 bool portable_isspace(const char c);
38 bool notspace(char c);
39 
40 enum {
41  REMOVE_EMPTY = 0x01, /** REMOVE_EMPTY: remove empty elements. */
42  STRIP_SPACES = 0x02 /** STRIP_SPACES: strips leading and trailing blank spaces. */
43 };
44 
45 /** Splits a (comma-)separated string into a vector of pieces. */
46 std::vector<std::string> split(const std::string& val, const char c = ',', const int flags = REMOVE_EMPTY | STRIP_SPACES);
47 
48 /**
49  * This function is identical to split(), except it does not split when it otherwise would if the
50  * previous character was identical to the parameter 'quote' (i.e. it does not split quoted commas).
51  * This method was added to make it possible to quote user input, particularly so commas in user input
52  * would not cause visual problems in menus.
53  *
54  * @todo Why not change split()? That would change the methods post condition.
55  */
56 std::vector<std::string> quoted_split(const std::string& val, char c= ',', int flags = REMOVE_EMPTY | STRIP_SPACES, char quote = '\\');
57 
58 /**
59  * Splits a (comma-)separated string into a set of pieces.
60  * See split() for the meanings of the parameters.
61  */
62 inline std::set<std::string> set_split(const std::string& val, const char c = ',', const int flags = REMOVE_EMPTY | STRIP_SPACES)
63 {
64  std::vector<std::string> vec_split = split(val, c, flags);
65  return std::set< std::string >(vec_split.begin(), vec_split.end());
66 }
67 
68 /**
69  * Splits a string based on two separators into a map.
70  *
71  * Major: the separator between elements of the map
72  * Minor: the separator between keys and values in one element
73  *
74  * For example, the string 'a:b,c:d,e:f' would be parsed into:
75  * a => b
76  * c => d
77  * e => f
78  */
79 std::map<std::string, std::string> map_split(
80  const std::string& val,
81  char major = ',',
82  char minor = ':',
83  int flags = REMOVE_EMPTY | STRIP_SPACES,
84  const std::string& default_value = "");
85 
86 /**
87  * Splits a string based either on a separator, except then the text appears within specified parenthesis.
88  *
89  * If the separator is "0" (default), it splits a string into an odd number of parts:
90  * - The part before the first '(',
91  * - the part between the first '('
92  * - and the matching right ')', etc ...
93  * and the remainder of the string.
94  *
95  * Note that one can use the same character for both the left and right parenthesis, which usually makes
96  * the most sense for this function.
97  *
98  * Note that this will find the first matching char in the left string and match against the corresponding
99  * char in the right string. A correctly processed string should return a vector with an odd number of
100  * elements. Empty elements are never removed as they are placeholders, hence REMOVE EMPTY only works for
101  * the separator split.
102  *
103  * INPUT: ("a(b)c{d}e(f{g})h", 0, "({", ")}")
104  * RETURNS: {"a", "b", "c", "d", "e", "f{g}", "h"}
105  */
106 std::vector< std::string > parenthetical_split(
107  const std::string& val,
108  const char separator = 0,
109  const std::string& left = "(",
110  const std::string& right = ")",
111  const int flags = REMOVE_EMPTY | STRIP_SPACES);
112 
113 /**
114  * Similar to parenthetical_split, but also expands embedded square brackets.
115  *
116  * Notes:
117  * - The Separator must be specified and number of entries in each square bracket must match in each section.
118  * - Leading zeros are preserved if specified between square brackets.
119  * - An asterisk as in [a*n] indicates to expand 'a' n times
120  *
121  * This is useful for expanding animation WML code.
122  *
123  * Examples:
124  *
125  * INPUT: ("a[1-3](1,[5,6,7]),b[8,9]", ",")
126  * RETURNS: {"a1(1,5)", "a2(1,6)", "a3(1,7)", "b8", "b9"}
127  *
128  * INPUT: ("abc[07-10]")
129  * RETURNS: {"abc07", "abc08", "abc09", "abc10"}
130  *
131  * INPUT: ("a[1,2]b[3-4]:c[5,6]")
132  * RETURNS: {"a1b3:c5", "a2b4:c6"}
133  *
134  * INPUT: ("abc[3,1].png")
135  * RETURNS: {"abc3.png", "abc2.png", "abc1.png"}
136  *
137  * INPUT: ("abc[de,xyz]")
138  * RETURNS: {"abcde", "abcxyz"}
139  *
140  * INPUT: ("abc[1*3]")
141  * RETURNS: {"abc1", "abc1", "abc1"}
142  */
143 std::vector<std::string> square_parenthetical_split(
144  const std::string& val,
145  const char separator = ',',
146  const std::string& left = "([",
147  const std::string& right = ")]",
148  const int flags = REMOVE_EMPTY | STRIP_SPACES);
149 
150 /**
151  * Generates a new string joining container items in a list.
152  *
153  * @param v A container with elements.
154  * @param s List delimiter.
155  */
156 template <typename T>
157 std::string join(const T& v, const std::string& s = ",")
158 {
159  std::stringstream str;
160 
161  for(typename T::const_iterator i = v.begin(); i != v.end(); ++i) {
162  str << *i;
163  if(std::next(i) != v.end()) {
164  str << s;
165  }
166  }
167 
168  return str.str();
169 }
170 
171 template <typename T>
172 std::string join_map(
173  const T& v,
174  const std::string& major = ",",
175  const std::string& minor = ":")
176 {
177  std::stringstream str;
178 
179  for(typename T::const_iterator i = v.begin(); i != v.end(); ++i) {
180  str << i->first << minor << i->second;
181  if(std::next(i) != v.end()) {
182  str << major;
183  }
184  }
185 
186  return str.str();
187 }
188 
189 /**
190  * Generates a new string containing a bullet list.
191  *
192  * List items are preceded by the indentation blanks, a bullet string and
193  * another blank; all but the last item are followed by a newline.
194  *
195  * @param v A container with elements.
196  * @param indent Number of indentation blanks.
197  * @param bullet The leading bullet string.
198  */
199 template<typename T>
200 std::string bullet_list(const T& v, std::size_t indent = 4, const std::string& bullet = font::unicode_bullet)
201 {
202  std::ostringstream str;
203 
204  for(typename T::const_iterator i = v.begin(); i != v.end(); ++i) {
205  if(i != v.begin()) {
206  str << '\n';
207  }
208 
209  str << std::string(indent, ' ') << bullet << ' ' << *i;
210  }
211 
212  return str.str();
213 }
214 
215 /**
216  * Indent a block of text.
217  *
218  * Only lines with content are changed; empty lines are left intact. However,
219  * if @a string is an empty string itself, the indentation unit with the
220  * specified @a indent_size will be returned instead.
221  *
222  * @param string Text to indent.
223  * @param indent_size Number of indentation units to use.
224  */
225 std::string indent(const std::string& string, std::size_t indent_size = 4);
226 
227 std::pair<int, int> parse_range(const std::string& str);
228 
229 std::vector<std::pair<int, int>> parse_ranges(const std::string& str);
230 
231 int apply_modifier(const int number, const std::string &amount, const int minimum = 0);
232 
233 /** Add a "+" or replace the "-" par Unicode minus */
234 inline std::string print_modifier(const std::string &mod)
235 {
236  return mod[0] == '-' ? (font::unicode_minus + std::string(mod.begin() + 1, mod.end())) : ("+" + mod);
237 }
238 
239 /** Prepends a configurable set of characters with a backslash */
240 std::string escape(const std::string &str, const char *special_chars);
241 
242 /**
243  * Prepend all special characters with a backslash.
244  *
245  * Special characters are:
246  * #@{}+-,\*=
247  */
248 inline std::string escape(const std::string &str)
249 {
250  return escape(str, "#@{}+-,\\*=");
251 }
252 
253 /** Remove all escape characters (backslash) */
254 std::string unescape(const std::string &str);
255 
256 /** Percent-escape characters in a UTF-8 string intended to be part of a URL. */
257 std::string urlencode(const std::string &str);
258 
259 /** Surround the string 'str' with double quotes. */
260 inline std::string quote(const std::string &str)
261 {
262  return '"' + str + '"';
263 }
264 
265 /** Convert no, false, off, 0, 0.0 to false, empty to def, and others to true */
266 bool string_bool(const std::string& str,bool def=false);
267 
268 /** Converts a bool value to 'true' or 'false' */
269 std::string bool_string(const bool value);
270 
271 /** Convert into a signed value (using the Unicode "−" and +0 convention */
272 std::string signed_value(int val);
273 
274 /** Sign with Unicode "−" if negative */
275 std::string half_signed_value(int val);
276 
277 /** Convert into a percentage (using the Unicode "−" and +0% convention */
278 inline std::string signed_percent(int val) {return signed_value(val) + "%";}
279 
280 /**
281  * Convert into a string with an SI-postfix.
282  *
283  * If the unit is to be translatable,
284  * a t_string should be passed as the third argument.
285  * _("unit_byte^B") is suggested as standard.
286  *
287  * There are no default values because they would not be translatable.
288  */
289 std::string si_string(double input, bool base2, const std::string& unit);
290 
291 /**
292  * Try to complete the last word of 'text' with the 'wordlist'.
293  *
294  * @param[in, out] text The parameter's usage is:
295  * - Input: Text where we try to complete the last word
296  * of.
297  * - Output: Text with completed last word.
298  * @param[in, out] wordlist
299  * The parameter's usage is:
300  * - Inout: A vector of strings to complete against.
301  * - Output: A vector of strings that matched 'text'.
302  *
303  * @retval true iff text is just one word (no spaces)
304  */
305 bool word_completion(std::string& text, std::vector<std::string>& wordlist);
306 
307 /** Check if a message contains a word. */
308 bool word_match(const std::string& message, const std::string& word);
309 
310 /**
311  * Match using '*' as any number of characters (including none),
312  * '+' as one or more characters, and '?' as any one character.
313  */
314 bool wildcard_string_match(const std::string& str, const std::string& match);
315 
316 /**
317  * Check if the username contains only valid characters.
318  *
319  * (all alpha-numeric characters plus underscore and hyphen)
320  */
321 bool isvalid_username(const std::string& login);
322 
323 /**
324  * Check if the username pattern contains only valid characters.
325  *
326  * (all alpha-numeric characters plus underscore, hyphen,
327  * question mark and asterisk)
328  */
329 bool isvalid_wildcard(const std::string& login);
330 
331 /**
332  * Truncates a string to a given utf-8 character count and then appends an ellipsis.
333  */
334 void ellipsis_truncate(std::string& str, const std::size_t size);
335 
336 } // end namespace utils
bool isvalid_wildcard(const std::string &username)
Check if the username pattern contains only valid characters.
std::pair< int, int > parse_range(const std::string &str)
std::string join_map(const T &v, const std::string &major=",", const std::string &minor=":")
std::string urlencode(const std::string &str)
Percent-escape characters in a UTF-8 string intended to be part of a URL.
bool isvalid_username(const std::string &username)
Check if the username contains only valid characters.
std::map< std::string, t_string > string_map
This class represents a single unit of a specific type.
Definition: unit.hpp:99
std::string join(const T &v, const std::string &s=",")
Generates a new string joining container items in a list.
std::string unescape(const std::string &str)
Remove all escape characters (backslash)
bool wildcard_string_match(const std::string &str, const std::string &match)
Match using &#39;*&#39; as any number of characters (including none), &#39;+&#39; as one or more characters, and &#39;?&#39; as any one character.
void ellipsis_truncate(std::string &str, const std::size_t size)
Truncates a string to a given utf-8 character count and then appends an ellipsis. ...
bool notspace(const char c)
std::map< std::string, std::string > map_split(const std::string &val, char major, char minor, int flags, const std::string &default_value)
Splits a string based on two separators into a map.
std::string quote(const std::string &str)
Surround the string &#39;str&#39; with double quotes.
std::vector< std::string > split(const std::string &val, const char c, const int flags)
Splits a (comma-)separated string into a vector of pieces.
std::string half_signed_value(int val)
Sign with Unicode "−" if negative.
std::string bullet_list(const T &v, std::size_t indent=4, const std::string &bullet=font::unicode_bullet)
Generates a new string containing a bullet list.
std::size_t size(const std::string &str)
Length in characters of a UTF-8 string.
Definition: unicode.cpp:86
const std::string unicode_minus
Definition: constants.cpp:38
std::vector< std::pair< int, int > > parse_ranges(const std::string &str)
std::string si_string(double input, bool base2, const std::string &unit)
Convert into a string with an SI-postfix.
REMOVE_EMPTY: remove empty elements.
lu_byte right
Definition: lparser.cpp:1027
std::string escape(const std::string &str, const char *special_chars)
Prepends a configurable set of characters with a backslash.
std::string login()
std::size_t i
Definition: function.cpp:933
static map_location::DIRECTION s
std::vector< std::string > quoted_split(const std::string &val, char c, int flags, char quote)
This function is identical to split(), except it does not split when it otherwise would if the previo...
std::string signed_percent(int val)
Convert into a percentage (using the Unicode "−" and +0% convention.
std::string bool_string(const bool value)
Converts a bool value to &#39;true&#39; or &#39;false&#39;.
bool string_bool(const std::string &str, bool def)
Convert no, false, off, 0, 0.0 to false, empty to def, and others to true.
const std::string unicode_bullet
Definition: constants.cpp:43
bool isnewline(const char c)
#define next(ls)
Definition: llex.cpp:32
int apply_modifier(const int number, const std::string &amount, const int minimum)
lu_byte left
Definition: lparser.cpp:1026
std::string indent(const std::string &string, std::size_t indent_size)
Indent a block of text.
static const char * match(MatchState *ms, const char *s, const char *p)
Definition: lstrlib.cpp:425
std::set< std::string > set_split(const std::string &val, const char c=',', const int flags=REMOVE_EMPTY|STRIP_SPACES)
Splits a (comma-)separated string into a set of pieces.
bool portable_isspace(const char c)
std::string signed_value(int val)
Convert into a signed value (using the Unicode "−" and +0 convention.
mock_char c
std::string print_modifier(const std::string &mod)
Add a "+" or replace the "-" par Unicode minus.
bool word_completion(std::string &text, std::vector< std::string > &wordlist)
Try to complete the last word of &#39;text&#39; with the &#39;wordlist&#39;.
std::vector< std::string > square_parenthetical_split(const std::string &val, const char separator, const std::string &left, const std::string &right, const int flags)
Similar to parenthetical_split, but also expands embedded square brackets.
bool word_match(const std::string &message, const std::string &word)
Check if a message contains a word.
std::vector< std::string > parenthetical_split(const std::string &val, const char separator, const std::string &left, const std::string &right, const int flags)
Splits a string based either on a separator, except then the text appears within specified parenthesi...