| 129 | } |
| 130 | |
| 131 | QString CodeHandler::processText(QString text, QString currentFilePath) |
| 132 | { |
| 133 | QString result; |
| 134 | QStringList lines = text.split('\n'); |
| 135 | bool inCodeBlock = false; |
| 136 | QString pendingComments; |
| 137 | |
| 138 | auto currentFileExtension = QFileInfo(currentFilePath).suffix(); |
| 139 | auto currentLanguage = detectLanguageFromExtension(currentFileExtension); |
| 140 | |
| 141 | auto addPendingCommentsIfAny = [&]() { |
| 142 | if (pendingComments.isEmpty()) { |
| 143 | return; |
| 144 | } |
| 145 | QStringList commentLines = pendingComments.split('\n'); |
| 146 | QString commentPrefix = getCommentPrefix(currentLanguage); |
| 147 | |
| 148 | for (const QString &commentLine : commentLines) { |
| 149 | if (!commentLine.trimmed().isEmpty()) { |
| 150 | result += commentPrefix + " " + commentLine.trimmed() + "\n"; |
| 151 | } else { |
| 152 | result += "\n"; |
| 153 | } |
| 154 | } |
| 155 | pendingComments.clear(); |
| 156 | }; |
| 157 | |
| 158 | for (const QString &line : lines) { |
| 159 | if (line.trimmed().startsWith("```")) { |
| 160 | if (!inCodeBlock) { |
| 161 | auto lineLanguage = detectLanguageFromLine(line); |
| 162 | if (!lineLanguage.isEmpty()) { |
| 163 | currentLanguage = lineLanguage; |
| 164 | } |
| 165 | |
| 166 | addPendingCommentsIfAny(); |
| 167 | |
| 168 | if (lineLanguage.isEmpty()) { |
| 169 | // language not detected, so add direct output from model, if any |
| 170 | result += line.trimmed().mid(3) + "\n"; // add the remainder of line after ``` |
| 171 | } |
| 172 | } |
| 173 | inCodeBlock = !inCodeBlock; |
| 174 | continue; |
| 175 | } |
| 176 | |
| 177 | if (inCodeBlock) { |
| 178 | result += line + "\n"; |
| 179 | } else { |
| 180 | QString trimmed = line.trimmed(); |
| 181 | if (!trimmed.isEmpty()) { |
| 182 | pendingComments += trimmed + "\n"; |
| 183 | } else { |
| 184 | pendingComments += "\n"; |
| 185 | } |
| 186 | } |
| 187 | } |
| 188 | |