|
1 | 1 | /* |
2 | | - * Copyright (C) 2006-2018 by Artur Kozioł, artkoz78@gmail.com |
3 | | - * Copyright (C) 2023 Nick Egorrov, nicegorov@yandex.ru |
| 2 | + * Copyright (C) 2023-2025 Nick Egorrov, nicegorov@yandex.ru |
4 | 3 | * |
5 | 4 | * This file is part of GCodeWorkShop. |
6 | 5 | * |
|
25 | 24 | #include "utils-emptylines.h" |
26 | 25 |
|
27 | 26 |
|
28 | | -void Utils::insertEmptyLines(QString& tx) |
| 27 | +bool Utils::insertEmptyLines(QString& tx, const std::function<bool (int)>& interrupt) |
29 | 28 | { |
30 | | - if (tx.contains(QLatin1String("\r\n"))) { |
31 | | - tx.replace(QLatin1String("\r\n"), QLatin1String("\r\n\r\n")); |
32 | | - } else { |
33 | | - tx.replace(QLatin1String("\n"), QLatin1String("\n\n")); |
| 29 | + bool changed = false; |
| 30 | + int pos = 0; |
| 31 | + QRegularExpression regexpr{ |
| 32 | + "\\n|\\r\\n" |
| 33 | + }; |
| 34 | + QRegularExpressionMatchIterator iterator = regexpr.globalMatch(tx); |
| 35 | + QString result; |
| 36 | + |
| 37 | + while (iterator.hasNext()) { |
| 38 | + if (interrupt(pos)) { |
| 39 | + return false; |
| 40 | + } |
| 41 | + |
| 42 | + QRegularExpressionMatch match = iterator.next(); |
| 43 | + result.append(tx.mid(pos, match.capturedStart() - pos)); |
| 44 | + result.append("\n\n"); |
| 45 | + pos = match.capturedEnd(); |
| 46 | + changed = true; |
34 | 47 | } |
| 48 | + |
| 49 | + result.append(tx.mid(pos)); |
| 50 | + tx = result; |
| 51 | + return changed; |
35 | 52 | } |
36 | 53 |
|
37 | | -void Utils::removeEmptyLines(QString& tx) |
| 54 | +bool Utils::removeEmptyLines(QString& tx, const std::function<bool (int)>& interrupt) |
38 | 55 | { |
39 | | - int i; |
40 | | - QRegularExpression regex; |
| 56 | + bool changed = false; |
| 57 | + int pos = 0; |
| 58 | + QRegularExpression regexpr{ |
| 59 | + "[\\n\\r]+" |
| 60 | + }; |
| 61 | + QRegularExpressionMatchIterator iterator = regexpr.globalMatch(tx); |
| 62 | + QString result; |
41 | 63 |
|
42 | | - regex.setPattern("[\\n]{2,}"); |
43 | | - i = 0; |
44 | | - |
45 | | - while (i >= 0) { |
46 | | - i = tx.indexOf(regex, 0); |
47 | | - |
48 | | - if (i >= 0) { |
49 | | - tx.replace(regex, "\r\n"); |
| 64 | + while (iterator.hasNext()) { |
| 65 | + if (interrupt(pos)) { |
| 66 | + return false; |
50 | 67 | } |
| 68 | + |
| 69 | + QRegularExpressionMatch match = iterator.next(); |
| 70 | + result.append(tx.mid(pos, match.capturedStart() - pos)); |
| 71 | + result.append("\n"); |
| 72 | + pos = match.capturedEnd(); |
| 73 | + changed = true; |
51 | 74 | } |
| 75 | + |
| 76 | + result.append(tx.mid(pos)); |
| 77 | + tx = result; |
| 78 | + return changed; |
52 | 79 | } |
0 commit comments