| 1113 | } |
| 1114 | |
| 1115 | bool ChangesManager::performFileEditWithDiff( |
| 1116 | const QString &filePath, |
| 1117 | const DiffInfo &diffInfo, |
| 1118 | bool reverse, |
| 1119 | QString *errorMsg) |
| 1120 | { |
| 1121 | LOG_MESSAGE(QString("=== performFileEditWithDiff: %1 (reverse: %2) ===") |
| 1122 | .arg(filePath).arg(reverse ? "yes" : "no")); |
| 1123 | |
| 1124 | auto setError = [errorMsg](const QString &msg) { |
| 1125 | if (errorMsg) *errorMsg = msg; |
| 1126 | }; |
| 1127 | |
| 1128 | auto editors = Core::EditorManager::visibleEditors(); |
| 1129 | LOG_MESSAGE(QString(" Checking %1 visible editor(s)").arg(editors.size())); |
| 1130 | |
| 1131 | for (auto *editor : editors) { |
| 1132 | if (!editor || !editor->document()) { |
| 1133 | continue; |
| 1134 | } |
| 1135 | |
| 1136 | QString editorPath = editor->document()->filePath().toFSPathString(); |
| 1137 | if (editorPath == filePath) { |
| 1138 | LOG_MESSAGE(QString(" Found open editor for: %1").arg(filePath)); |
| 1139 | |
| 1140 | QByteArray contentBytes = editor->document()->contents(); |
| 1141 | QString currentContent = QString::fromUtf8(contentBytes); |
| 1142 | |
| 1143 | LOG_MESSAGE(QString(" Current content size: %1 bytes").arg(currentContent.size())); |
| 1144 | |
| 1145 | QString modifiedContent = currentContent; |
| 1146 | QString diffErrorMsg; |
| 1147 | bool diffSuccess = applyDiffToContent(modifiedContent, diffInfo, reverse, &diffErrorMsg); |
| 1148 | |
| 1149 | if (!diffSuccess) { |
| 1150 | LOG_MESSAGE(QString(" Failed to apply diff: %1").arg(diffErrorMsg)); |
| 1151 | setError(diffErrorMsg); |
| 1152 | |
| 1153 | LOG_MESSAGE(" Attempting fallback to old content-based method..."); |
| 1154 | QString oldContent = reverse ? diffInfo.modifiedContent : diffInfo.originalContent; |
| 1155 | QString newContent = reverse ? diffInfo.originalContent : diffInfo.modifiedContent; |
| 1156 | |
| 1157 | return performFileEdit(filePath, oldContent, newContent, errorMsg); |
| 1158 | } |
| 1159 | |
| 1160 | if (auto *textEditor = qobject_cast<TextEditor::TextDocument *>(editor->document())) { |
| 1161 | QTextDocument *doc = textEditor->document(); |
| 1162 | |
| 1163 | LOG_MESSAGE(" Applying changes to text editor document..."); |
| 1164 | |
| 1165 | if (!doc) { |
| 1166 | LOG_MESSAGE(" Document is invalid"); |
| 1167 | setError("Document pointer is null"); |
| 1168 | return false; |
| 1169 | } |
| 1170 | |
| 1171 | try { |
| 1172 | QTextCursor cursor(doc); |