OSDN Git Service

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