Sonnet

textbreaks.cpp
1 /* This file is part of the KDE libraries
2  SPDX-FileCopyrightText: 2006 Jacob R Rideout <[email protected]>
3  SPDX-FileCopyrightText: 2006 Martin Sandsmark <[email protected]>
4 
5  SPDX-License-Identifier: LGPL-2.0-or-later
6 */
7 
8 #include <QHash>
9 #include <QString>
10 #include <QTextBoundaryFinder>
11 
12 #include "textbreaks_p.h"
13 
14 namespace Sonnet
15 {
16 class TextBreaksPrivate
17 {
18 public:
19  TextBreaksPrivate()
20  {
21  }
22 
23  QString text;
24 };
25 
26 TextBreaks::TextBreaks(const QString &text)
27  : d(new TextBreaksPrivate())
28 {
29  setText(text);
30 }
31 
32 TextBreaks::~TextBreaks()
33 {
34  delete d;
35 }
36 
37 QString TextBreaks::text() const
38 {
39  return d->text;
40 }
41 
42 void TextBreaks::setText(const QString &text)
43 {
44  d->text = text;
45 }
46 
47 TextBreaks::Positions TextBreaks::wordBreaks(const QString &text)
48 {
49  Positions breaks;
50 
51  if (text.isEmpty()) {
52  return breaks;
53  }
54 
55  QTextBoundaryFinder boundaryFinder(QTextBoundaryFinder::Word, text);
56 
57  while (boundaryFinder.position() < text.length()) {
58  if (!(boundaryFinder.boundaryReasons().testFlag(QTextBoundaryFinder::StartOfItem))) {
59  if (boundaryFinder.toNextBoundary() == -1) {
60  break;
61  }
62  continue;
63  }
64 
65  Position pos;
66  pos.start = boundaryFinder.position();
67  int end = boundaryFinder.toNextBoundary();
68  if (end == -1) {
69  break;
70  }
71  pos.length = end - pos.start;
72  if (pos.length < 1) {
73  continue;
74  }
75  breaks.append(pos);
76 
77  if (boundaryFinder.toNextBoundary() == -1) {
78  break;
79  }
80  }
81  return breaks;
82 }
83 
84 TextBreaks::Positions TextBreaks::sentenceBreaks(const QString &text)
85 {
86  Positions breaks;
87 
88  if (text.isEmpty()) {
89  return breaks;
90  }
91 
93 
94  while (boundaryFinder.position() < text.length()) {
95  Position pos;
96  pos.start = boundaryFinder.position();
97  int end = boundaryFinder.toNextBoundary();
98  if (end == -1) {
99  break;
100  }
101  pos.length = end - pos.start;
102  if (pos.length < 1) {
103  continue;
104  }
105  breaks.append(pos);
106  }
107  return breaks;
108 }
109 
110 TextBreaks::Positions TextBreaks::wordBreaks() const
111 {
112  return wordBreaks(d->text);
113 }
114 
115 TextBreaks::Positions TextBreaks::sentenceBreaks() const
116 {
117  return sentenceBreaks(d->text);
118 }
119 }
bool isEmpty() const const
int length() const const
The sonnet namespace.
const QList< QKeySequence > & end()
This file is part of the KDE documentation.
Documentation copyright © 1996-2022 The KDE developers.
Generated on Sun Sep 25 2022 04:14:52 by doxygen 1.8.17 written by Dimitri van Heesch, © 1997-2006

KDE's Doxygen guidelines are available online.