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