Skip to content

Commit a48cab5

Browse files
committed
AI.sct: If the trailing newline character of the text returned by the OpenAI API is different from the trailing newline character of the original text, match it to the original text.
1 parent bdc6df1 commit a48cab5

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

Plugins/dlls/AI.sct

+25-1
Original file line numberDiff line numberDiff line change
@@ -244,6 +244,30 @@ function getOpenAIKey() {
244244
return openAIKey;
245245
}
246246

247+
function getTrailingNewline(text) {
248+
if (text.length === 0) {
249+
return "";
250+
}
251+
if (text.length >= 2 && text.substring(text.length - 2) === "\r\n") {
252+
return "\r\n";
253+
}
254+
var ch = text.substring(text.length - 1);
255+
if (ch === "\n" || ch === "\r") {
256+
return ch;
257+
}
258+
return "";
259+
}
260+
261+
function syncTrailingNewline(originalText, convertedText) {
262+
var originalNewline = getTrailingNewline(originalText);
263+
var convertedNewline = getTrailingNewline(convertedText);
264+
if (originalNewline !== convertedNewline) {
265+
var trimmedConvertedText = convertedText.replace(/(\r\n|\r|\n)$/, '');
266+
return trimmedConvertedText + originalNewline;
267+
}
268+
return convertedText;
269+
}
270+
247271
function getResp(xmlHttp) {
248272
var stream = new ActiveXObject("ADODB.Stream");
249273
stream.Type = 1; // adTypeBinary
@@ -283,7 +307,7 @@ function AIConvertText(Text) {
283307
xmlHttp.setRequestHeader("Content-Type", "application/json");
284308
xmlHttp.setRequestHeader("Authorization", "Bearer " + openAIKey);
285309
xmlHttp.send(body);
286-
return getContentOrThrowError(getResp(xmlHttp)) ;
310+
return syncTrailingNewline(Text, getContentOrThrowError(getResp(xmlHttp)));
287311
}
288312

289313
function translate(text) {

0 commit comments

Comments
 (0)