Euphoria
wordwrap.cc
Go to the documentation of this file.
1 #include "core/wordwrap.h"
2 
3 #include <optional>
4 
5 #include "assert/assert.h"
6 #include "base/stringutils.h"
7 
8 
9 namespace eu::core
10 {
11 
12 // get_word_wrapped is currently based on https://stackoverflow.com/a/17635
13 
14 namespace
15 {
16 
17  bool
18  is_whitespace(char c)
19  {
20  return space_characters.find(c) != std::string::npos;
21  }
22 
23  constexpr auto split_chars = space_characters;
24 
25  std::vector<std::string>
26  explode(const std::string& str)
27  {
28  std::vector<std::string> parts;
29  std::size_t start_index = 0;
30  while (true)
31  {
32  const auto index = str.find_first_of(split_chars, start_index);
33 
34  if (index == std::string::npos)
35  {
36  parts.emplace_back(str.substr(start_index));
37  return parts;
38  }
39 
40  ASSERTX(index > start_index, index, start_index);
41  auto word = str.substr(start_index, index - start_index);
42  char next_char = str.substr(index, 1)[0];
43  if (is_whitespace(next_char))
44  {
45  parts.emplace_back(word);
46  parts.emplace_back(std::string(1, next_char));
47  }
48  else
49  {
50  parts.emplace_back(word + next_char);
51  }
52 
53  start_index = index + 1;
54  }
55  }
56 
57 }
58 
59 // todo(Gustav): rename to get_word_wrapped
60 std::vector<std::string>
62 (
63  const std::string& str,
64  std::function<bool (const std::string&)> fit
65 )
66 {
67  auto words = explode(str);
68 
69  auto lines = std::vector<std::string>{};
70  std::optional<std::string> current_line;
71 
72  auto add_current_line = [&]()
73  {
74  if(current_line)
75  {
76  const auto t = trim(*current_line, " \t");
77  if(t.empty() == false)
78  {
79  lines.emplace_back(trim(t));
80  }
81  current_line = {};
82  }
83  };
84 
85  for(const auto& word: words)
86  {
87  if (fit(current_line.value_or("") + word) == false)
88  {
89  add_current_line();
90  }
91  current_line = current_line.value_or("") + word;
92  }
93 
94  add_current_line();
95  if(lines.empty())
96  {
97  lines.emplace_back("");
98  }
99  return lines;
100 }
101 
102 }
103 
#define ASSERTX(x,...)
Definition: assert.h:48
constexpr std::string_view space_characters
Space characters.
Definition: stringutils.h:24
std::string trim(const std::string &string_to_trim, std::string_view trim_characters)
Remove characters from both the start and the end.
Definition: stringutils.cc:79
std::vector< std::string > get_word_wrapped(const std::string &str, std::function< bool(const std::string &)> fit)
Definition: wordwrap.cc:62
TextSentence words
Definition: nlp_sentence.cc:88
String utility functions.