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