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