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