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