OSDN Git Service

Merge pull request #42 from GreyMerlin/master
[winmerge-jp/winmerge-jp.git] / Src / DiffTextBuffer.cpp
1 /** 
2  * @file  DiffTextBuffer.cpp
3  *
4  * @brief Implementation file for CDiffTextBuffer
5  *
6  */
7
8 #include "StdAfx.h"
9 #include "DiffTextBuffer.h"
10 #include <Poco/Exception.h>
11 #include "UniFile.h"
12 #include "files.h"
13 #include "locality.h"
14 #include "paths.h"
15 #include "OptionsDef.h"
16 #include "OptionsMgr.h"
17 #include "Environment.h"
18 #include "MergeLineFlags.h"
19 #include "MergeDoc.h"
20 #include "FileTransform.h"
21 #include "FileTextEncoding.h"
22 #include "codepage_detect.h"
23 #include "TFile.h"
24
25 using Poco::Exception;
26
27 #ifdef _DEBUG
28 #define new DEBUG_NEW
29 #endif
30
31 static bool IsTextFileStylePure(const UniMemFile::txtstats & stats);
32 static void EscapeControlChars(String &s);
33 static CRLFSTYLE GetTextFileStyle(const UniMemFile::txtstats & stats);
34
35 /**
36  * @brief Check if file has only one EOL type.
37  * @param [in] stats File's text stats.
38  * @return true if only one EOL type is found, false otherwise.
39  */
40 static bool IsTextFileStylePure(const UniMemFile::txtstats & stats)
41 {
42         int nType = 0;
43         if (stats.ncrlfs > 0)
44                 nType++;
45         if ( stats.ncrs > 0)
46                 nType++;
47         if (stats.nlfs > 0)
48                 nType++;
49         return (nType <= 1);
50 }
51
52 /**
53  * @brief Escape control characters.
54  * @param [in,out] s Line of text excluding eol chars.
55  *
56  * @note Escape sequences follow the pattern
57  * (leadin character, high nibble, low nibble, leadout character).
58  * The leadin character is '\x0F'. The leadout character is a backslash.
59  */
60 static void EscapeControlChars(String &s)
61 {
62         // Compute buffer length required for escaping
63         size_t n = s.length();
64         LPCTSTR q = s.c_str();
65         size_t i = n;
66         while (i)
67         {
68                 TCHAR c = q[--i];
69                 // Is it a control character in the range 0..31 except TAB?
70                 if (!(c & ~_T('\x1F')) && c != _T('\t'))
71                 {
72                         n += 3; // Need 3 extra characters to escape
73                 }
74         }
75         // Reallocate accordingly
76         i = s.length();
77         s.reserve(n + 1);
78         s.resize(n + 1);
79         LPTSTR p = &s[0];
80         // Copy/translate characters starting at end of string
81         while (i)
82         {
83                 TCHAR c = p[--i];
84                 // Is it a control character in the range 0..31 except TAB?
85                 if (!(c & ~_T('\x1F')) && c != _T('\t'))
86                 {
87                         // Bitwise OR with 0x100 so _itot_s() will output 3 hex digits
88                         _itot_s(0x100 | c, p + n - 4, 4, 16);
89                         // Replace terminating zero with leadout character
90                         p[n - 1] = _T('\\');
91                         // Prepare to replace 1st hex digit with leadin character
92                         c = _T('\x0F');
93                         n -= 3;
94                 }
95                 p[--n] = c;
96         }
97         s.resize(s.length() - 1);
98 }
99
100 /**
101  * @brief Get file's EOL type.
102  * @param [in] stats File's text stats.
103  * @return EOL type.
104  */
105 static CRLFSTYLE GetTextFileStyle(const UniMemFile::txtstats & stats)
106 {
107         // Check if file has more than one EOL type.
108         if (!IsTextFileStylePure(stats))
109                         return CRLF_STYLE_MIXED;
110         else if (stats.ncrlfs >= stats.nlfs)
111         {
112                 if (stats.ncrlfs >= stats.ncrs)
113                         return CRLF_STYLE_DOS;
114                 else
115                         return CRLF_STYLE_MAC;
116         }
117         else
118         {
119                 if (stats.nlfs >= stats.ncrs)
120                         return CRLF_STYLE_UNIX;
121                 else
122                         return CRLF_STYLE_MAC;
123         }
124 }
125
126 /**
127  * @brief Constructor.
128  * @param [in] pDoc Owning CMergeDoc.
129  * @param [in] pane Pane number this buffer is associated with.
130  */
131 CDiffTextBuffer::CDiffTextBuffer(CMergeDoc * pDoc, int pane)
132 : m_pOwnerDoc(pDoc)
133 , m_nThisPane(pane)
134 , m_unpackerSubcode(0)
135 , m_bMixedEOL(false)
136 {
137 }
138
139 /**
140  * @brief Get a line from the buffer.
141  * @param [in] nLineIndex Index of the line to get.
142  * @param [out] strLine Returns line text in the index.
143  */
144 bool CDiffTextBuffer::GetLine(int nLineIndex, CString &strLine) const
145 {
146         int nLineLength = CCrystalTextBuffer::GetLineLength(nLineIndex);
147         if (nLineLength < 0)
148                 return false;
149         else if (nLineLength == 0)
150                 strLine.Empty();
151         else
152         {
153                 _tcsncpy_s(strLine.GetBuffer(nLineLength + 1), nLineLength + 1,
154                         CCrystalTextBuffer::GetLineChars(nLineIndex), nLineLength);
155                 strLine.ReleaseBuffer(nLineLength);
156         }
157         return true;
158 }
159
160 /**
161  * @brief Set the buffer modified status.
162  * @param [in] bModified New modified status, true if buffer has been
163  *   modified since last saving.
164  */
165 void CDiffTextBuffer::SetModified(bool bModified /*= true*/)
166 {
167         CCrystalTextBuffer::SetModified (bModified);
168         m_pOwnerDoc->SetModifiedFlag (bModified);
169 }
170
171 /**
172  * @brief Get a line (with EOL bytes) from the buffer.
173  * This function is like GetLine() but it also includes line's EOL to the
174  * returned string.
175  * @param [in] nLineIndex Index of the line to get.
176  * @param [out] strLine Returns line text in the index. Existing content
177  * of this string is overwritten.
178  */
179 bool CDiffTextBuffer::GetFullLine(int nLineIndex, CString &strLine) const
180 {
181         int cchText = GetFullLineLength(nLineIndex);
182         if (cchText == 0)
183         {
184                 strLine.Empty();
185                 return false;
186         }
187         LPTSTR pchText = strLine.GetBufferSetLength(cchText);
188         memcpy(pchText, GetLineChars(nLineIndex), cchText * sizeof(TCHAR));
189         return true;
190 }
191
192 void CDiffTextBuffer::AddUndoRecord(bool bInsert, const CPoint & ptStartPos,
193                 const CPoint & ptEndPos, LPCTSTR pszText, int cchText,
194                 int nActionType /*= CE_ACTION_UNKNOWN*/,
195                 CDWordArray *paSavedRevisionNumbers)
196 {
197         CGhostTextBuffer::AddUndoRecord(bInsert, ptStartPos, ptEndPos, pszText,
198                 cchText, nActionType, paSavedRevisionNumbers);
199         if (m_aUndoBuf[m_nUndoPosition - 1].m_dwFlags & UNDO_BEGINGROUP)
200         {
201                 m_pOwnerDoc->undoTgt.erase(m_pOwnerDoc->curUndo, m_pOwnerDoc->undoTgt.end());
202                 m_pOwnerDoc->undoTgt.push_back(m_pOwnerDoc->GetView(m_nThisPane));
203                 m_pOwnerDoc->curUndo = m_pOwnerDoc->undoTgt.end();
204         }
205 }
206 /**
207  * @brief Checks if a flag is set for line.
208  * @param [in] line Index (0-based) for line.
209  * @param [in] flag Flag to check.
210  * @return true if flag is set, false otherwise.
211  */
212 bool CDiffTextBuffer::FlagIsSet(UINT line, DWORD flag) const
213 {
214         return ((m_aLines[line].m_dwFlags & flag) == flag);
215 }
216
217 /**
218 Remove blank lines and clear winmerge flags
219 (2003-06-21, Perry: I don't understand why this is necessary, but if this isn't 
220 done, more and more gray lines appear in the file)
221 (2003-07-31, Laoran I don't understand either why it is necessary, but it works
222 fine, so let's go on with it)
223 */
224 void CDiffTextBuffer::prepareForRescan()
225 {
226         RemoveAllGhostLines();
227         for (int ct = GetLineCount() - 1; ct >= 0; --ct)
228         {
229                 SetLineFlag(ct, 
230                         LF_INVISIBLE | LF_DIFF | LF_TRIVIAL | LF_MOVED | LF_SNP,
231                         false, false, false);
232         }
233 }
234
235 /** 
236  * @brief Called when line has been edited.
237  * After editing a line, we don't know if there is a diff or not.
238  * So we clear the LF_DIFF flag (and it is more easy to read during edition).
239  * Rescan will set the proper color.
240  * @param [in] nLine Line that has been edited.
241  */
242
243 void CDiffTextBuffer::OnNotifyLineHasBeenEdited(int nLine)
244 {
245         SetLineFlag(nLine, LF_DIFF, false, false, false);
246         SetLineFlag(nLine, LF_TRIVIAL, false, false, false);
247         SetLineFlag(nLine, LF_MOVED, false, false, false);
248         SetLineFlag(nLine, LF_SNP, false, false, false);
249         CGhostTextBuffer::OnNotifyLineHasBeenEdited(nLine);
250 }
251
252 /**
253  * @brief Set the folder for temp files.
254  * @param [in] path Temp files folder.
255  */
256 void CDiffTextBuffer::SetTempPath(const String &path)
257 {
258         m_strTempPath = path;
259 }
260
261 /**
262  * @brief Is the buffer initialized?
263  * @return true if the buffer is initialized, false otherwise.
264  */
265 bool CDiffTextBuffer::IsInitialized() const
266 {
267         return !!m_bInit;
268 }
269
270 /**
271  * @brief Load file from disk into buffer
272  *
273  * @param [in] pszFileNameInit File to load
274  * @param [in] infoUnpacker Unpacker plugin
275  * @param [in] sToFindUnpacker String for finding unpacker plugin
276  * @param [out] readOnly Loading was lossy so file should be read-only
277  * @param [in] nCrlfStyle EOL style used
278  * @param [in] encoding Encoding used
279  * @param [out] sError Error message returned
280  * @return FRESULT_OK when loading succeed or (list in files.h):
281  * - FRESULT_OK_IMPURE : load OK, but the EOL are of different types
282  * - FRESULT_ERROR_UNPACK : plugin failed to unpack
283  * - FRESULT_ERROR : loading failed, sError contains error message
284  * - FRESULT_BINARY : file is binary file
285  * @note If this method fails, it calls InitNew so the CDiffTextBuffer is in a valid state
286  */
287 int CDiffTextBuffer::LoadFromFile(LPCTSTR pszFileNameInit,
288                 PackingInfo * infoUnpacker, LPCTSTR sToFindUnpacker, bool & readOnly,
289                 CRLFSTYLE nCrlfStyle, const FileTextEncoding & encoding, CString &sError)
290 {
291         ASSERT(!m_bInit);
292         ASSERT(m_aLines.size() == 0);
293
294         // Unpacking the file here, save the result in a temporary file
295         String sFileName(pszFileNameInit);
296         if (!FileTransform::Unpacking(infoUnpacker, sFileName, sToFindUnpacker))
297         {
298                 InitNew(); // leave crystal editor in valid, empty state
299                 return FileLoadResult::FRESULT_ERROR_UNPACK;
300         }
301         m_unpackerSubcode = infoUnpacker->subcode;
302
303         // we use the same unpacker for both files, so it must be defined after first file
304         ASSERT(infoUnpacker->bToBeScanned != PLUGIN_AUTO);
305         // we will load the transformed file
306         LPCTSTR pszFileName = sFileName.c_str();
307
308         String sExt;
309         DWORD nRetVal = FileLoadResult::FRESULT_OK;
310
311         // Set encoding based on extension, if we know one
312         paths::SplitFilename(pszFileName, NULL, NULL, &sExt);
313         CCrystalTextView::TextDefinition *def = 
314                 CCrystalTextView::GetTextType(sExt.c_str());
315         if (def && def->encoding != -1)
316                 m_nSourceEncoding = def->encoding;
317         
318         UniFile *pufile = infoUnpacker->pufile;
319         if (pufile == 0)
320                 pufile = new UniMemFile;
321
322         // Now we only use the UniFile interface
323         // which is something we could implement for HTTP and/or FTP files
324
325         if (!pufile->OpenReadOnly(pszFileName))
326         {
327                 nRetVal = FileLoadResult::FRESULT_ERROR;
328                 UniFile::UniError uniErr = pufile->GetLastUniError();
329                 if (uniErr.HasError())
330                 {
331                         sError = uniErr.GetError().c_str();
332                 }
333                 InitNew(); // leave crystal editor in valid, empty state
334                 goto LoadFromFileExit;
335         }
336         else
337         {
338                 if (infoUnpacker->pluginName.length() > 0)
339                 {
340                         // re-detect codepage
341                         int iGuessEncodingType = GetOptionsMgr()->GetInt(OPT_CP_DETECT);
342                         FileTextEncoding encoding2 = GuessCodepageEncoding(pszFileName, iGuessEncodingType);
343                         pufile->SetUnicoding(encoding2.m_unicoding);
344                         pufile->SetCodepage(encoding2.m_codepage);
345                         pufile->SetBom(encoding2.m_bom);
346                         if (encoding2.m_bom)
347                                 pufile->ReadBom();
348                 }
349                 else
350                 {
351                         // If the file is not unicode file, use the codepage we were given to
352                         // interpret the 8-bit characters. If the file is unicode file,
353                         // determine its type (IsUnicode() does that).
354                         if (encoding.m_unicoding == ucr::NONE  || !pufile->IsUnicode())
355                                 pufile->SetCodepage(encoding.m_codepage);
356                 }
357                 UINT lineno = 0;
358                 String eol, preveol;
359                 String sline;
360                 bool done = false;
361                 COleDateTime start = COleDateTime::GetCurrentTime(); // for trace messages
362
363                 // Manually grow line array exponentially
364                 UINT arraysize = 500;
365                 m_aLines.resize(arraysize);
366                 
367                 // preveol must be initialized for empty files
368                 preveol = _T("\n");
369                 
370                 do {
371                         bool lossy = false;
372                         done = !pufile->ReadString(sline, eol, &lossy);
373
374                         // if last line had no eol, we can quit
375                         if (done && preveol.empty())
376                                 break;
377                         // but if last line had eol, we add an extra (empty) line to buffer
378
379                         // Grow line array
380                         if (lineno == arraysize)
381                         {
382                                 // For smaller sizes use exponential growth, but for larger
383                                 // sizes grow by constant ratio. Unlimited exponential growth
384                                 // easily runs out of memory.
385                                 if (arraysize < 100 * 1024)
386                                         arraysize *= 2;
387                                 else
388                                         arraysize += 100 * 1024;
389                                 m_aLines.resize(arraysize);
390                         }
391
392                         sline += eol; // TODO: opportunity for optimization, as CString append is terrible
393                         if (lossy)
394                         {
395                                 // TODO: Should record lossy status of line
396                         }
397                         AppendLine(lineno, sline.c_str(), static_cast<int>(sline.length()));
398                         ++lineno;
399                         preveol = eol;
400                 } while (!done);
401
402                 // fix array size (due to our manual exponential growth
403                 m_aLines.resize(lineno);
404         
405                 
406                 //Try to determine current CRLF mode (most frequent)
407                 if (nCrlfStyle == CRLF_STYLE_AUTOMATIC)
408                 {
409                         nCrlfStyle = GetTextFileStyle(pufile->GetTxtStats());
410                 }
411                 ASSERT(nCrlfStyle >= 0 && nCrlfStyle <= 3);
412                 SetCRLFMode(nCrlfStyle);
413                 
414                 //  At least one empty line must present
415                 // (view does not work for empty buffers)
416                 ASSERT(m_aLines.size() > 0);
417                 
418                 m_bInit = true;
419                 m_bModified = false;
420                 m_bUndoGroup = m_bUndoBeginGroup = false;
421                 m_nSyncPosition = m_nUndoPosition = 0;
422                 ASSERT(m_aUndoBuf.size() == 0);
423                 m_ptLastChange.x = m_ptLastChange.y = -1;
424                 
425                 FinishLoading();
426                 // flags don't need initialization because 0 is the default value
427
428                 // Set the return value : OK + info if the file is impure
429                 // A pure file is a file where EOL are consistent (all DOS, or all UNIX, or all MAC)
430                 // An impure file is a file with several EOL types
431                 // WinMerge may display impure files, but the default option is to unify the EOL
432                 // We return this info to the caller, so it may display a confirmation box
433                 if (IsTextFileStylePure(pufile->GetTxtStats()))
434                         nRetVal = FileLoadResult::FRESULT_OK;
435                 else
436                         nRetVal = FileLoadResult::FRESULT_OK_IMPURE;
437
438                 // stash original encoding away
439                 m_encoding.m_unicoding = pufile->GetUnicoding();
440                 m_encoding.m_bom = pufile->HasBom();
441                 m_encoding.m_codepage = pufile->GetCodepage();
442
443                 if (pufile->GetTxtStats().nlosses)
444                 {
445                         FileLoadResult::AddModifier(nRetVal, FileLoadResult::FRESULT_LOSSY);
446                         readOnly = true;
447                 }
448         }
449         
450 LoadFromFileExit:
451         // close the file now to free the handle
452         pufile->Close();
453         delete pufile;
454
455         // delete the file that unpacking may have created
456         if (_tcscmp(pszFileNameInit, pszFileName) != 0)
457         {
458                 try
459                 {
460                         TFile(pszFileName).remove();
461                 }
462                 catch (Exception& e)
463                 {
464                         LogErrorStringUTF8(e.displayText());
465                 }
466         }
467         return nRetVal;
468 }
469
470 /**
471  * @brief Saves file from buffer to disk
472  *
473  * @param bTempFile : false if we are saving user files and
474  * true if we are saving workin-temp-files for diff-engine
475  *
476  * @return SAVE_DONE or an error code (list in MergeDoc.h)
477  */
478 int CDiffTextBuffer::SaveToFile (const String& pszFileName,
479                 bool bTempFile, String & sError, PackingInfo * infoUnpacker /*= NULL*/,
480                 CRLFSTYLE nCrlfStyle /*= CRLF_STYLE_AUTOMATIC*/,
481                 bool bClearModifiedFlag /*= true*/,
482                 int nStartLine /*= 0*/, int nLines /*= -1*/)
483 {
484         ASSERT (nCrlfStyle == CRLF_STYLE_AUTOMATIC || nCrlfStyle == CRLF_STYLE_DOS ||
485                 nCrlfStyle == CRLF_STYLE_UNIX || nCrlfStyle == CRLF_STYLE_MAC);
486         ASSERT (m_bInit);
487
488         if (nLines == -1)
489                 nLines = static_cast<int>(m_aLines.size() - nStartLine);
490
491         if (pszFileName.empty())
492                 return SAVE_FAILED;     // No filename, cannot save...
493
494         if (nCrlfStyle == CRLF_STYLE_AUTOMATIC &&
495                 !GetOptionsMgr()->GetBool(OPT_ALLOW_MIXED_EOL) ||
496                 infoUnpacker && infoUnpacker->disallowMixedEOL)
497         {
498                         // get the default nCrlfStyle of the CDiffTextBuffer
499                 nCrlfStyle = GetCRLFMode();
500                 ASSERT(nCrlfStyle >= 0 && nCrlfStyle <= 3);
501         }
502
503         bool bOpenSuccess = true;
504         bool bSaveSuccess = false;
505
506         UniStdioFile file;
507         file.SetUnicoding(m_encoding.m_unicoding);
508         file.SetBom(m_encoding.m_bom);
509         file.SetCodepage(m_encoding.m_codepage);
510
511         String sIntermediateFilename; // used when !bTempFile
512
513         if (bTempFile)
514         {
515                 bOpenSuccess = !!file.OpenCreate(pszFileName);
516         }
517         else
518         {
519                 sIntermediateFilename = env::GetTemporaryFileName(m_strTempPath,
520                         _T("MRG_"), NULL);
521                 if (sIntermediateFilename.empty())
522                         return SAVE_FAILED;  //Nothing to do if even tempfile name fails
523                 bOpenSuccess = !!file.OpenCreate(sIntermediateFilename);
524         }
525
526         if (!bOpenSuccess)
527         {       
528                 UniFile::UniError uniErr = file.GetLastUniError();
529                 if (uniErr.HasError())
530                 {
531                         sError = uniErr.GetError();
532                         if (bTempFile)
533                                 LogErrorString(strutils::format(_T("Opening file %s failed: %s"),
534                                         pszFileName.c_str(), sError.c_str()));
535                         else
536                                 LogErrorString(strutils::format(_T("Opening file %s failed: %s"),
537                                         sIntermediateFilename.c_str(), sError.c_str()));
538                 }
539                 return SAVE_FAILED;
540         }
541
542         file.WriteBom();
543
544         // line loop : get each real line and write it in the file
545         String sLine;
546         String sEol = GetStringEol(nCrlfStyle);
547         for (int line = nStartLine; line < nStartLine + nLines; ++line)
548         {
549                 if (GetLineFlags(line) & LF_GHOST)
550                         continue;
551
552                 // get the characters of the line (excluding EOL)
553                 if (GetLineLength(line) > 0)
554                 {
555                         int nLineLength = GetLineLength(line);
556                         sLine.resize(0);
557                         sLine.reserve(nLineLength + 4);
558                         sLine.append(GetLineChars(line), nLineLength);
559                 }
560                 else
561                         sLine = _T("");
562
563                 if (bTempFile)
564                         EscapeControlChars(sLine);
565                 // last real line ?
566                 int lastRealLine = ApparentLastRealLine();
567                 if (line == lastRealLine || lastRealLine == -1 )
568                 {
569                         // last real line is never EOL terminated
570                         ASSERT (_tcslen(GetLineEol(line)) == 0);
571                         // write the line and exit loop
572                         file.WriteString(sLine);
573                         break;
574                 }
575
576                 // normal real line : append an EOL
577                 if (nCrlfStyle == CRLF_STYLE_AUTOMATIC || nCrlfStyle == CRLF_STYLE_MIXED)
578                 {
579                         // either the EOL of the line (when preserve original EOL chars is on)
580                         sLine += GetLineEol(line);
581                 }
582                 else
583                 {
584                         // or the default EOL for this file
585                         sLine += sEol;
586                 }
587
588                 // write this line to the file (codeset or unicode conversions are done there
589                 file.WriteString(sLine);
590         }
591         file.Close();
592
593         if (!bTempFile)
594         {
595                 // If we are saving user files
596                 // we need an unpacker/packer, at least a "do nothing" one
597                 ASSERT(infoUnpacker != NULL);
598                 // repack the file here, overwrite the temporary file we did save in
599                 String csTempFileName = sIntermediateFilename;
600                 infoUnpacker->subcode = m_unpackerSubcode;
601                 if (!FileTransform::Packing(csTempFileName, *infoUnpacker))
602                 {
603                         try
604                         {
605                                 TFile(sIntermediateFilename).remove();
606                         }
607                         catch (Exception& e)
608                         {
609                                 LogErrorStringUTF8(e.displayText());
610                         }
611                         // returns now, don't overwrite the original file
612                         return SAVE_PACK_FAILED;
613                 }
614                 // the temp filename may have changed during packing
615                 if (csTempFileName != sIntermediateFilename)
616                 {
617                         try
618                         {
619                                 TFile(sIntermediateFilename).remove();
620                         }
621                         catch (Exception& e)
622                         {
623                                 LogErrorStringUTF8(e.displayText());
624                         }
625                         sIntermediateFilename = csTempFileName;
626                 }
627
628                 // Write tempfile over original file
629                 try
630                 {
631                         TFile file(sIntermediateFilename);
632                         file.copyTo(pszFileName);
633                         file.remove();
634                         if (bClearModifiedFlag)
635                         {
636                                 SetModified(false);
637                                 m_nSyncPosition = m_nUndoPosition;
638                         }
639                         bSaveSuccess = true;
640
641                         // remember revision number on save
642                         m_dwRevisionNumberOnSave = m_dwCurrentRevisionNumber;
643
644                         // redraw line revision marks
645                         UpdateViews (NULL, NULL, UPDATE_FLAGSONLY);     
646                 }
647                 catch (Exception& e)
648                 {
649                         LogErrorStringUTF8(e.displayText());
650                 }
651         }
652         else
653         {
654                 if (bClearModifiedFlag)
655                 {
656                         SetModified(false);
657                         m_nSyncPosition = m_nUndoPosition;
658                 }
659                 bSaveSuccess = true;
660         }
661
662         if (bSaveSuccess)
663                 return SAVE_DONE;
664         else
665                 return SAVE_FAILED;
666 }
667
668 /// Replace line (removing any eol, and only including one if in strText)
669 void CDiffTextBuffer::ReplaceFullLines(CDiffTextBuffer& dbuf, CDiffTextBuffer& sbuf, CCrystalTextView * pSource, int nLineBegin, int nLineEnd, int nAction /*=CE_ACTION_UNKNOWN*/)
670 {
671         CString strText;
672         if (nLineBegin != nLineEnd || sbuf.GetLineLength(nLineEnd) > 0)
673                 sbuf.GetTextWithoutEmptys(nLineBegin, 0, nLineEnd, sbuf.GetLineLength(nLineEnd), strText);
674         strText += sbuf.GetLineEol(nLineEnd);
675
676         if (nLineBegin != nLineEnd || dbuf.GetFullLineLength(nLineEnd) > 0)
677         {
678                 int nLineEndSource = nLineEnd < dbuf.GetLineCount() ? nLineEnd : dbuf.GetLineCount();
679                 if (nLineEnd+1 < GetLineCount())
680                         dbuf.DeleteText(pSource, nLineBegin, 0, nLineEndSource + 1, 0, nAction);
681                 else
682                         dbuf.DeleteText(pSource, nLineBegin, 0, nLineEndSource, dbuf.GetLineLength(nLineEndSource), nAction); 
683         }
684
685         if (int cchText = strText.GetLength())
686         {
687                 int endl,endc;
688                 dbuf.InsertText(pSource, nLineBegin, 0, strText, cchText, endl,endc, nAction);
689         }
690 }
691
692 bool CDiffTextBuffer::curUndoGroup()
693 {
694         return (m_aUndoBuf.size() != 0 && m_aUndoBuf[0].m_dwFlags&UNDO_BEGINGROUP);
695 }
696
697 bool CDiffTextBuffer::
698 DeleteText2(CCrystalTextView * pSource, int nStartLine, int nStartChar,
699         int nEndLine, int nEndChar, int nAction, bool bHistory /*=true*/)
700 {
701         for (auto syncpnt : m_pOwnerDoc->GetSyncPointList())
702         {
703                 const int nLineSyncPoint = syncpnt[m_nThisPane];
704                 if (((nStartChar == 0 && nStartLine == nLineSyncPoint) || nStartLine < nLineSyncPoint) &&
705                         nLineSyncPoint < nEndLine)
706                         m_pOwnerDoc->DeleteSyncPoint(m_nThisPane, nLineSyncPoint, false);
707         }
708         return CGhostTextBuffer::DeleteText2(pSource, nStartLine, nStartChar, nEndLine, nEndChar, nAction, bHistory);
709 }