]> git.lyx.org Git - lyx.git/blob - src/Buffer.cpp
header cleanup.
[lyx.git] / src / Buffer.cpp
1 /**
2  * \file Buffer.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Stefan Schimanski
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "Buffer.h"
15
16 #include "Author.h"
17 #include "BiblioInfo.h"
18 #include "BranchList.h"
19 #include "buffer_funcs.h"
20 #include "BufferList.h"
21 #include "BufferParams.h"
22 #include "Bullet.h"
23 #include "Chktex.h"
24 #include "Converter.h"
25 #include "Counters.h"
26 #include "DocIterator.h"
27 #include "EmbeddedFiles.h"
28 #include "Encoding.h"
29 #include "ErrorList.h"
30 #include "Exporter.h"
31 #include "Format.h"
32 #include "FuncRequest.h"
33 #include "InsetIterator.h"
34 #include "InsetList.h"
35 #include "Language.h"
36 #include "LaTeXFeatures.h"
37 #include "LaTeX.h"
38 #include "Layout.h"
39 #include "Lexer.h"
40 #include "LyXAction.h"
41 #include "LyX.h"
42 #include "LyXRC.h"
43 #include "LyXVC.h"
44 #include "output_docbook.h"
45 #include "output.h"
46 #include "output_latex.h"
47 #include "output_plaintext.h"
48 #include "paragraph_funcs.h"
49 #include "Paragraph.h"
50 #include "ParagraphParameters.h"
51 #include "ParIterator.h"
52 #include "PDFOptions.h"
53 #include "Session.h"
54 #include "sgml.h"
55 #include "TexRow.h"
56 #include "TexStream.h"
57 #include "TextClassList.h"
58 #include "Text.h"
59 #include "TocBackend.h"
60 #include "Undo.h"
61 #include "VCBackend.h"
62 #include "version.h"
63
64 #include "insets/InsetBibitem.h"
65 #include "insets/InsetBibtex.h"
66 #include "insets/InsetInclude.h"
67 #include "insets/InsetText.h"
68
69 #include "mathed/MacroTable.h"
70 #include "mathed/MathMacroTemplate.h"
71 #include "mathed/MathSupport.h"
72
73 #include "frontends/alert.h"
74 #include "frontends/Delegates.h"
75 #include "frontends/WorkAreaManager.h"
76
77 #include "graphics/Previews.h"
78
79 #include "support/convert.h"
80 #include "support/debug.h"
81 #include "support/FileFilterList.h"
82 #include "support/FileNameList.h"
83 #include "support/filetools.h"
84 #include "support/ForkedCalls.h"
85 #include "support/gettext.h"
86 #include "support/gzstream.h"
87 #include "support/lstrings.h"
88 #include "support/lyxalgo.h"
89 #include "support/os.h"
90 #include "support/Path.h"
91 #include "support/textutils.h"
92 #include "support/types.h"
93 #include "support/FileZipListDir.h"
94
95 #if !defined (HAVE_FORK)
96 # define fork() -1
97 #endif
98
99 #include <boost/bind.hpp>
100 #include <boost/shared_ptr.hpp>
101
102 #include <algorithm>
103 #include <iomanip>
104 #include <stack>
105 #include <sstream>
106 #include <fstream>
107
108 using namespace std;
109 using namespace lyx::support;
110
111 namespace lyx {
112
113 namespace Alert = frontend::Alert;
114 namespace os = support::os;
115
116 namespace {
117
118 int const LYX_FORMAT = 308; // Uwe: Serbian-Latin
119
120 } // namespace anon
121
122
123 typedef map<string, bool> DepClean;
124
125 class Buffer::Impl
126 {
127 public:
128         Impl(Buffer & parent, FileName const & file, bool readonly);
129
130         ~Impl()
131         {
132                 if (wa_) {
133                         wa_->closeAll();
134                         delete wa_;
135                 }
136         }
137         
138         BufferParams params;
139         LyXVC lyxvc;
140         string temppath;
141         mutable TexRow texrow;
142         Buffer const * parent_buffer;
143
144         /// need to regenerate .tex?
145         DepClean dep_clean;
146
147         /// is save needed?
148         mutable bool lyx_clean;
149
150         /// is autosave needed?
151         mutable bool bak_clean;
152
153         /// is this a unnamed file (New...)?
154         bool unnamed;
155
156         /// buffer is r/o
157         bool read_only;
158
159         /// name of the file the buffer is associated with.
160         FileName filename;
161
162         /** Set to true only when the file is fully loaded.
163          *  Used to prevent the premature generation of previews
164          *  and by the citation inset.
165          */
166         bool file_fully_loaded;
167
168         /// our Text that should be wrapped in an InsetText
169         InsetText inset;
170
171         ///
172         mutable TocBackend toc_backend;
173
174         /// macro table
175         typedef map<unsigned int, MacroData, greater<int> > PositionToMacroMap;
176         typedef map<docstring, PositionToMacroMap> NameToPositionMacroMap;
177         NameToPositionMacroMap macros;
178
179         /// Container for all sort of Buffer dependant errors.
180         map<string, ErrorList> errorLists;
181
182         /// all embedded files of this buffer
183         EmbeddedFiles embedded_files;
184
185         /// timestamp and checksum used to test if the file has been externally
186         /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
187         time_t timestamp_;
188         unsigned long checksum_;
189
190         ///
191         frontend::WorkAreaManager * wa_;
192
193         ///
194         Undo undo_;
195
196         /// A cache for the bibfiles (including bibfiles of loaded child
197         /// documents), needed for appropriate update of natbib labels.
198         mutable FileNameList bibfilesCache_;
199 };
200
201
202 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
203         : parent_buffer(0), lyx_clean(true), bak_clean(true), unnamed(false),
204           read_only(readonly_), filename(file), file_fully_loaded(false),
205           inset(params), toc_backend(&parent), embedded_files(&parent),
206           timestamp_(0), checksum_(0), wa_(0), undo_(parent)
207 {
208         inset.setAutoBreakRows(true);
209         lyxvc.setBuffer(&parent);
210         temppath = createBufferTmpDir();
211
212         // FIXME: And now do something if temppath == string(), because we
213         // assume from now on that temppath points to a valid temp dir.
214         // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg67406.html
215
216         if (use_gui)
217                 wa_ = new frontend::WorkAreaManager;
218 }
219
220
221 Buffer::Buffer(string const & file, bool readonly)
222         : d(new Impl(*this, FileName(file), readonly)), gui_(0)
223 {
224         LYXERR(Debug::INFO, "Buffer::Buffer()");
225 }
226
227
228 Buffer::~Buffer()
229 {
230         LYXERR(Debug::INFO, "Buffer::~Buffer()");
231         // here the buffer should take care that it is
232         // saved properly, before it goes into the void.
233
234         // GuiView already destroyed
235         gui_ = 0;
236
237         Buffer const * master = masterBuffer();
238         if (master != this && use_gui)
239                 // We are closing buf which was a child document so we
240                 // must update the labels and section numbering of its master
241                 // Buffer.
242                 updateLabels(*master);
243
244         resetChildDocuments(false);
245
246         if (!temppath().empty() && !FileName(temppath()).destroyDirectory()) {
247                 Alert::warning(_("Could not remove temporary directory"),
248                         bformat(_("Could not remove the temporary directory %1$s"),
249                         from_utf8(temppath())));
250         }
251
252         // Remove any previewed LaTeX snippets associated with this buffer.
253         graphics::Previews::get().removeLoader(*this);
254
255         delete d;
256 }
257
258
259 void Buffer::changed() const
260 {
261         if (d->wa_)
262                 d->wa_->redrawAll();
263 }
264
265
266 frontend::WorkAreaManager & Buffer::workAreaManager() const
267 {
268         BOOST_ASSERT(d->wa_);
269         return *d->wa_;
270 }
271
272
273 Text & Buffer::text() const
274 {
275         return const_cast<Text &>(d->inset.text_);
276 }
277
278
279 Inset & Buffer::inset() const
280 {
281         return const_cast<InsetText &>(d->inset);
282 }
283
284
285 BufferParams & Buffer::params()
286 {
287         return d->params;
288 }
289
290
291 BufferParams const & Buffer::params() const
292 {
293         return d->params;
294 }
295
296
297 ParagraphList & Buffer::paragraphs()
298 {
299         return text().paragraphs();
300 }
301
302
303 ParagraphList const & Buffer::paragraphs() const
304 {
305         return text().paragraphs();
306 }
307
308
309 LyXVC & Buffer::lyxvc()
310 {
311         return d->lyxvc;
312 }
313
314
315 LyXVC const & Buffer::lyxvc() const
316 {
317         return d->lyxvc;
318 }
319
320
321 string const & Buffer::temppath() const
322 {
323         return d->temppath;
324 }
325
326
327 TexRow const & Buffer::texrow() const
328 {
329         return d->texrow;
330 }
331
332
333 TocBackend & Buffer::tocBackend() const
334 {
335         return d->toc_backend;
336 }
337
338
339 EmbeddedFiles & Buffer::embeddedFiles()
340 {
341         return d->embedded_files;
342 }
343
344
345 EmbeddedFiles const & Buffer::embeddedFiles() const
346 {
347         return d->embedded_files;
348 }
349
350
351 Undo & Buffer::undo()
352 {
353         return d->undo_;
354 }
355
356
357 string Buffer::latexName(bool const no_path) const
358 {
359         FileName latex_name = makeLatexName(d->filename);
360         return no_path ? latex_name.onlyFileName()
361                 : latex_name.absFilename();
362 }
363
364
365 string Buffer::logName(LogType * type) const
366 {
367         string const filename = latexName(false);
368
369         if (filename.empty()) {
370                 if (type)
371                         *type = latexlog;
372                 return string();
373         }
374
375         string const path = temppath();
376
377         FileName const fname(addName(temppath(),
378                                      onlyFilename(changeExtension(filename,
379                                                                   ".log"))));
380         FileName const bname(
381                 addName(path, onlyFilename(
382                         changeExtension(filename,
383                                         formats.extension("literate") + ".out"))));
384
385         // If no Latex log or Build log is newer, show Build log
386
387         if (bname.exists() &&
388             (!fname.exists() || fname.lastModified() < bname.lastModified())) {
389                 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
390                 if (type)
391                         *type = buildlog;
392                 return bname.absFilename();
393         }
394         LYXERR(Debug::FILES, "Log name calculated as: " << fname);
395         if (type)
396                         *type = latexlog;
397         return fname.absFilename();
398 }
399
400
401 void Buffer::setReadonly(bool const flag)
402 {
403         if (d->read_only != flag) {
404                 d->read_only = flag;
405                 setReadOnly(flag);
406         }
407 }
408
409
410 void Buffer::setFileName(string const & newfile)
411 {
412         d->filename = makeAbsPath(newfile);
413         setReadonly(d->filename.isReadOnly());
414         updateTitles();
415 }
416
417
418 int Buffer::readHeader(Lexer & lex)
419 {
420         int unknown_tokens = 0;
421         int line = -1;
422         int begin_header_line = -1;
423
424         // Initialize parameters that may be/go lacking in header:
425         params().branchlist().clear();
426         params().preamble.erase();
427         params().options.erase();
428         params().float_placement.erase();
429         params().paperwidth.erase();
430         params().paperheight.erase();
431         params().leftmargin.erase();
432         params().rightmargin.erase();
433         params().topmargin.erase();
434         params().bottommargin.erase();
435         params().headheight.erase();
436         params().headsep.erase();
437         params().footskip.erase();
438         params().listings_params.clear();
439         params().clearLayoutModules();
440         params().pdfoptions().clear();
441         
442         for (int i = 0; i < 4; ++i) {
443                 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
444                 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
445         }
446
447         ErrorList & errorList = d->errorLists["Parse"];
448
449         while (lex.isOK()) {
450                 lex.next();
451                 string const token = lex.getString();
452
453                 if (token.empty())
454                         continue;
455
456                 if (token == "\\end_header")
457                         break;
458
459                 ++line;
460                 if (token == "\\begin_header") {
461                         begin_header_line = line;
462                         continue;
463                 }
464
465                 LYXERR(Debug::PARSER, "Handling document header token: `"
466                                       << token << '\'');
467
468                 string unknown = params().readToken(lex, token, d->filename.onlyPath());
469                 if (!unknown.empty()) {
470                         if (unknown[0] != '\\' && token == "\\textclass") {
471                                 Alert::warning(_("Unknown document class"),
472                        bformat(_("Using the default document class, because the "
473                                               "class %1$s is unknown."), from_utf8(unknown)));
474                         } else {
475                                 ++unknown_tokens;
476                                 docstring const s = bformat(_("Unknown token: "
477                                                                         "%1$s %2$s\n"),
478                                                          from_utf8(token),
479                                                          lex.getDocString());
480                                 errorList.push_back(ErrorItem(_("Document header error"),
481                                         s, -1, 0, 0));
482                         }
483                 }
484         }
485         if (begin_header_line) {
486                 docstring const s = _("\\begin_header is missing");
487                 errorList.push_back(ErrorItem(_("Document header error"),
488                         s, -1, 0, 0));
489         }
490
491         return unknown_tokens;
492 }
493
494
495 // Uwe C. Schroeder
496 // changed to be public and have one parameter
497 // Returns false if "\end_document" is not read (Asger)
498 bool Buffer::readDocument(Lexer & lex)
499 {
500         ErrorList & errorList = d->errorLists["Parse"];
501         errorList.clear();
502
503         lex.next();
504         string const token = lex.getString();
505         if (token != "\\begin_document") {
506                 docstring const s = _("\\begin_document is missing");
507                 errorList.push_back(ErrorItem(_("Document header error"),
508                         s, -1, 0, 0));
509         }
510
511         // we are reading in a brand new document
512         BOOST_ASSERT(paragraphs().empty());
513
514         readHeader(lex);
515         TextClass const & baseClass = textclasslist[params().getBaseClass()];
516         if (!baseClass.load(filePath())) {
517                 string theclass = baseClass.name();
518                 Alert::error(_("Can't load document class"), bformat(
519                         _("Using the default document class, because the "
520                                      "class %1$s could not be loaded."), from_utf8(theclass)));
521                 params().setBaseClass(defaultTextclass());
522         }
523
524         if (params().outputChanges) {
525                 bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
526                 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
527                                   LaTeXFeatures::isAvailable("xcolor");
528
529                 if (!dvipost && !xcolorsoul) {
530                         Alert::warning(_("Changes not shown in LaTeX output"),
531                                        _("Changes will not be highlighted in LaTeX output, "
532                                          "because neither dvipost nor xcolor/soul are installed.\n"
533                                          "Please install these packages or redefine "
534                                          "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
535                 } else if (!xcolorsoul) {
536                         Alert::warning(_("Changes not shown in LaTeX output"),
537                                        _("Changes will not be highlighted in LaTeX output "
538                                          "when using pdflatex, because xcolor and soul are not installed.\n"
539                                          "Please install both packages or redefine "
540                                          "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
541                 }
542         }
543
544         // read main text
545         bool const res = text().read(*this, lex, errorList);
546         for_each(text().paragraphs().begin(),
547                  text().paragraphs().end(),
548                  bind(&Paragraph::setInsetOwner, _1, &inset()));
549
550         return res;
551 }
552
553
554 // needed to insert the selection
555 void Buffer::insertStringAsLines(ParagraphList & pars,
556         pit_type & pit, pos_type & pos,
557         Font const & fn, docstring const & str, bool autobreakrows)
558 {
559         Font font = fn;
560
561         // insert the string, don't insert doublespace
562         bool space_inserted = true;
563         for (docstring::const_iterator cit = str.begin();
564             cit != str.end(); ++cit) {
565                 Paragraph & par = pars[pit];
566                 if (*cit == '\n') {
567                         if (autobreakrows && (!par.empty() || par.allowEmpty())) {
568                                 breakParagraph(params(), pars, pit, pos,
569                                                par.layout()->isEnvironment());
570                                 ++pit;
571                                 pos = 0;
572                                 space_inserted = true;
573                         } else {
574                                 continue;
575                         }
576                         // do not insert consecutive spaces if !free_spacing
577                 } else if ((*cit == ' ' || *cit == '\t') &&
578                            space_inserted && !par.isFreeSpacing()) {
579                         continue;
580                 } else if (*cit == '\t') {
581                         if (!par.isFreeSpacing()) {
582                                 // tabs are like spaces here
583                                 par.insertChar(pos, ' ', font, params().trackChanges);
584                                 ++pos;
585                                 space_inserted = true;
586                         } else {
587                                 const pos_type n = 8 - pos % 8;
588                                 for (pos_type i = 0; i < n; ++i) {
589                                         par.insertChar(pos, ' ', font, params().trackChanges);
590                                         ++pos;
591                                 }
592                                 space_inserted = true;
593                         }
594                 } else if (!isPrintable(*cit)) {
595                         // Ignore unprintables
596                         continue;
597                 } else {
598                         // just insert the character
599                         par.insertChar(pos, *cit, font, params().trackChanges);
600                         ++pos;
601                         space_inserted = (*cit == ' ');
602                 }
603
604         }
605 }
606
607
608 bool Buffer::readString(string const & s)
609 {
610         params().compressed = false;
611
612         // remove dummy empty par
613         paragraphs().clear();
614         Lexer lex(0, 0);
615         istringstream is(s);
616         lex.setStream(is);
617         FileName const name = FileName::tempName();
618         switch (readFile(lex, name, true)) {
619         case failure:
620                 return false;
621         case wrongversion: {
622                 // We need to call lyx2lyx, so write the input to a file
623                 ofstream os(name.toFilesystemEncoding().c_str());
624                 os << s;
625                 os.close();
626                 return readFile(name);
627         }
628         case success:
629                 break;
630         }
631
632         return true;
633 }
634
635
636 bool Buffer::readFile(FileName const & filename)
637 {
638         FileName fname(filename);
639         // Check if the file is compressed.
640         string format = filename.guessFormatFromContents();
641         if (format == "zip") {
642                 // decompress to a temp directory
643                 LYXERR(Debug::FILES, filename << " is in zip format. Unzip to " << temppath());
644                 ::unzipToDir(filename.toFilesystemEncoding(), temppath());
645                 //
646                 FileName lyxfile(addName(temppath(), "content.lyx"));
647                 // if both manifest.txt and file.lyx exist, this is am embedded file
648                 if (lyxfile.exists()) {
649                         params().embedded = true;
650                         fname = lyxfile;
651                 }
652         }
653         // The embedded lyx file can also be compressed, for backward compatibility
654         format = fname.guessFormatFromContents();
655         if (format == "gzip" || format == "zip" || format == "compress")
656                 params().compressed = true;
657
658         // remove dummy empty par
659         paragraphs().clear();
660         Lexer lex(0, 0);
661         lex.setFile(fname);
662         if (readFile(lex, fname) != success)
663                 return false;
664
665         return true;
666 }
667
668
669 bool Buffer::isFullyLoaded() const
670 {
671         return d->file_fully_loaded;
672 }
673
674
675 void Buffer::setFullyLoaded(bool value)
676 {
677         d->file_fully_loaded = value;
678 }
679
680
681 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
682                 bool fromstring)
683 {
684         BOOST_ASSERT(!filename.empty());
685
686         if (!lex.isOK()) {
687                 Alert::error(_("Document could not be read"),
688                              bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
689                 return failure;
690         }
691
692         lex.next();
693         string const token = lex.getString();
694
695         if (!lex) {
696                 Alert::error(_("Document could not be read"),
697                              bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
698                 return failure;
699         }
700
701         // the first token _must_ be...
702         if (token != "\\lyxformat") {
703                 lyxerr << "Token: " << token << endl;
704
705                 Alert::error(_("Document format failure"),
706                              bformat(_("%1$s is not a LyX document."),
707                                        from_utf8(filename.absFilename())));
708                 return failure;
709         }
710
711         lex.next();
712         string tmp_format = lex.getString();
713         //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
714         // if present remove ".," from string.
715         string::size_type dot = tmp_format.find_first_of(".,");
716         //lyxerr << "           dot found at " << dot << endl;
717         if (dot != string::npos)
718                         tmp_format.erase(dot, 1);
719         int const file_format = convert<int>(tmp_format);
720         //lyxerr << "format: " << file_format << endl;
721
722         // save timestamp and checksum of the original disk file, making sure
723         // to not overwrite them with those of the file created in the tempdir
724         // when it has to be converted to the current format.
725         if (!d->checksum_) {
726                 // Save the timestamp and checksum of disk file. If filename is an
727                 // emergency file, save the timestamp and checksum of the original lyx file
728                 // because isExternallyModified will check for this file. (BUG4193)
729                 string diskfile = filename.absFilename();
730                 if (suffixIs(diskfile, ".emergency"))
731                         diskfile = diskfile.substr(0, diskfile.size() - 10);
732                 saveCheckSum(FileName(diskfile));
733         }
734
735         if (file_format != LYX_FORMAT) {
736
737                 if (fromstring)
738                         // lyx2lyx would fail
739                         return wrongversion;
740
741                 FileName const tmpfile = FileName::tempName();
742                 if (tmpfile.empty()) {
743                         Alert::error(_("Conversion failed"),
744                                      bformat(_("%1$s is from a different"
745                                               " version of LyX, but a temporary"
746                                               " file for converting it could"
747                                                             " not be created."),
748                                               from_utf8(filename.absFilename())));
749                         return failure;
750                 }
751                 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
752                 if (lyx2lyx.empty()) {
753                         Alert::error(_("Conversion script not found"),
754                                      bformat(_("%1$s is from a different"
755                                                " version of LyX, but the"
756                                                " conversion script lyx2lyx"
757                                                             " could not be found."),
758                                                from_utf8(filename.absFilename())));
759                         return failure;
760                 }
761                 ostringstream command;
762                 command << os::python()
763                         << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
764                         << " -t " << convert<string>(LYX_FORMAT)
765                         << " -o " << quoteName(tmpfile.toFilesystemEncoding())
766                         << ' ' << quoteName(filename.toFilesystemEncoding());
767                 string const command_str = command.str();
768
769                 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
770
771                 cmd_ret const ret = runCommand(command_str);
772                 if (ret.first != 0) {
773                         Alert::error(_("Conversion script failed"),
774                                      bformat(_("%1$s is from a different version"
775                                               " of LyX, but the lyx2lyx script"
776                                                             " failed to convert it."),
777                                               from_utf8(filename.absFilename())));
778                         return failure;
779                 } else {
780                         bool const ret = readFile(tmpfile);
781                         // Do stuff with tmpfile name and buffer name here.
782                         return ret ? success : failure;
783                 }
784
785         }
786
787         if (readDocument(lex)) {
788                 Alert::error(_("Document format failure"),
789                              bformat(_("%1$s ended unexpectedly, which means"
790                                                     " that it is probably corrupted."),
791                                        from_utf8(filename.absFilename())));
792         }
793
794         d->file_fully_loaded = true;
795         return success;
796 }
797
798
799 // Should probably be moved to somewhere else: BufferView? LyXView?
800 bool Buffer::save() const
801 {
802         // We don't need autosaves in the immediate future. (Asger)
803         resetAutosaveTimers();
804
805         string const encodedFilename = d->filename.toFilesystemEncoding();
806
807         FileName backupName;
808         bool madeBackup = false;
809
810         // make a backup if the file already exists
811         if (lyxrc.make_backup && fileName().exists()) {
812                 backupName = FileName(absFileName() + '~');
813                 if (!lyxrc.backupdir_path.empty()) {
814                         string const mangledName =
815                                 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
816                         backupName = FileName(addName(lyxrc.backupdir_path,
817                                                       mangledName));
818                 }
819                 if (fileName().copyTo(backupName)) {
820                         madeBackup = true;
821                 } else {
822                         Alert::error(_("Backup failure"),
823                                      bformat(_("Cannot create backup file %1$s.\n"
824                                                "Please check whether the directory exists and is writeable."),
825                                              from_utf8(backupName.absFilename())));
826                         //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
827                 }
828         }
829
830         // ask if the disk file has been externally modified (use checksum method)
831         if (fileName().exists() && isExternallyModified(checksum_method)) {
832                 docstring const file = makeDisplayPath(absFileName(), 20);
833                 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
834                                                              "you want to overwrite this file?"), file);
835                 int const ret = Alert::prompt(_("Overwrite modified file?"),
836                         text, 1, 1, _("&Overwrite"), _("&Cancel"));
837                 if (ret == 1)
838                         return false;
839         }
840
841         if (writeFile(d->filename)) {
842                 markClean();
843                 return true;
844         } else {
845                 // Saving failed, so backup is not backup
846                 if (madeBackup)
847                         backupName.moveTo(d->filename);
848                 return false;
849         }
850 }
851
852
853 bool Buffer::writeFile(FileName const & fname) const
854 {
855         if (d->read_only && fname == d->filename)
856                 return false;
857
858         bool retval = false;
859
860         FileName content;
861         if (params().embedded)
862                 // first write the .lyx file to the temporary directory
863                 content = FileName(addName(temppath(), "content.lyx"));
864         else
865                 content = fname;
866
867         docstring const str = bformat(_("Saving document %1$s..."),
868                 makeDisplayPath(content.absFilename()));
869         message(str);
870
871         if (params().compressed) {
872                 gz::ogzstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
873                 retval = ofs && write(ofs);
874         } else {
875                 ofstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
876                 retval = ofs && write(ofs);
877         }
878
879         if (!retval) {
880                 message(str + _(" could not write file!."));
881                 return false;
882         }
883
884         removeAutosaveFile(d->filename.absFilename());
885         saveCheckSum(d->filename);
886         message(str + _(" done."));
887
888         if (!params().embedded)
889                 return true;
890
891         message(str + _(" writing embedded files!."));
892         // if embedding is enabled, write file.lyx and all the embedded files
893         // to the zip file fname.
894         if (!d->embedded_files.writeFile(fname)) {
895                 message(str + _(" could not write embedded files!."));
896                 return false;
897         }
898         message(str + _(" error while writing embedded files."));
899         return true;
900 }
901
902
903 bool Buffer::write(ostream & ofs) const
904 {
905 #ifdef HAVE_LOCALE
906         // Use the standard "C" locale for file output.
907         ofs.imbue(locale::classic());
908 #endif
909
910         // The top of the file should not be written by params().
911
912         // write out a comment in the top of the file
913         ofs << "#LyX " << lyx_version
914             << " created this file. For more info see http://www.lyx.org/\n"
915             << "\\lyxformat " << LYX_FORMAT << "\n"
916             << "\\begin_document\n";
917
918
919         /// For each author, set 'used' to true if there is a change
920         /// by this author in the document; otherwise set it to 'false'.
921         AuthorList::Authors::const_iterator a_it = params().authors().begin();
922         AuthorList::Authors::const_iterator a_end = params().authors().end();
923         for (; a_it != a_end; ++a_it)
924                 a_it->second.setUsed(false);
925
926         ParIterator const end = par_iterator_end();
927         ParIterator it = par_iterator_begin();
928         for ( ; it != end; ++it)
929                 it->checkAuthors(params().authors());
930
931         // now write out the buffer parameters.
932         ofs << "\\begin_header\n";
933         params().writeFile(ofs);
934         ofs << "\\end_header\n";
935
936         // write the text
937         ofs << "\n\\begin_body\n";
938         text().write(*this, ofs);
939         ofs << "\n\\end_body\n";
940
941         // Write marker that shows file is complete
942         ofs << "\\end_document" << endl;
943
944         // Shouldn't really be needed....
945         //ofs.close();
946
947         // how to check if close went ok?
948         // Following is an attempt... (BE 20001011)
949
950         // good() returns false if any error occured, including some
951         //        formatting error.
952         // bad()  returns true if something bad happened in the buffer,
953         //        which should include file system full errors.
954
955         bool status = true;
956         if (!ofs) {
957                 status = false;
958                 lyxerr << "File was not closed properly." << endl;
959         }
960
961         return status;
962 }
963
964
965 bool Buffer::makeLaTeXFile(FileName const & fname,
966                            string const & original_path,
967                            OutputParams const & runparams,
968                            bool output_preamble, bool output_body) const
969 {
970         string const encoding = runparams.encoding->iconvName();
971         LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
972
973         odocfstream ofs;
974         try { ofs.reset(encoding); }
975         catch (iconv_codecvt_facet_exception & e) {
976                 lyxerr << "Caught iconv exception: " << e.what() << endl;
977                 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
978                         "verify that the support software for your encoding (%1$s) is "
979                         "properly installed"), from_ascii(encoding)));
980                 return false;
981         }
982         if (!openFileWrite(ofs, fname))
983                 return false;
984
985         //TexStream ts(ofs.rdbuf(), &texrow());
986
987         bool failed_export = false;
988         try {
989                 d->texrow.reset();
990                 writeLaTeXSource(ofs, original_path,
991                       runparams, output_preamble, output_body);
992         }
993         catch (iconv_codecvt_facet_exception & e) {
994                 lyxerr << "Caught iconv exception: " << e.what() << endl;
995                 failed_export = true;
996         }
997         catch (exception const & e) {
998                 lyxerr << "Caught \"normal\" exception: " << e.what() << endl;
999                 failed_export = true;
1000         }
1001         catch (...) {
1002                 lyxerr << "Caught some really weird exception..." << endl;
1003                 LyX::cref().exit(1);
1004         }
1005
1006         ofs.close();
1007         if (ofs.fail()) {
1008                 failed_export = true;
1009                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1010         }
1011
1012         if (failed_export) {
1013                 Alert::error(_("Encoding error"),
1014                         _("Some characters of your document are probably not "
1015                         "representable in the chosen encoding.\n"
1016                         "Changing the document encoding to utf8 could help."));
1017                 return false;
1018         }
1019         return true;
1020 }
1021
1022
1023 void Buffer::writeLaTeXSource(odocstream & os,
1024                            string const & original_path,
1025                            OutputParams const & runparams_in,
1026                            bool const output_preamble, bool const output_body) const
1027 {
1028         OutputParams runparams = runparams_in;
1029
1030         // validate the buffer.
1031         LYXERR(Debug::LATEX, "  Validating buffer...");
1032         LaTeXFeatures features(*this, params(), runparams);
1033         validate(features);
1034         LYXERR(Debug::LATEX, "  Buffer validation done.");
1035
1036         // The starting paragraph of the coming rows is the
1037         // first paragraph of the document. (Asger)
1038         if (output_preamble && runparams.nice) {
1039                 os << "%% LyX " << lyx_version << " created this file.  "
1040                         "For more info, see http://www.lyx.org/.\n"
1041                         "%% Do not edit unless you really know what "
1042                         "you are doing.\n";
1043                 d->texrow.newline();
1044                 d->texrow.newline();
1045         }
1046         LYXERR(Debug::INFO, "lyx document header finished");
1047         // There are a few differences between nice LaTeX and usual files:
1048         // usual is \batchmode and has a
1049         // special input@path to allow the including of figures
1050         // with either \input or \includegraphics (what figinsets do).
1051         // input@path is set when the actual parameter
1052         // original_path is set. This is done for usual tex-file, but not
1053         // for nice-latex-file. (Matthias 250696)
1054         // Note that input@path is only needed for something the user does
1055         // in the preamble, included .tex files or ERT, files included by
1056         // LyX work without it.
1057         if (output_preamble) {
1058                 if (!runparams.nice) {
1059                         // code for usual, NOT nice-latex-file
1060                         os << "\\batchmode\n"; // changed
1061                         // from \nonstopmode
1062                         d->texrow.newline();
1063                 }
1064                 if (!original_path.empty()) {
1065                         // FIXME UNICODE
1066                         // We don't know the encoding of inputpath
1067                         docstring const inputpath = from_utf8(latex_path(original_path));
1068                         os << "\\makeatletter\n"
1069                            << "\\def\\input@path{{"
1070                            << inputpath << "/}}\n"
1071                            << "\\makeatother\n";
1072                         d->texrow.newline();
1073                         d->texrow.newline();
1074                         d->texrow.newline();
1075                 }
1076
1077                 // Write the preamble
1078                 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1079
1080                 if (!output_body)
1081                         return;
1082
1083                 // make the body.
1084                 os << "\\begin{document}\n";
1085                 d->texrow.newline();
1086         } // output_preamble
1087
1088         d->texrow.start(paragraphs().begin()->id(), 0);
1089         
1090         LYXERR(Debug::INFO, "preamble finished, now the body.");
1091
1092         // if we are doing a real file with body, even if this is the
1093         // child of some other buffer, let's cut the link here.
1094         // This happens for example if only a child document is printed.
1095         Buffer const * save_parent = 0;
1096         if (output_preamble) {
1097                 save_parent = d->parent_buffer;
1098                 d->parent_buffer = 0;
1099         }
1100
1101         loadChildDocuments();
1102
1103         // the real stuff
1104         latexParagraphs(*this, paragraphs(), os, d->texrow, runparams);
1105
1106         // Restore the parenthood if needed
1107         if (output_preamble)
1108                 d->parent_buffer = save_parent;
1109
1110         // add this just in case after all the paragraphs
1111         os << endl;
1112         d->texrow.newline();
1113
1114         if (output_preamble) {
1115                 os << "\\end{document}\n";
1116                 d->texrow.newline();
1117                 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1118         } else {
1119                 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1120         }
1121         runparams_in.encoding = runparams.encoding;
1122
1123         // Just to be sure. (Asger)
1124         d->texrow.newline();
1125
1126         LYXERR(Debug::INFO, "Finished making LaTeX file.");
1127         LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1128 }
1129
1130
1131 bool Buffer::isLatex() const
1132 {
1133         return params().getTextClass().outputType() == LATEX;
1134 }
1135
1136
1137 bool Buffer::isLiterate() const
1138 {
1139         return params().getTextClass().outputType() == LITERATE;
1140 }
1141
1142
1143 bool Buffer::isDocBook() const
1144 {
1145         return params().getTextClass().outputType() == DOCBOOK;
1146 }
1147
1148
1149 void Buffer::makeDocBookFile(FileName const & fname,
1150                               OutputParams const & runparams,
1151                               bool const body_only) const
1152 {
1153         LYXERR(Debug::LATEX, "makeDocBookFile...");
1154
1155         //ofstream ofs;
1156         odocfstream ofs;
1157         if (!openFileWrite(ofs, fname))
1158                 return;
1159
1160         writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1161
1162         ofs.close();
1163         if (ofs.fail())
1164                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1165 }
1166
1167
1168 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1169                              OutputParams const & runparams,
1170                              bool const only_body) const
1171 {
1172         LaTeXFeatures features(*this, params(), runparams);
1173         validate(features);
1174
1175         d->texrow.reset();
1176
1177         TextClass const & tclass = params().getTextClass();
1178         string const top_element = tclass.latexname();
1179
1180         if (!only_body) {
1181                 if (runparams.flavor == OutputParams::XML)
1182                         os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1183
1184                 // FIXME UNICODE
1185                 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1186
1187                 // FIXME UNICODE
1188                 if (! tclass.class_header().empty())
1189                         os << from_ascii(tclass.class_header());
1190                 else if (runparams.flavor == OutputParams::XML)
1191                         os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1192                             << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1193                 else
1194                         os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1195
1196                 docstring preamble = from_utf8(params().preamble);
1197                 if (runparams.flavor != OutputParams::XML ) {
1198                         preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1199                         preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1200                         preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1201                         preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1202                 }
1203
1204                 string const name = runparams.nice
1205                         ? changeExtension(absFileName(), ".sgml") : fname;
1206                 preamble += features.getIncludedFiles(name);
1207                 preamble += features.getLyXSGMLEntities();
1208
1209                 if (!preamble.empty()) {
1210                         os << "\n [ " << preamble << " ]";
1211                 }
1212                 os << ">\n\n";
1213         }
1214
1215         string top = top_element;
1216         top += " lang=\"";
1217         if (runparams.flavor == OutputParams::XML)
1218                 top += params().language->code();
1219         else
1220                 top += params().language->code().substr(0,2);
1221         top += '"';
1222
1223         if (!params().options.empty()) {
1224                 top += ' ';
1225                 top += params().options;
1226         }
1227
1228         os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1229             << " file was created by LyX " << lyx_version
1230             << "\n  See http://www.lyx.org/ for more information -->\n";
1231
1232         params().getTextClass().counters().reset();
1233
1234         loadChildDocuments();
1235
1236         sgml::openTag(os, top);
1237         os << '\n';
1238         docbookParagraphs(paragraphs(), *this, os, runparams);
1239         sgml::closeTag(os, top_element);
1240 }
1241
1242
1243 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1244 // Other flags: -wall -v0 -x
1245 int Buffer::runChktex()
1246 {
1247         setBusy(true);
1248
1249         // get LaTeX-Filename
1250         FileName const path(temppath());
1251         string const name = addName(path.absFilename(), latexName());
1252         string const org_path = filePath();
1253
1254         PathChanger p(path); // path to LaTeX file
1255         message(_("Running chktex..."));
1256
1257         // Generate the LaTeX file if neccessary
1258         OutputParams runparams(&params().encoding());
1259         runparams.flavor = OutputParams::LATEX;
1260         runparams.nice = false;
1261         makeLaTeXFile(FileName(name), org_path, runparams);
1262
1263         TeXErrors terr;
1264         Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1265         int const res = chktex.run(terr); // run chktex
1266
1267         if (res == -1) {
1268                 Alert::error(_("chktex failure"),
1269                              _("Could not run chktex successfully."));
1270         } else if (res > 0) {
1271                 ErrorList & errlist = d->errorLists["ChkTeX"];
1272                 errlist.clear();
1273                 bufferErrors(terr, errlist);
1274         }
1275
1276         setBusy(false);
1277
1278         errors("ChkTeX");
1279
1280         return res;
1281 }
1282
1283
1284 void Buffer::validate(LaTeXFeatures & features) const
1285 {
1286         params().validate(features);
1287
1288         loadChildDocuments();
1289
1290         for_each(paragraphs().begin(), paragraphs().end(),
1291                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1292
1293         if (lyxerr.debugging(Debug::LATEX)) {
1294                 features.showStruct();
1295         }
1296 }
1297
1298
1299 void Buffer::getLabelList(vector<docstring> & list) const
1300 {
1301         /// if this is a child document and the parent is already loaded
1302         /// Use the parent's list instead  [ale990407]
1303         Buffer const * tmp = masterBuffer();
1304         if (!tmp) {
1305                 lyxerr << "masterBuffer() failed!" << endl;
1306                 BOOST_ASSERT(tmp);
1307         }
1308         if (tmp != this) {
1309                 tmp->getLabelList(list);
1310                 return;
1311         }
1312
1313         loadChildDocuments();
1314
1315         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1316                 it.nextInset()->getLabelList(*this, list);
1317 }
1318
1319
1320 void Buffer::updateBibfilesCache() const
1321 {
1322         // if this is a child document and the parent is already loaded
1323         // update the parent's cache instead
1324         Buffer const * tmp = masterBuffer();
1325         BOOST_ASSERT(tmp);
1326         if (tmp != this) {
1327                 tmp->updateBibfilesCache();
1328                 return;
1329         }
1330
1331         d->bibfilesCache_.clear();
1332         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1333                 if (it->lyxCode() == BIBTEX_CODE) {
1334                         InsetBibtex const & inset =
1335                                 static_cast<InsetBibtex const &>(*it);
1336                         FileNameList const bibfiles = inset.getFiles(*this);
1337                         d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1338                                 bibfiles.begin(),
1339                                 bibfiles.end());
1340                 } else if (it->lyxCode() == INCLUDE_CODE) {
1341                         InsetInclude & inset =
1342                                 static_cast<InsetInclude &>(*it);
1343                         inset.updateBibfilesCache(*this);
1344                         FileNameList const & bibfiles =
1345                                         inset.getBibfilesCache(*this);
1346                         d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1347                                 bibfiles.begin(),
1348                                 bibfiles.end());
1349                 }
1350         }
1351 }
1352
1353
1354 FileNameList const & Buffer::getBibfilesCache() const
1355 {
1356         // if this is a child document and the parent is already loaded
1357         // use the parent's cache instead
1358         Buffer const * tmp = masterBuffer();
1359         BOOST_ASSERT(tmp);
1360         if (tmp != this)
1361                 return tmp->getBibfilesCache();
1362
1363         // We update the cache when first used instead of at loading time.
1364         if (d->bibfilesCache_.empty())
1365                 const_cast<Buffer *>(this)->updateBibfilesCache();
1366
1367         return d->bibfilesCache_;
1368 }
1369
1370
1371 bool Buffer::isDepClean(string const & name) const
1372 {
1373         DepClean::const_iterator const it = d->dep_clean.find(name);
1374         if (it == d->dep_clean.end())
1375                 return true;
1376         return it->second;
1377 }
1378
1379
1380 void Buffer::markDepClean(string const & name)
1381 {
1382         d->dep_clean[name] = true;
1383 }
1384
1385
1386 bool Buffer::dispatch(string const & command, bool * result)
1387 {
1388         return dispatch(lyxaction.lookupFunc(command), result);
1389 }
1390
1391
1392 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1393 {
1394         bool dispatched = true;
1395
1396         switch (func.action) {
1397                 case LFUN_BUFFER_EXPORT: {
1398                         bool const tmp = doExport(to_utf8(func.argument()), false);
1399                         if (result)
1400                                 *result = tmp;
1401                         break;
1402                 }
1403
1404                 default:
1405                         dispatched = false;
1406         }
1407         return dispatched;
1408 }
1409
1410
1411 void Buffer::changeLanguage(Language const * from, Language const * to)
1412 {
1413         BOOST_ASSERT(from);
1414         BOOST_ASSERT(to);
1415
1416         for_each(par_iterator_begin(),
1417                  par_iterator_end(),
1418                  bind(&Paragraph::changeLanguage, _1, params(), from, to));
1419 }
1420
1421
1422 bool Buffer::isMultiLingual() const
1423 {
1424         ParConstIterator end = par_iterator_end();
1425         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1426                 if (it->isMultiLingual(params()))
1427                         return true;
1428
1429         return false;
1430 }
1431
1432
1433 ParIterator Buffer::getParFromID(int const id) const
1434 {
1435         ParConstIterator it = par_iterator_begin();
1436         ParConstIterator const end = par_iterator_end();
1437
1438         if (id < 0) {
1439                 // John says this is called with id == -1 from undo
1440                 lyxerr << "getParFromID(), id: " << id << endl;
1441                 return end;
1442         }
1443
1444         for (; it != end; ++it)
1445                 if (it->id() == id)
1446                         return it;
1447
1448         return end;
1449 }
1450
1451
1452 bool Buffer::hasParWithID(int const id) const
1453 {
1454         ParConstIterator const it = getParFromID(id);
1455         return it != par_iterator_end();
1456 }
1457
1458
1459 ParIterator Buffer::par_iterator_begin()
1460 {
1461         return lyx::par_iterator_begin(inset());
1462 }
1463
1464
1465 ParIterator Buffer::par_iterator_end()
1466 {
1467         return lyx::par_iterator_end(inset());
1468 }
1469
1470
1471 ParConstIterator Buffer::par_iterator_begin() const
1472 {
1473         return lyx::par_const_iterator_begin(inset());
1474 }
1475
1476
1477 ParConstIterator Buffer::par_iterator_end() const
1478 {
1479         return lyx::par_const_iterator_end(inset());
1480 }
1481
1482
1483 Language const * Buffer::language() const
1484 {
1485         return params().language;
1486 }
1487
1488
1489 docstring const Buffer::B_(string const & l10n) const
1490 {
1491         return params().B_(l10n);
1492 }
1493
1494
1495 bool Buffer::isClean() const
1496 {
1497         return d->lyx_clean;
1498 }
1499
1500
1501 bool Buffer::isBakClean() const
1502 {
1503         return d->bak_clean;
1504 }
1505
1506
1507 bool Buffer::isExternallyModified(CheckMethod method) const
1508 {
1509         BOOST_ASSERT(d->filename.exists());
1510         // if method == timestamp, check timestamp before checksum
1511         return (method == checksum_method 
1512                 || d->timestamp_ != d->filename.lastModified())
1513                 && d->checksum_ != d->filename.checksum();
1514 }
1515
1516
1517 void Buffer::saveCheckSum(FileName const & file) const
1518 {
1519         if (file.exists()) {
1520                 d->timestamp_ = file.lastModified();
1521                 d->checksum_ = file.checksum();
1522         } else {
1523                 // in the case of save to a new file.
1524                 d->timestamp_ = 0;
1525                 d->checksum_ = 0;
1526         }
1527 }
1528
1529
1530 void Buffer::markClean() const
1531 {
1532         if (!d->lyx_clean) {
1533                 d->lyx_clean = true;
1534                 updateTitles();
1535         }
1536         // if the .lyx file has been saved, we don't need an
1537         // autosave
1538         d->bak_clean = true;
1539 }
1540
1541
1542 void Buffer::markBakClean() const
1543 {
1544         d->bak_clean = true;
1545 }
1546
1547
1548 void Buffer::setUnnamed(bool flag)
1549 {
1550         d->unnamed = flag;
1551 }
1552
1553
1554 bool Buffer::isUnnamed() const
1555 {
1556         return d->unnamed;
1557 }
1558
1559
1560 // FIXME: this function should be moved to buffer_pimpl.C
1561 void Buffer::markDirty()
1562 {
1563         if (d->lyx_clean) {
1564                 d->lyx_clean = false;
1565                 updateTitles();
1566         }
1567         d->bak_clean = false;
1568
1569         DepClean::iterator it = d->dep_clean.begin();
1570         DepClean::const_iterator const end = d->dep_clean.end();
1571
1572         for (; it != end; ++it)
1573                 it->second = false;
1574 }
1575
1576
1577 FileName Buffer::fileName() const
1578 {
1579         return d->filename;
1580 }
1581
1582
1583 string Buffer::absFileName() const
1584 {
1585         return d->filename.absFilename();
1586 }
1587
1588
1589 string Buffer::filePath() const
1590 {
1591         return d->filename.onlyPath().absFilename();
1592 }
1593
1594
1595 bool Buffer::isReadonly() const
1596 {
1597         return d->read_only;
1598 }
1599
1600
1601 void Buffer::setParent(Buffer const * buffer)
1602 {
1603         // Avoids recursive include.
1604         d->parent_buffer = buffer == this ? 0 : buffer;
1605 }
1606
1607
1608 Buffer const * Buffer::parent()
1609 {
1610         return d->parent_buffer;
1611 }
1612
1613
1614 Buffer const * Buffer::masterBuffer() const
1615 {
1616         if (!d->parent_buffer)
1617                 return this;
1618         
1619         return d->parent_buffer->masterBuffer();
1620 }
1621
1622
1623 bool Buffer::hasMacro(docstring const & name, Paragraph const & par) const
1624 {
1625         Impl::PositionToMacroMap::iterator it;
1626         it = d->macros[name].upper_bound(par.macrocontextPosition());
1627         if (it != d->macros[name].end())
1628                 return true;
1629
1630         // If there is a master buffer, query that
1631         Buffer const * master = masterBuffer();
1632         if (master && master != this)
1633                 return master->hasMacro(name);
1634
1635         return MacroTable::globalMacros().has(name);
1636 }
1637
1638
1639 bool Buffer::hasMacro(docstring const & name) const
1640 {
1641         if( !d->macros[name].empty() )
1642                 return true;
1643
1644         // If there is a master buffer, query that
1645         Buffer const * master = masterBuffer();
1646         if (master && master != this)
1647                 return master->hasMacro(name);
1648
1649         return MacroTable::globalMacros().has(name);
1650 }
1651
1652
1653 MacroData const & Buffer::getMacro(docstring const & name,
1654         Paragraph const & par) const
1655 {
1656         Impl::PositionToMacroMap::iterator it;
1657         it = d->macros[name].upper_bound(par.macrocontextPosition());
1658         if( it != d->macros[name].end() )
1659                 return it->second;
1660
1661         // If there is a master buffer, query that
1662         Buffer const * master = masterBuffer();
1663         if (master && master != this)
1664                 return master->getMacro(name);
1665
1666         return MacroTable::globalMacros().get(name);
1667 }
1668
1669
1670 MacroData const & Buffer::getMacro(docstring const & name) const
1671 {
1672         Impl::PositionToMacroMap::iterator it;
1673         it = d->macros[name].begin();
1674         if( it != d->macros[name].end() )
1675                 return it->second;
1676
1677         // If there is a master buffer, query that
1678         Buffer const * master = masterBuffer();
1679         if (master && master != this)
1680                 return master->getMacro(name);
1681
1682         return MacroTable::globalMacros().get(name);
1683 }
1684
1685
1686 void Buffer::updateMacros()
1687 {
1688         // start with empty table
1689         d->macros = Impl::NameToPositionMacroMap();
1690
1691         // Iterate over buffer
1692         ParagraphList & pars = text().paragraphs();
1693         for (size_t i = 0, n = pars.size(); i != n; ++i) {
1694                 // set position again
1695                 pars[i].setMacrocontextPosition(i);
1696
1697                 //lyxerr << "searching main par " << i
1698                 //      << " for macro definitions" << endl;
1699                 InsetList const & insets = pars[i].insetList();
1700                 InsetList::const_iterator it = insets.begin();
1701                 InsetList::const_iterator end = insets.end();
1702                 for ( ; it != end; ++it) {
1703                         if (it->inset->lyxCode() != MATHMACRO_CODE)
1704                                 continue;
1705                         
1706                         // get macro data
1707                         MathMacroTemplate const & macroTemplate
1708                         = static_cast<MathMacroTemplate const &>(*it->inset);
1709
1710                         // valid?
1711                         if (macroTemplate.validMacro()) {
1712                                 MacroData macro = macroTemplate.asMacroData();
1713
1714                                 // redefinition?
1715                                 // call hasMacro here instead of directly querying mc to
1716                                 // also take the master document into consideration
1717                                 macro.setRedefinition(hasMacro(macroTemplate.name()));
1718
1719                                 // register macro (possibly overwrite the previous one of this paragraph)
1720                                 d->macros[macroTemplate.name()][i] = macro;
1721                         }
1722                 }
1723         }
1724 }
1725
1726
1727 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
1728         InsetCode code)
1729 {
1730         //FIXME: This does not work for child documents yet.
1731         BOOST_ASSERT(code == CITE_CODE || code == REF_CODE);
1732         // Check if the label 'from' appears more than once
1733         vector<docstring> labels;
1734
1735         string paramName;
1736         if (code == CITE_CODE) {
1737                 BiblioInfo keys;
1738                 keys.fillWithBibKeys(this);
1739                 BiblioInfo::const_iterator bit  = keys.begin();
1740                 BiblioInfo::const_iterator bend = keys.end();
1741
1742                 for (; bit != bend; ++bit)
1743                         // FIXME UNICODE
1744                         labels.push_back(bit->first);
1745                 paramName = "key";
1746         } else {
1747                 getLabelList(labels);
1748                 paramName = "reference";
1749         }
1750
1751         if (count(labels.begin(), labels.end(), from) > 1)
1752                 return;
1753
1754         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1755                 if (it->lyxCode() == code) {
1756                         InsetCommand & inset = static_cast<InsetCommand &>(*it);
1757                         docstring const oldValue = inset.getParam(paramName);
1758                         if (oldValue == from)
1759                                 inset.setParam(paramName, to);
1760                 }
1761         }
1762 }
1763
1764
1765 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
1766         pit_type par_end, bool full_source)
1767 {
1768         OutputParams runparams(&params().encoding());
1769         runparams.nice = true;
1770         runparams.flavor = OutputParams::LATEX;
1771         runparams.linelen = lyxrc.plaintext_linelen;
1772         // No side effect of file copying and image conversion
1773         runparams.dryrun = true;
1774
1775         d->texrow.reset();
1776         if (full_source) {
1777                 os << "% " << _("Preview source code") << "\n\n";
1778                 d->texrow.newline();
1779                 d->texrow.newline();
1780                 if (isLatex())
1781                         writeLaTeXSource(os, filePath(), runparams, true, true);
1782                 else {
1783                         writeDocBookSource(os, absFileName(), runparams, false);
1784                 }
1785         } else {
1786                 runparams.par_begin = par_begin;
1787                 runparams.par_end = par_end;
1788                 if (par_begin + 1 == par_end)
1789                         os << "% "
1790                            << bformat(_("Preview source code for paragraph %1$d"), par_begin)
1791                            << "\n\n";
1792                 else
1793                         os << "% "
1794                            << bformat(_("Preview source code from paragraph %1$s to %2$s"),
1795                                         convert<docstring>(par_begin),
1796                                         convert<docstring>(par_end - 1))
1797                            << "\n\n";
1798                 d->texrow.newline();
1799                 d->texrow.newline();
1800                 // output paragraphs
1801                 if (isLatex()) {
1802                         latexParagraphs(*this, paragraphs(), os, d->texrow, runparams);
1803                 } else {
1804                         // DocBook
1805                         docbookParagraphs(paragraphs(), *this, os, runparams);
1806                 }
1807         }
1808 }
1809
1810
1811 ErrorList & Buffer::errorList(string const & type) const
1812 {
1813         static ErrorList emptyErrorList;
1814         map<string, ErrorList>::iterator I = d->errorLists.find(type);
1815         if (I == d->errorLists.end())
1816                 return emptyErrorList;
1817
1818         return I->second;
1819 }
1820
1821
1822 void Buffer::structureChanged() const
1823 {
1824         if (gui_)
1825                 gui_->structureChanged();
1826 }
1827
1828
1829 void Buffer::errors(string const & err) const
1830 {
1831         if (gui_)
1832                 gui_->errors(err);
1833 }
1834
1835
1836 void Buffer::message(docstring const & msg) const
1837 {
1838         if (gui_)
1839                 gui_->message(msg);
1840 }
1841
1842
1843 void Buffer::setBusy(bool on) const
1844 {
1845         if (gui_)
1846                 gui_->setBusy(on);
1847 }
1848
1849
1850 void Buffer::setReadOnly(bool on) const
1851 {
1852         if (d->wa_)
1853                 d->wa_->setReadOnly(on);
1854 }
1855
1856
1857 void Buffer::updateTitles() const
1858 {
1859         if (d->wa_)
1860                 d->wa_->updateTitles();
1861 }
1862
1863
1864 void Buffer::resetAutosaveTimers() const
1865 {
1866         if (gui_)
1867                 gui_->resetAutosaveTimers();
1868 }
1869
1870
1871 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
1872 {
1873         gui_ = gui;
1874 }
1875
1876
1877
1878 namespace {
1879
1880 class AutoSaveBuffer : public ForkedProcess {
1881 public:
1882         ///
1883         AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
1884                 : buffer_(buffer), fname_(fname) {}
1885         ///
1886         virtual boost::shared_ptr<ForkedProcess> clone() const
1887         {
1888                 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
1889         }
1890         ///
1891         int start()
1892         {
1893                 command_ = to_utf8(bformat(_("Auto-saving %1$s"), 
1894                                                  from_utf8(fname_.absFilename())));
1895                 return run(DontWait);
1896         }
1897 private:
1898         ///
1899         virtual int generateChild();
1900         ///
1901         Buffer const & buffer_;
1902         FileName fname_;
1903 };
1904
1905
1906 #if !defined (HAVE_FORK)
1907 # define fork() -1
1908 #endif
1909
1910 int AutoSaveBuffer::generateChild()
1911 {
1912         // tmp_ret will be located (usually) in /tmp
1913         // will that be a problem?
1914         pid_t const pid = fork();
1915         // If you want to debug the autosave
1916         // you should set pid to -1, and comment out the fork.
1917         if (pid == 0 || pid == -1) {
1918                 // pid = -1 signifies that lyx was unable
1919                 // to fork. But we will do the save
1920                 // anyway.
1921                 bool failed = false;
1922
1923                 FileName const tmp_ret = FileName::tempName("lyxauto");
1924                 if (!tmp_ret.empty()) {
1925                         buffer_.writeFile(tmp_ret);
1926                         // assume successful write of tmp_ret
1927                         if (!tmp_ret.moveTo(fname_)) {
1928                                 failed = true;
1929                                 // most likely couldn't move between
1930                                 // filesystems unless write of tmp_ret
1931                                 // failed so remove tmp file (if it
1932                                 // exists)
1933                                 tmp_ret.removeFile();
1934                         }
1935                 } else {
1936                         failed = true;
1937                 }
1938
1939                 if (failed) {
1940                         // failed to write/rename tmp_ret so try writing direct
1941                         if (!buffer_.writeFile(fname_)) {
1942                                 // It is dangerous to do this in the child,
1943                                 // but safe in the parent, so...
1944                                 if (pid == -1) // emit message signal.
1945                                         buffer_.message(_("Autosave failed!"));
1946                         }
1947                 }
1948                 if (pid == 0) { // we are the child so...
1949                         _exit(0);
1950                 }
1951         }
1952         return pid;
1953 }
1954
1955 } // namespace anon
1956
1957
1958 // Perfect target for a thread...
1959 void Buffer::autoSave() const
1960 {
1961         if (isBakClean() || isReadonly()) {
1962                 // We don't save now, but we'll try again later
1963                 resetAutosaveTimers();
1964                 return;
1965         }
1966
1967         // emit message signal.
1968         message(_("Autosaving current document..."));
1969
1970         // create autosave filename
1971         string fname = filePath();
1972         fname += '#';
1973         fname += d->filename.onlyFileName();
1974         fname += '#';
1975
1976         AutoSaveBuffer autosave(*this, FileName(fname));
1977         autosave.start();
1978
1979         markBakClean();
1980         resetAutosaveTimers();
1981 }
1982
1983
1984 void Buffer::resetChildDocuments(bool close_them) const
1985 {
1986         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1987                 if (it->lyxCode() != INCLUDE_CODE)
1988                         continue;
1989                 InsetCommand const & inset = static_cast<InsetCommand const &>(*it);
1990                 InsetCommandParams const & ip = inset.params();
1991
1992                 resetParentBuffer(this, ip, close_them);
1993         }
1994
1995         if (use_gui && masterBuffer() == this)
1996                 updateLabels(*this);
1997 }
1998
1999
2000 void Buffer::loadChildDocuments() const
2001 {
2002         bool parse_error = false;
2003                 
2004         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2005                 if (it->lyxCode() != INCLUDE_CODE)
2006                         continue;
2007                 InsetCommand const & inset = static_cast<InsetCommand const &>(*it);
2008                 InsetCommandParams const & ip = inset.params();
2009                 Buffer * child = loadIfNeeded(*this, ip);
2010                 if (!child)
2011                         continue;
2012                 parse_error |= !child->errorList("Parse").empty();
2013                 child->loadChildDocuments();
2014         }
2015
2016         if (use_gui && masterBuffer() == this)
2017                 updateLabels(*this);
2018 }
2019
2020
2021 string Buffer::bufferFormat() const
2022 {
2023         if (isDocBook())
2024                 return "docbook";
2025         if (isLiterate())
2026                 return "literate";
2027         return "latex";
2028 }
2029
2030
2031 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2032         string & result_file) const
2033 {
2034         string backend_format;
2035         OutputParams runparams(&params().encoding());
2036         runparams.flavor = OutputParams::LATEX;
2037         runparams.linelen = lyxrc.plaintext_linelen;
2038         vector<string> backs = backends();
2039         if (find(backs.begin(), backs.end(), format) == backs.end()) {
2040                 // Get shortest path to format
2041                 Graph::EdgePath path;
2042                 for (vector<string>::const_iterator it = backs.begin();
2043                      it != backs.end(); ++it) {
2044                         Graph::EdgePath p = theConverters().getPath(*it, format);
2045                         if (!p.empty() && (path.empty() || p.size() < path.size())) {
2046                                 backend_format = *it;
2047                                 path = p;
2048                         }
2049                 }
2050                 if (!path.empty())
2051                         runparams.flavor = theConverters().getFlavor(path);
2052                 else {
2053                         Alert::error(_("Couldn't export file"),
2054                                 bformat(_("No information for exporting the format %1$s."),
2055                                    formats.prettyName(format)));
2056                         return false;
2057                 }
2058         } else {
2059                 backend_format = format;
2060                 // FIXME: Don't hardcode format names here, but use a flag
2061                 if (backend_format == "pdflatex")
2062                         runparams.flavor = OutputParams::PDFLATEX;
2063         }
2064
2065         string filename = latexName(false);
2066         filename = addName(temppath(), filename);
2067         filename = changeExtension(filename,
2068                                    formats.extension(backend_format));
2069
2070         // Plain text backend
2071         if (backend_format == "text")
2072                 writePlaintextFile(*this, FileName(filename), runparams);
2073         // no backend
2074         else if (backend_format == "lyx")
2075                 writeFile(FileName(filename));
2076         // Docbook backend
2077         else if (isDocBook()) {
2078                 runparams.nice = !put_in_tempdir;
2079                 makeDocBookFile(FileName(filename), runparams);
2080         }
2081         // LaTeX backend
2082         else if (backend_format == format) {
2083                 runparams.nice = true;
2084                 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2085                         return false;
2086         } else if (!lyxrc.tex_allows_spaces
2087                    && contains(filePath(), ' ')) {
2088                 Alert::error(_("File name error"),
2089                            _("The directory path to the document cannot contain spaces."));
2090                 return false;
2091         } else {
2092                 runparams.nice = false;
2093                 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2094                         return false;
2095         }
2096
2097         string const error_type = (format == "program")
2098                 ? "Build" : bufferFormat();
2099         string const ext = formats.extension(format);
2100         FileName const tmp_result_file(changeExtension(filename, ext));
2101         bool const success = theConverters().convert(this, FileName(filename),
2102                 tmp_result_file, FileName(absFileName()), backend_format, format,
2103                 errorList(error_type));
2104         // Emit the signal to show the error list.
2105         if (format != backend_format)
2106                 errors(error_type);
2107         if (!success)
2108                 return false;
2109
2110         if (put_in_tempdir)
2111                 result_file = tmp_result_file.absFilename();
2112         else {
2113                 result_file = changeExtension(absFileName(), ext);
2114                 // We need to copy referenced files (e. g. included graphics
2115                 // if format == "dvi") to the result dir.
2116                 vector<ExportedFile> const files =
2117                         runparams.exportdata->externalFiles(format);
2118                 string const dest = onlyPath(result_file);
2119                 CopyStatus status = SUCCESS;
2120                 for (vector<ExportedFile>::const_iterator it = files.begin();
2121                                 it != files.end() && status != CANCEL; ++it) {
2122                         string const fmt =
2123                                 formats.getFormatFromFile(it->sourceName);
2124                         status = copyFile(fmt, it->sourceName,
2125                                           makeAbsPath(it->exportName, dest),
2126                                           it->exportName, status == FORCE);
2127                 }
2128                 if (status == CANCEL) {
2129                         message(_("Document export cancelled."));
2130                 } else if (tmp_result_file.exists()) {
2131                         // Finally copy the main file
2132                         status = copyFile(format, tmp_result_file,
2133                                           FileName(result_file), result_file,
2134                                           status == FORCE);
2135                         message(bformat(_("Document exported as %1$s "
2136                                                                "to file `%2$s'"),
2137                                                 formats.prettyName(format),
2138                                                 makeDisplayPath(result_file)));
2139                 } else {
2140                         // This must be a dummy converter like fax (bug 1888)
2141                         message(bformat(_("Document exported as %1$s"),
2142                                                 formats.prettyName(format)));
2143                 }
2144         }
2145
2146         return true;
2147 }
2148
2149
2150 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2151 {
2152         string result_file;
2153         return doExport(format, put_in_tempdir, result_file);
2154 }
2155
2156
2157 bool Buffer::preview(string const & format) const
2158 {
2159         string result_file;
2160         if (!doExport(format, true, result_file))
2161                 return false;
2162         return formats.view(*this, FileName(result_file), format);
2163 }
2164
2165
2166 bool Buffer::isExportable(string const & format) const
2167 {
2168         vector<string> backs = backends();
2169         for (vector<string>::const_iterator it = backs.begin();
2170              it != backs.end(); ++it)
2171                 if (theConverters().isReachable(*it, format))
2172                         return true;
2173         return false;
2174 }
2175
2176
2177 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2178 {
2179         vector<string> backs = backends();
2180         vector<Format const *> result =
2181                 theConverters().getReachable(backs[0], only_viewable, true);
2182         for (vector<string>::const_iterator it = backs.begin() + 1;
2183              it != backs.end(); ++it) {
2184                 vector<Format const *>  r =
2185                         theConverters().getReachable(*it, only_viewable, false);
2186                 result.insert(result.end(), r.begin(), r.end());
2187         }
2188         return result;
2189 }
2190
2191
2192 vector<string> Buffer::backends() const
2193 {
2194         vector<string> v;
2195         if (params().getTextClass().isTeXClassAvailable()) {
2196                 v.push_back(bufferFormat());
2197                 // FIXME: Don't hardcode format names here, but use a flag
2198                 if (v.back() == "latex")
2199                         v.push_back("pdflatex");
2200         }
2201         v.push_back("text");
2202         v.push_back("lyx");
2203         return v;
2204 }
2205
2206
2207 bool Buffer::readFileHelper(FileName const & s)
2208 {
2209         // File information about normal file
2210         if (!s.exists()) {
2211                 docstring const file = makeDisplayPath(s.absFilename(), 50);
2212                 docstring text = bformat(_("The specified document\n%1$s"
2213                                                      "\ncould not be read."), file);
2214                 Alert::error(_("Could not read document"), text);
2215                 return false;
2216         }
2217
2218         // Check if emergency save file exists and is newer.
2219         FileName const e(s.absFilename() + ".emergency");
2220
2221         if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2222                 docstring const file = makeDisplayPath(s.absFilename(), 20);
2223                 docstring const text =
2224                         bformat(_("An emergency save of the document "
2225                                   "%1$s exists.\n\n"
2226                                                "Recover emergency save?"), file);
2227                 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2228                                       _("&Recover"),  _("&Load Original"),
2229                                       _("&Cancel")))
2230                 {
2231                 case 0:
2232                         // the file is not saved if we load the emergency file.
2233                         markDirty();
2234                         return readFile(e);
2235                 case 1:
2236                         break;
2237                 default:
2238                         return false;
2239                 }
2240         }
2241
2242         // Now check if autosave file is newer.
2243         FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2244
2245         if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2246                 docstring const file = makeDisplayPath(s.absFilename(), 20);
2247                 docstring const text =
2248                         bformat(_("The backup of the document "
2249                                   "%1$s is newer.\n\nLoad the "
2250                                                "backup instead?"), file);
2251                 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2252                                       _("&Load backup"), _("Load &original"),
2253                                       _("&Cancel") ))
2254                 {
2255                 case 0:
2256                         // the file is not saved if we load the autosave file.
2257                         markDirty();
2258                         return readFile(a);
2259                 case 1:
2260                         // Here we delete the autosave
2261                         a.removeFile();
2262                         break;
2263                 default:
2264                         return false;
2265                 }
2266         }
2267         return readFile(s);
2268 }
2269
2270
2271 bool Buffer::loadLyXFile(FileName const & s)
2272 {
2273         if (s.isReadableFile()) {
2274                 if (readFileHelper(s)) {
2275                         lyxvc().file_found_hook(s);
2276                         if (!s.isWritable())
2277                                 setReadonly(true);
2278                         return true;
2279                 }
2280         } else {
2281                 docstring const file = makeDisplayPath(s.absFilename(), 20);
2282                 // Here we probably should run
2283                 if (LyXVC::file_not_found_hook(s)) {
2284                         docstring const text =
2285                                 bformat(_("Do you want to retrieve the document"
2286                                                        " %1$s from version control?"), file);
2287                         int const ret = Alert::prompt(_("Retrieve from version control?"),
2288                                 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2289
2290                         if (ret == 0) {
2291                                 // How can we know _how_ to do the checkout?
2292                                 // With the current VC support it has to be,
2293                                 // a RCS file since CVS do not have special ,v files.
2294                                 RCS::retrieve(s);
2295                                 return loadLyXFile(s);
2296                         }
2297                 }
2298         }
2299         return false;
2300 }
2301
2302
2303 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2304 {
2305         TeXErrors::Errors::const_iterator cit = terr.begin();
2306         TeXErrors::Errors::const_iterator end = terr.end();
2307
2308         for (; cit != end; ++cit) {
2309                 int id_start = -1;
2310                 int pos_start = -1;
2311                 int errorRow = cit->error_in_line;
2312                 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2313                                                        pos_start);
2314                 int id_end = -1;
2315                 int pos_end = -1;
2316                 do {
2317                         ++errorRow;
2318                         found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2319                 } while (found && id_start == id_end && pos_start == pos_end);
2320
2321                 errorList.push_back(ErrorItem(cit->error_desc,
2322                         cit->error_text, id_start, pos_start, pos_end));
2323         }
2324 }
2325
2326 } // namespace lyx