]> git.lyx.org Git - features.git/blob - src/Buffer.cpp
There was a bit too much copying of dociterators gpoing on leading to an
[features.git] / src / Buffer.cpp
1 /**
2  * \file Buffer.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Stefan Schimanski
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "Buffer.h"
15
16 #include "Author.h"
17 #include "BiblioInfo.h"
18 #include "BranchList.h"
19 #include "buffer_funcs.h"
20 #include "BufferList.h"
21 #include "BufferParams.h"
22 #include "Bullet.h"
23 #include "Chktex.h"
24 #include "Converter.h"
25 #include "Counters.h"
26 #include "DocIterator.h"
27 #include "EmbeddedFiles.h"
28 #include "Encoding.h"
29 #include "ErrorList.h"
30 #include "Exporter.h"
31 #include "Format.h"
32 #include "FuncRequest.h"
33 #include "InsetIterator.h"
34 #include "InsetList.h"
35 #include "Language.h"
36 #include "LaTeXFeatures.h"
37 #include "LaTeX.h"
38 #include "Layout.h"
39 #include "Lexer.h"
40 #include "LyXAction.h"
41 #include "LyX.h"
42 #include "LyXRC.h"
43 #include "LyXVC.h"
44 #include "output_docbook.h"
45 #include "output.h"
46 #include "output_latex.h"
47 #include "output_plaintext.h"
48 #include "paragraph_funcs.h"
49 #include "Paragraph.h"
50 #include "ParagraphParameters.h"
51 #include "ParIterator.h"
52 #include "PDFOptions.h"
53 #include "Session.h"
54 #include "sgml.h"
55 #include "TexRow.h"
56 #include "TexStream.h"
57 #include "TextClassList.h"
58 #include "Text.h"
59 #include "TocBackend.h"
60 #include "Undo.h"
61 #include "VCBackend.h"
62 #include "version.h"
63
64 #include "insets/InsetBibitem.h"
65 #include "insets/InsetBibtex.h"
66 #include "insets/InsetInclude.h"
67 #include "insets/InsetText.h"
68
69 #include "mathed/MacroTable.h"
70 #include "mathed/MathMacroTemplate.h"
71 #include "mathed/MathSupport.h"
72
73 #include "frontends/alert.h"
74 #include "frontends/Delegates.h"
75 #include "frontends/WorkAreaManager.h"
76
77 #include "graphics/Previews.h"
78
79 #include "support/convert.h"
80 #include "support/debug.h"
81 #include "support/ExceptionMessage.h"
82 #include "support/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 = 313; // Richard Heck: conversion of module representations
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         EmbeddedFileList 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 EmbeddedFileList 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(), 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 EmbeddedFileList & Buffer::embeddedFiles()
370 {
371         return d->embedded_files;
372 }
373
374
375 EmbeddedFileList const & Buffer::embeddedFiles() const
376 {
377         return d->embedded_files;
378 }
379
380
381 bool Buffer::embedded() const
382 {
383         return params().embedded;
384 }
385
386
387 Undo & Buffer::undo()
388 {
389         return d->undo_;
390 }
391
392
393 string Buffer::latexName(bool const no_path) const
394 {
395         FileName latex_name = makeLatexName(d->filename);
396         return no_path ? latex_name.onlyFileName()
397                 : latex_name.absFilename();
398 }
399
400
401 string Buffer::logName(LogType * type) const
402 {
403         string const filename = latexName(false);
404
405         if (filename.empty()) {
406                 if (type)
407                         *type = latexlog;
408                 return string();
409         }
410
411         string const path = temppath();
412
413         FileName const fname(addName(temppath(),
414                                      onlyFilename(changeExtension(filename,
415                                                                   ".log"))));
416         FileName const bname(
417                 addName(path, onlyFilename(
418                         changeExtension(filename,
419                                         formats.extension("literate") + ".out"))));
420
421         // If no Latex log or Build log is newer, show Build log
422
423         if (bname.exists() &&
424             (!fname.exists() || fname.lastModified() < bname.lastModified())) {
425                 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
426                 if (type)
427                         *type = buildlog;
428                 return bname.absFilename();
429         }
430         LYXERR(Debug::FILES, "Log name calculated as: " << fname);
431         if (type)
432                         *type = latexlog;
433         return fname.absFilename();
434 }
435
436
437 void Buffer::setReadonly(bool const flag)
438 {
439         if (d->read_only != flag) {
440                 d->read_only = flag;
441                 setReadOnly(flag);
442         }
443 }
444
445
446 void Buffer::setFileName(string const & newfile)
447 {
448         d->filename = makeAbsPath(newfile);
449         setReadonly(d->filename.isReadOnly());
450         updateTitles();
451 }
452
453
454 int Buffer::readHeader(Lexer & lex)
455 {
456         int unknown_tokens = 0;
457         int line = -1;
458         int begin_header_line = -1;
459
460         // Initialize parameters that may be/go lacking in header:
461         params().branchlist().clear();
462         params().preamble.erase();
463         params().options.erase();
464         params().float_placement.erase();
465         params().paperwidth.erase();
466         params().paperheight.erase();
467         params().leftmargin.erase();
468         params().rightmargin.erase();
469         params().topmargin.erase();
470         params().bottommargin.erase();
471         params().headheight.erase();
472         params().headsep.erase();
473         params().footskip.erase();
474         params().listings_params.clear();
475         params().clearLayoutModules();
476         params().pdfoptions().clear();
477         
478         for (int i = 0; i < 4; ++i) {
479                 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
480                 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
481         }
482
483         ErrorList & errorList = d->errorLists["Parse"];
484
485         while (lex.isOK()) {
486                 lex.next();
487                 string const token = lex.getString();
488
489                 if (token.empty())
490                         continue;
491
492                 if (token == "\\end_header")
493                         break;
494
495                 ++line;
496                 if (token == "\\begin_header") {
497                         begin_header_line = line;
498                         continue;
499                 }
500
501                 LYXERR(Debug::PARSER, "Handling document header token: `"
502                                       << token << '\'');
503
504                 string unknown = params().readToken(lex, token, d->filename.onlyPath());
505                 if (!unknown.empty()) {
506                         if (unknown[0] != '\\' && token == "\\textclass") {
507                                 Alert::warning(_("Unknown document class"),
508                        bformat(_("Using the default document class, because the "
509                                               "class %1$s is unknown."), from_utf8(unknown)));
510                         } else {
511                                 ++unknown_tokens;
512                                 docstring const s = bformat(_("Unknown token: "
513                                                                         "%1$s %2$s\n"),
514                                                          from_utf8(token),
515                                                          lex.getDocString());
516                                 errorList.push_back(ErrorItem(_("Document header error"),
517                                         s, -1, 0, 0));
518                         }
519                 }
520         }
521         if (begin_header_line) {
522                 docstring const s = _("\\begin_header is missing");
523                 errorList.push_back(ErrorItem(_("Document header error"),
524                         s, -1, 0, 0));
525         }
526         
527         params().makeTextClass();
528
529         return unknown_tokens;
530 }
531
532
533 // Uwe C. Schroeder
534 // changed to be public and have one parameter
535 // Returns false if "\end_document" is not read (Asger)
536 bool Buffer::readDocument(Lexer & lex)
537 {
538         ErrorList & errorList = d->errorLists["Parse"];
539         errorList.clear();
540
541         lex.next();
542         string const token = lex.getString();
543         if (token != "\\begin_document") {
544                 docstring const s = _("\\begin_document is missing");
545                 errorList.push_back(ErrorItem(_("Document header error"),
546                         s, -1, 0, 0));
547         }
548
549         // we are reading in a brand new document
550         BOOST_ASSERT(paragraphs().empty());
551
552         readHeader(lex);
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                         // if in bundled format, save checksum of the compressed file, not content.lyx
682                         saveCheckSum(filename);
683                         params().embedded = true;
684                         fname = lyxfile;
685                 }
686         }
687         // The embedded lyx file can also be compressed, for backward compatibility
688         format = fname.guessFormatFromContents();
689         if (format == "gzip" || format == "zip" || format == "compress")
690                 params().compressed = true;
691
692         // remove dummy empty par
693         paragraphs().clear();
694         Lexer lex(0, 0);
695         lex.setFile(fname);
696         if (readFile(lex, fname) != success)
697                 return false;
698
699         return true;
700 }
701
702
703 bool Buffer::isFullyLoaded() const
704 {
705         return d->file_fully_loaded;
706 }
707
708
709 void Buffer::setFullyLoaded(bool value)
710 {
711         d->file_fully_loaded = value;
712 }
713
714
715 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
716                 bool fromstring)
717 {
718         BOOST_ASSERT(!filename.empty());
719
720         if (!lex.isOK()) {
721                 Alert::error(_("Document could not be read"),
722                              bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
723                 return failure;
724         }
725
726         lex.next();
727         string const token = lex.getString();
728
729         if (!lex) {
730                 Alert::error(_("Document could not be read"),
731                              bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
732                 return failure;
733         }
734
735         // the first token _must_ be...
736         if (token != "\\lyxformat") {
737                 lyxerr << "Token: " << token << endl;
738
739                 Alert::error(_("Document format failure"),
740                              bformat(_("%1$s is not a LyX document."),
741                                        from_utf8(filename.absFilename())));
742                 return failure;
743         }
744
745         lex.next();
746         string tmp_format = lex.getString();
747         //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
748         // if present remove ".," from string.
749         string::size_type dot = tmp_format.find_first_of(".,");
750         //lyxerr << "           dot found at " << dot << endl;
751         if (dot != string::npos)
752                         tmp_format.erase(dot, 1);
753         int const file_format = convert<int>(tmp_format);
754         //lyxerr << "format: " << file_format << endl;
755
756         // save timestamp and checksum of the original disk file, making sure
757         // to not overwrite them with those of the file created in the tempdir
758         // when it has to be converted to the current format.
759         if (!d->checksum_) {
760                 // Save the timestamp and checksum of disk file. If filename is an
761                 // emergency file, save the timestamp and checksum of the original lyx file
762                 // because isExternallyModified will check for this file. (BUG4193)
763                 string diskfile = filename.absFilename();
764                 if (suffixIs(diskfile, ".emergency"))
765                         diskfile = diskfile.substr(0, diskfile.size() - 10);
766                 saveCheckSum(FileName(diskfile));
767         }
768
769         if (file_format != LYX_FORMAT) {
770
771                 if (fromstring)
772                         // lyx2lyx would fail
773                         return wrongversion;
774
775                 FileName const tmpfile = FileName::tempName();
776                 if (tmpfile.empty()) {
777                         Alert::error(_("Conversion failed"),
778                                      bformat(_("%1$s is from a different"
779                                               " version of LyX, but a temporary"
780                                               " file for converting it could"
781                                                             " not be created."),
782                                               from_utf8(filename.absFilename())));
783                         return failure;
784                 }
785                 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
786                 if (lyx2lyx.empty()) {
787                         Alert::error(_("Conversion script not found"),
788                                      bformat(_("%1$s is from a different"
789                                                " version of LyX, but the"
790                                                " conversion script lyx2lyx"
791                                                             " could not be found."),
792                                                from_utf8(filename.absFilename())));
793                         return failure;
794                 }
795                 ostringstream command;
796                 command << os::python()
797                         << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
798                         << " -t " << convert<string>(LYX_FORMAT)
799                         << " -o " << quoteName(tmpfile.toFilesystemEncoding())
800                         << ' ' << quoteName(filename.toFilesystemEncoding());
801                 string const command_str = command.str();
802
803                 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
804
805                 cmd_ret const ret = runCommand(command_str);
806                 if (ret.first != 0) {
807                         Alert::error(_("Conversion script failed"),
808                                      bformat(_("%1$s is from a different version"
809                                               " of LyX, but the lyx2lyx script"
810                                                             " failed to convert it."),
811                                               from_utf8(filename.absFilename())));
812                         return failure;
813                 } else {
814                         bool const ret = readFile(tmpfile);
815                         // Do stuff with tmpfile name and buffer name here.
816                         return ret ? success : failure;
817                 }
818
819         }
820
821         if (readDocument(lex)) {
822                 Alert::error(_("Document format failure"),
823                              bformat(_("%1$s ended unexpectedly, which means"
824                                                     " that it is probably corrupted."),
825                                        from_utf8(filename.absFilename())));
826         }
827
828         d->file_fully_loaded = true;
829         return success;
830 }
831
832
833 // Should probably be moved to somewhere else: BufferView? LyXView?
834 bool Buffer::save() const
835 {
836         // We don't need autosaves in the immediate future. (Asger)
837         resetAutosaveTimers();
838
839         string const encodedFilename = d->filename.toFilesystemEncoding();
840
841         FileName backupName;
842         bool madeBackup = false;
843
844         // make a backup if the file already exists
845         if (lyxrc.make_backup && fileName().exists()) {
846                 backupName = FileName(absFileName() + '~');
847                 if (!lyxrc.backupdir_path.empty()) {
848                         string const mangledName =
849                                 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
850                         backupName = FileName(addName(lyxrc.backupdir_path,
851                                                       mangledName));
852                 }
853                 if (fileName().copyTo(backupName)) {
854                         madeBackup = true;
855                 } else {
856                         Alert::error(_("Backup failure"),
857                                      bformat(_("Cannot create backup file %1$s.\n"
858                                                "Please check whether the directory exists and is writeable."),
859                                              from_utf8(backupName.absFilename())));
860                         //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
861                 }
862         }
863
864         // ask if the disk file has been externally modified (use checksum method)
865         if (fileName().exists() && isExternallyModified(checksum_method)) {
866                 docstring const file = makeDisplayPath(absFileName(), 20);
867                 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
868                                                              "you want to overwrite this file?"), file);
869                 int const ret = Alert::prompt(_("Overwrite modified file?"),
870                         text, 1, 1, _("&Overwrite"), _("&Cancel"));
871                 if (ret == 1)
872                         return false;
873         }
874
875         if (writeFile(d->filename)) {
876                 markClean();
877                 return true;
878         } else {
879                 // Saving failed, so backup is not backup
880                 if (madeBackup)
881                         backupName.moveTo(d->filename);
882                 return false;
883         }
884 }
885
886
887 bool Buffer::writeFile(FileName const & fname) const
888 {
889         if (d->read_only && fname == d->filename)
890                 return false;
891
892         bool retval = false;
893
894         FileName content;
895         if (params().embedded)
896                 // first write the .lyx file to the temporary directory
897                 content = FileName(addName(temppath(), "content.lyx"));
898         else
899                 content = fname;
900
901         docstring const str = bformat(_("Saving document %1$s..."),
902                 makeDisplayPath(content.absFilename()));
903         message(str);
904
905         if (params().compressed) {
906                 gz::ogzstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
907                 retval = ofs && write(ofs);
908         } else {
909                 ofstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
910                 retval = ofs && write(ofs);
911         }
912
913         if (!retval) {
914                 message(str + _(" could not write file!."));
915                 return false;
916         }
917
918         removeAutosaveFile(d->filename.absFilename());
919
920         if (params().embedded) {
921                 message(str + _(" writing embedded files!."));
922                 // if embedding is enabled, write file.lyx and all the embedded files
923                 // to the zip file fname.
924                 if (!d->embedded_files.writeFile(fname, *this)) {
925                         message(str + _(" could not write embedded files!."));
926                         return false;
927                 }
928         }
929         saveCheckSum(d->filename);
930         message(str + _(" done."));
931
932         return true;
933 }
934
935
936 bool Buffer::write(ostream & ofs) const
937 {
938 #ifdef HAVE_LOCALE
939         // Use the standard "C" locale for file output.
940         ofs.imbue(locale::classic());
941 #endif
942
943         // The top of the file should not be written by params().
944
945         // write out a comment in the top of the file
946         ofs << "#LyX " << lyx_version
947             << " created this file. For more info see http://www.lyx.org/\n"
948             << "\\lyxformat " << LYX_FORMAT << "\n"
949             << "\\begin_document\n";
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 = const_cast<Buffer *>(this)->par_iterator_end();
959         ParIterator it = const_cast<Buffer *>(this)->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                         EmbeddedFileList 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                         EmbeddedFileList 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 EmbeddedFileList 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 ParConstIterator 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 ParIterator Buffer::getParFromID(int const id)
1509 {
1510         ParIterator it = par_iterator_begin();
1511         ParIterator const end = par_iterator_end();
1512
1513         if (id < 0) {
1514                 // John says this is called with id == -1 from undo
1515                 lyxerr << "getParFromID(), id: " << id << endl;
1516                 return end;
1517         }
1518
1519         for (; it != end; ++it)
1520                 if (it->id() == id)
1521                         return it;
1522
1523         return end;
1524 }
1525
1526
1527 bool Buffer::hasParWithID(int const id) const
1528 {
1529         ParConstIterator const it = getParFromID(id);
1530         return it != par_iterator_end();
1531 }
1532
1533
1534 ParIterator Buffer::par_iterator_begin()
1535 {
1536         return lyx::par_iterator_begin(inset());
1537 }
1538
1539
1540 ParIterator Buffer::par_iterator_end()
1541 {
1542         return lyx::par_iterator_end(inset());
1543 }
1544
1545
1546 ParConstIterator Buffer::par_iterator_begin() const
1547 {
1548         return lyx::par_const_iterator_begin(inset());
1549 }
1550
1551
1552 ParConstIterator Buffer::par_iterator_end() const
1553 {
1554         return lyx::par_const_iterator_end(inset());
1555 }
1556
1557
1558 Language const * Buffer::language() const
1559 {
1560         return params().language;
1561 }
1562
1563
1564 docstring const Buffer::B_(string const & l10n) const
1565 {
1566         return params().B_(l10n);
1567 }
1568
1569
1570 bool Buffer::isClean() const
1571 {
1572         return d->lyx_clean;
1573 }
1574
1575
1576 bool Buffer::isBakClean() const
1577 {
1578         return d->bak_clean;
1579 }
1580
1581
1582 bool Buffer::isExternallyModified(CheckMethod method) const
1583 {
1584         BOOST_ASSERT(d->filename.exists());
1585         // if method == timestamp, check timestamp before checksum
1586         return (method == checksum_method 
1587                 || d->timestamp_ != d->filename.lastModified())
1588                 && d->checksum_ != d->filename.checksum();
1589 }
1590
1591
1592 void Buffer::saveCheckSum(FileName const & file) const
1593 {
1594         if (file.exists()) {
1595                 d->timestamp_ = file.lastModified();
1596                 d->checksum_ = file.checksum();
1597         } else {
1598                 // in the case of save to a new file.
1599                 d->timestamp_ = 0;
1600                 d->checksum_ = 0;
1601         }
1602 }
1603
1604
1605 void Buffer::markClean() const
1606 {
1607         if (!d->lyx_clean) {
1608                 d->lyx_clean = true;
1609                 updateTitles();
1610         }
1611         // if the .lyx file has been saved, we don't need an
1612         // autosave
1613         d->bak_clean = true;
1614 }
1615
1616
1617 void Buffer::markBakClean() const
1618 {
1619         d->bak_clean = true;
1620 }
1621
1622
1623 void Buffer::setUnnamed(bool flag)
1624 {
1625         d->unnamed = flag;
1626 }
1627
1628
1629 bool Buffer::isUnnamed() const
1630 {
1631         return d->unnamed;
1632 }
1633
1634
1635 // FIXME: this function should be moved to buffer_pimpl.C
1636 void Buffer::markDirty()
1637 {
1638         if (d->lyx_clean) {
1639                 d->lyx_clean = false;
1640                 updateTitles();
1641         }
1642         d->bak_clean = false;
1643
1644         DepClean::iterator it = d->dep_clean.begin();
1645         DepClean::const_iterator const end = d->dep_clean.end();
1646
1647         for (; it != end; ++it)
1648                 it->second = false;
1649 }
1650
1651
1652 FileName Buffer::fileName() const
1653 {
1654         return d->filename;
1655 }
1656
1657
1658 string Buffer::absFileName() const
1659 {
1660         return d->filename.absFilename();
1661 }
1662
1663
1664 string Buffer::filePath() const
1665 {
1666         return d->filename.onlyPath().absFilename() + "/";
1667 }
1668
1669
1670 bool Buffer::isReadonly() const
1671 {
1672         return d->read_only;
1673 }
1674
1675
1676 void Buffer::setParent(Buffer const * buffer)
1677 {
1678         // Avoids recursive include.
1679         d->parent_buffer = buffer == this ? 0 : buffer;
1680         updateMacros();
1681 }
1682
1683
1684 Buffer const * Buffer::parent()
1685 {
1686         return d->parent_buffer;
1687 }
1688
1689
1690 Buffer const * Buffer::masterBuffer() const
1691 {
1692         if (!d->parent_buffer)
1693                 return this;
1694         
1695         return d->parent_buffer->masterBuffer();
1696 }
1697
1698
1699 template<typename M>
1700 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
1701 {
1702         if (m.empty())
1703                 return m.end();
1704
1705         typename M::iterator it = m.lower_bound(x);
1706         if (it == m.begin())
1707                 return m.end();
1708
1709         it--;
1710         return it;      
1711 }
1712
1713
1714 MacroData const * Buffer::getBufferMacro(docstring const & name, 
1715                                          DocIterator const & pos) const
1716 {
1717         LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
1718
1719         // if paragraphs have no macro context set, pos will be empty
1720         if (pos.empty())
1721                 return 0;
1722
1723         // we haven't found anything yet
1724         DocIterator bestPos = par_iterator_begin();
1725         MacroData const * bestData = 0;
1726         
1727         // find macro definitions for name
1728         Impl::NamePositionScopeMacroMap::iterator nameIt
1729         = d->macros.find(name);
1730         if (nameIt != d->macros.end()) {
1731                 // find last definition in front of pos or at pos itself
1732                 Impl::PositionScopeMacroMap::const_iterator it
1733                 = greatest_below(nameIt->second, pos);
1734                 if (it != nameIt->second.end()) {
1735                         while (true) {
1736                                 // scope ends behind pos?
1737                                 if (pos < it->second.first) {
1738                                         // Looks good, remember this. If there
1739                                         // is no external macro behind this,
1740                                         // we found the right one already.
1741                                         bestPos = it->first;
1742                                         bestData = &it->second.second;
1743                                         break;
1744                                 }
1745                                 
1746                                 // try previous macro if there is one
1747                                 if (it == nameIt->second.begin())
1748                                         break;
1749                                 it--;
1750                         }
1751                 }
1752         }
1753
1754         // find macros in included files
1755         Impl::PositionScopeBufferMap::const_iterator it
1756         = greatest_below(d->position_to_children, pos);
1757         if (it != d->position_to_children.end()) {
1758                 while (true) {
1759                         // do we know something better (i.e. later) already?
1760                         if (it->first < bestPos )               
1761                                 break;
1762
1763                         // scope ends behind pos?
1764                         if (pos < it->second.first) {
1765                                 // look for macro in external file
1766                                 d->macro_lock = true;
1767                                 MacroData const * data
1768                                 = it->second.second->getMacro(name, false);
1769                                 d->macro_lock = false;
1770                                 if (data) {
1771                                         bestPos = it->first;
1772                                         bestData = data;                               
1773                                         break;
1774                                 }
1775                         }
1776                         
1777                         // try previous file if there is one
1778                         if (it == d->position_to_children.begin())
1779                                 break;
1780                         --it;
1781                 }
1782         }
1783                 
1784         // return the best macro we have found
1785         return bestData;
1786 }
1787
1788
1789 MacroData const * Buffer::getMacro(docstring const & name,
1790         DocIterator const & pos, bool global) const
1791 {
1792         if (d->macro_lock)
1793                 return 0;       
1794
1795         // query buffer macros
1796         MacroData const * data = getBufferMacro(name, pos);
1797         if (data != 0)
1798                 return data;
1799
1800         // If there is a master buffer, query that
1801         if (d->parent_buffer) {
1802                 d->macro_lock = true;
1803                 MacroData const * macro
1804                 = d->parent_buffer->getMacro(name, *this, false);
1805                 d->macro_lock = false;
1806                 if (macro)
1807                         return macro;
1808         }
1809
1810         if (global) {
1811                 data = MacroTable::globalMacros().get(name);
1812                 if (data != 0)
1813                         return data;
1814         }
1815
1816         return 0;
1817 }
1818
1819
1820 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
1821 {
1822         // set scope end behind the last paragraph
1823         DocIterator scope = par_iterator_begin();
1824         scope.pit() = scope.lastpit() + 1;
1825
1826         return getMacro(name, scope, global);
1827 }
1828
1829
1830 MacroData const * Buffer::getMacro(docstring const & name, Buffer const & child, bool global) const
1831 {
1832         // look where the child buffer is included first
1833         Impl::BufferPositionMap::iterator it
1834         = d->children_positions.find(&child);
1835         if (it == d->children_positions.end())
1836                 return 0;
1837
1838         // check for macros at the inclusion position
1839         return getMacro(name, it->second, global);
1840 }
1841
1842
1843 void Buffer::updateEnvironmentMacros(DocIterator & it, 
1844                                      pit_type lastpit, 
1845                                      DocIterator & scope) const
1846 {
1847         Paragraph & par = it.paragraph();
1848         depth_type depth 
1849         = par.params().depth();
1850         Length const & leftIndent
1851         = par.params().leftIndent();
1852
1853         // look for macros in each paragraph
1854         while (it.pit() <= lastpit) {
1855                 Paragraph & par = it.paragraph();
1856
1857                 // increased depth?
1858                 if ((par.params().depth() > depth
1859                      || par.params().leftIndent() != leftIndent)
1860                     && par.layout()->isEnvironment()) {
1861                         updateBlockMacros(it, scope);
1862                         continue;
1863                 }
1864
1865                 // iterate over the insets of the current paragraph
1866                 InsetList const & insets = par.insetList();
1867                 InsetList::const_iterator iit = insets.begin();
1868                 InsetList::const_iterator end = insets.end();
1869                 for (; iit != end; ++iit) {
1870                         it.pos() = iit->pos;
1871                         
1872                         // is it a nested text inset?
1873                         if (iit->inset->asInsetText()) {
1874                                 // Inset needs its own scope?
1875                                 InsetText const * itext 
1876                                 = iit->inset->asInsetText();
1877                                 bool newScope = itext->isMacroScope(*this);
1878
1879                                 // scope which ends just behind die inset       
1880                                 DocIterator insetScope = it;
1881                                 insetScope.pos()++;
1882
1883                                 // collect macros in inset
1884                                 it.push_back(CursorSlice(*iit->inset));
1885                                 updateInsetMacros(it, newScope ? insetScope : scope);
1886                                 it.pop_back();
1887                                 continue;
1888                         }
1889                                               
1890                         // is it an external file?
1891                         if (iit->inset->lyxCode() == INCLUDE_CODE) {
1892                                 // get buffer of external file
1893                                 InsetCommand const & inset 
1894                                 = static_cast<InsetCommand const &>(*iit->inset);
1895                                 InsetCommandParams const & ip = inset.params();
1896                                 d->macro_lock = true;
1897                                 Buffer * child = loadIfNeeded(*this, ip);
1898                                 d->macro_lock = false;
1899                                 if (!child)
1900                                         continue;                               
1901
1902                                 // register it, but only when it is
1903                                 // included first in the buffer
1904                                 if (d->children_positions.find(child)
1905                                     == d->children_positions.end())
1906                                         d->children_positions[child] = it;
1907                                                                                                 
1908                                 // register child with its scope
1909                                 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
1910
1911                                 continue;
1912                         }
1913
1914                         if (iit->inset->lyxCode() != MATHMACRO_CODE)
1915                                 continue;
1916                         
1917                         // get macro data
1918                         MathMacroTemplate & macroTemplate
1919                         = static_cast<MathMacroTemplate &>(*iit->inset);
1920                         MacroContext mc(*this, it);
1921                         macroTemplate.updateToContext(mc);
1922
1923                         // valid?
1924                         bool valid = macroTemplate.validMacro();
1925                         // FIXME: Should be fixNameAndCheckIfValid() in fact,
1926                         // then the BufferView's cursor will be invalid in
1927                         // some cases which leads to crashes.
1928                         if (!valid)
1929                                 continue;
1930
1931                         // register macro
1932                         d->macros[macroTemplate.name()][it] 
1933                         = Impl::ScopeMacro(scope, MacroData(*this, it));
1934                 }
1935
1936                 // next paragraph
1937                 it.pit()++;
1938                 it.pos() = 0;
1939         }
1940 }
1941
1942
1943 void Buffer::updateBlockMacros(DocIterator & it, DocIterator & scope) const
1944 {
1945         Paragraph & par = it.paragraph();
1946                 
1947         // set scope for macros in this paragraph:
1948         // * either the "old" outer scope
1949         // * or the scope ending after the environment
1950         if (par.layout()->isEnvironment()) {
1951                 // find end of environment block,
1952                 DocIterator envEnd = it;
1953                 pit_type n = it.lastpit() + 1;
1954                 depth_type depth = par.params().depth();
1955                 Length const & length = par.params().leftIndent();
1956                 // looping through the paragraph, basically until
1957                 // the layout changes or the depth gets smaller.
1958                 // (the logic of output_latex.cpp's TeXEnvironment)
1959                 do {
1960                         envEnd.pit()++;
1961                         if (envEnd.pit() == n)
1962                                 break;
1963                 } while (par.layout() == envEnd.paragraph().layout()
1964                          || depth < envEnd.paragraph().params().depth()
1965                          || length != envEnd.paragraph().params().leftIndent());               
1966                 
1967                 // collect macros from environment block
1968                 updateEnvironmentMacros(it, envEnd.pit() - 1, envEnd);
1969         } else {
1970                 // collect macros from paragraph
1971                 updateEnvironmentMacros(it, it.pit(), scope);
1972         }
1973 }
1974
1975
1976 void Buffer::updateInsetMacros(DocIterator & it, DocIterator & scope) const
1977 {
1978         // look for macros in each paragraph
1979         pit_type n = it.lastpit() + 1;
1980         while (it.pit() < n)
1981                 updateBlockMacros(it, scope);       
1982 }
1983
1984
1985 void Buffer::updateMacros() const
1986 {
1987         if (d->macro_lock)
1988                 return;
1989
1990         LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
1991
1992         // start with empty table
1993         d->macros.clear();
1994         d->children_positions.clear();
1995         d->position_to_children.clear();
1996
1997         // Iterate over buffer, starting with first paragraph
1998         // The scope must be bigger than any lookup DocIterator
1999         // later. For the global lookup, lastpit+1 is used, hence
2000         // we use lastpit+2 here.
2001         DocIterator it = par_iterator_begin();
2002         DocIterator outerScope = it;
2003         outerScope.pit() = outerScope.lastpit() + 2;
2004         updateInsetMacros(it, outerScope);
2005 }
2006
2007
2008 void Buffer::updateMacroInstances() const
2009 {
2010         LYXERR(Debug::MACROS, "updateMacroInstances for "
2011                 << d->filename.onlyFileName());
2012         ParConstIterator it = par_iterator_begin();
2013         ParConstIterator end = par_iterator_end();
2014         for (; it != end; it.forwardPos()) {
2015                 // look for MathData cells in InsetMathNest insets
2016                 Inset * inset = it.nextInset();
2017                 if (!inset)
2018                         continue;
2019
2020                 InsetMath * minset = inset->asInsetMath();
2021                 if (!minset)
2022                         continue;
2023
2024                 // update macro in all cells of the InsetMathNest
2025                 DocIterator::idx_type n = minset->nargs();
2026                 MacroContext mc = MacroContext(*this, it);
2027                 for (DocIterator::idx_type i = 0; i < n; ++i) {
2028                         MathData & data = minset->cell(i);
2029                         data.updateMacros(0, mc);
2030                 }
2031         }
2032 }
2033
2034
2035 void Buffer::listMacroNames(MacroNameSet & macros) const
2036 {
2037         if (d->macro_lock)
2038                 return;
2039
2040         d->macro_lock = true;
2041         
2042         // loop over macro names
2043         Impl::NamePositionScopeMacroMap::iterator nameIt
2044         = d->macros.begin();
2045         Impl::NamePositionScopeMacroMap::iterator nameEnd
2046         = d->macros.end();
2047         for (; nameIt != nameEnd; ++nameIt)
2048                 macros.insert(nameIt->first);
2049
2050         // loop over children
2051         Impl::BufferPositionMap::iterator it
2052         = d->children_positions.begin();        
2053         Impl::BufferPositionMap::iterator end
2054         = d->children_positions.end();
2055         for (; it != end; ++it)
2056                 it->first->listMacroNames(macros);
2057
2058         // call parent
2059         if (d->parent_buffer)
2060                 d->parent_buffer->listMacroNames(macros);
2061
2062         d->macro_lock = false;  
2063 }
2064
2065
2066 void Buffer::writeParentMacros(odocstream & os) const
2067 {
2068         if (!d->parent_buffer)
2069                 return;
2070
2071         // collect macro names
2072         MacroNameSet names;
2073         d->parent_buffer->listMacroNames(names);
2074
2075         // resolve and output them
2076         MacroNameSet::iterator it = names.begin();
2077         MacroNameSet::iterator end = names.end();
2078         for (; it != end; ++it) {
2079                 // defined?
2080                 MacroData const * data = 
2081                 d->parent_buffer->getMacro(*it, *this, false);
2082                 if (data)
2083                         data->write(os, true);          
2084         }
2085 }
2086
2087
2088 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2089         InsetCode code)
2090 {
2091         //FIXME: This does not work for child documents yet.
2092         BOOST_ASSERT(code == CITE_CODE || code == REF_CODE);
2093         // Check if the label 'from' appears more than once
2094         vector<docstring> labels;
2095
2096         string paramName;
2097         if (code == CITE_CODE) {
2098                 BiblioInfo keys;
2099                 keys.fillWithBibKeys(this);
2100                 BiblioInfo::const_iterator bit  = keys.begin();
2101                 BiblioInfo::const_iterator bend = keys.end();
2102
2103                 for (; bit != bend; ++bit)
2104                         // FIXME UNICODE
2105                         labels.push_back(bit->first);
2106                 paramName = "key";
2107         } else {
2108                 getLabelList(labels);
2109                 paramName = "reference";
2110         }
2111
2112         if (count(labels.begin(), labels.end(), from) > 1)
2113                 return;
2114
2115         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2116                 if (it->lyxCode() == code) {
2117                         InsetCommand & inset = static_cast<InsetCommand &>(*it);
2118                         docstring const oldValue = inset.getParam(paramName);
2119                         if (oldValue == from)
2120                                 inset.setParam(paramName, to);
2121                 }
2122         }
2123 }
2124
2125
2126 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2127         pit_type par_end, bool full_source)
2128 {
2129         OutputParams runparams(&params().encoding());
2130         runparams.nice = true;
2131         runparams.flavor = OutputParams::LATEX;
2132         runparams.linelen = lyxrc.plaintext_linelen;
2133         // No side effect of file copying and image conversion
2134         runparams.dryrun = true;
2135
2136         d->texrow.reset();
2137         if (full_source) {
2138                 os << "% " << _("Preview source code") << "\n\n";
2139                 d->texrow.newline();
2140                 d->texrow.newline();
2141                 if (isLatex())
2142                         writeLaTeXSource(os, filePath(), runparams, true, true);
2143                 else {
2144                         writeDocBookSource(os, absFileName(), runparams, false);
2145                 }
2146         } else {
2147                 runparams.par_begin = par_begin;
2148                 runparams.par_end = par_end;
2149                 if (par_begin + 1 == par_end)
2150                         os << "% "
2151                            << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2152                            << "\n\n";
2153                 else
2154                         os << "% "
2155                            << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2156                                         convert<docstring>(par_begin),
2157                                         convert<docstring>(par_end - 1))
2158                            << "\n\n";
2159                 d->texrow.newline();
2160                 d->texrow.newline();
2161                 // output paragraphs
2162                 if (isLatex()) {
2163                         latexParagraphs(*this, paragraphs(), os, d->texrow, runparams);
2164                 } else {
2165                         // DocBook
2166                         docbookParagraphs(paragraphs(), *this, os, runparams);
2167                 }
2168         }
2169 }
2170
2171
2172 ErrorList & Buffer::errorList(string const & type) const
2173 {
2174         static ErrorList emptyErrorList;
2175         map<string, ErrorList>::iterator I = d->errorLists.find(type);
2176         if (I == d->errorLists.end())
2177                 return emptyErrorList;
2178
2179         return I->second;
2180 }
2181
2182
2183 void Buffer::structureChanged() const
2184 {
2185         if (gui_)
2186                 gui_->structureChanged();
2187 }
2188
2189
2190 void Buffer::errors(string const & err) const
2191 {
2192         if (gui_)
2193                 gui_->errors(err);
2194 }
2195
2196
2197 void Buffer::message(docstring const & msg) const
2198 {
2199         if (gui_)
2200                 gui_->message(msg);
2201 }
2202
2203
2204 void Buffer::setBusy(bool on) const
2205 {
2206         if (gui_)
2207                 gui_->setBusy(on);
2208 }
2209
2210
2211 void Buffer::setReadOnly(bool on) const
2212 {
2213         if (d->wa_)
2214                 d->wa_->setReadOnly(on);
2215 }
2216
2217
2218 void Buffer::updateTitles() const
2219 {
2220         if (d->wa_)
2221                 d->wa_->updateTitles();
2222 }
2223
2224
2225 void Buffer::resetAutosaveTimers() const
2226 {
2227         if (gui_)
2228                 gui_->resetAutosaveTimers();
2229 }
2230
2231
2232 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2233 {
2234         gui_ = gui;
2235 }
2236
2237
2238
2239 namespace {
2240
2241 class AutoSaveBuffer : public ForkedProcess {
2242 public:
2243         ///
2244         AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2245                 : buffer_(buffer), fname_(fname) {}
2246         ///
2247         virtual boost::shared_ptr<ForkedProcess> clone() const
2248         {
2249                 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2250         }
2251         ///
2252         int start()
2253         {
2254                 command_ = to_utf8(bformat(_("Auto-saving %1$s"), 
2255                                                  from_utf8(fname_.absFilename())));
2256                 return run(DontWait);
2257         }
2258 private:
2259         ///
2260         virtual int generateChild();
2261         ///
2262         Buffer const & buffer_;
2263         FileName fname_;
2264 };
2265
2266
2267 #if !defined (HAVE_FORK)
2268 # define fork() -1
2269 #endif
2270
2271 int AutoSaveBuffer::generateChild()
2272 {
2273         // tmp_ret will be located (usually) in /tmp
2274         // will that be a problem?
2275         pid_t const pid = fork();
2276         // If you want to debug the autosave
2277         // you should set pid to -1, and comment out the fork.
2278         if (pid == 0 || pid == -1) {
2279                 // pid = -1 signifies that lyx was unable
2280                 // to fork. But we will do the save
2281                 // anyway.
2282                 bool failed = false;
2283
2284                 FileName const tmp_ret = FileName::tempName("lyxauto");
2285                 if (!tmp_ret.empty()) {
2286                         buffer_.writeFile(tmp_ret);
2287                         // assume successful write of tmp_ret
2288                         if (!tmp_ret.moveTo(fname_)) {
2289                                 failed = true;
2290                                 // most likely couldn't move between
2291                                 // filesystems unless write of tmp_ret
2292                                 // failed so remove tmp file (if it
2293                                 // exists)
2294                                 tmp_ret.removeFile();
2295                         }
2296                 } else {
2297                         failed = true;
2298                 }
2299
2300                 if (failed) {
2301                         // failed to write/rename tmp_ret so try writing direct
2302                         if (!buffer_.writeFile(fname_)) {
2303                                 // It is dangerous to do this in the child,
2304                                 // but safe in the parent, so...
2305                                 if (pid == -1) // emit message signal.
2306                                         buffer_.message(_("Autosave failed!"));
2307                         }
2308                 }
2309                 if (pid == 0) { // we are the child so...
2310                         _exit(0);
2311                 }
2312         }
2313         return pid;
2314 }
2315
2316 } // namespace anon
2317
2318
2319 // Perfect target for a thread...
2320 void Buffer::autoSave() const
2321 {
2322         if (isBakClean() || isReadonly()) {
2323                 // We don't save now, but we'll try again later
2324                 resetAutosaveTimers();
2325                 return;
2326         }
2327
2328         // emit message signal.
2329         message(_("Autosaving current document..."));
2330
2331         // create autosave filename
2332         string fname = filePath();
2333         fname += '#';
2334         fname += d->filename.onlyFileName();
2335         fname += '#';
2336
2337         AutoSaveBuffer autosave(*this, FileName(fname));
2338         autosave.start();
2339
2340         markBakClean();
2341         resetAutosaveTimers();
2342 }
2343
2344
2345 void Buffer::resetChildDocuments(bool close_them) const
2346 {
2347         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2348                 if (it->lyxCode() != INCLUDE_CODE)
2349                         continue;
2350                 InsetCommand const & inset = static_cast<InsetCommand const &>(*it);
2351                 InsetCommandParams const & ip = inset.params();
2352
2353                 resetParentBuffer(this, ip, close_them);
2354         }
2355
2356         if (use_gui && masterBuffer() == this)
2357                 updateLabels(*this);
2358
2359         // clear references to children in macro tables
2360         d->children_positions.clear();
2361         d->position_to_children.clear();
2362 }
2363
2364
2365 void Buffer::loadChildDocuments() const
2366 {
2367         bool parse_error = false;
2368                 
2369         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2370                 if (it->lyxCode() != INCLUDE_CODE)
2371                         continue;
2372                 InsetCommand const & inset = static_cast<InsetCommand const &>(*it);
2373                 InsetCommandParams const & ip = inset.params();
2374                 Buffer * child = loadIfNeeded(*this, ip);
2375                 if (!child)
2376                         continue;
2377                 parse_error |= !child->errorList("Parse").empty();
2378                 child->loadChildDocuments();
2379         }
2380
2381         if (use_gui && masterBuffer() == this)
2382                 updateLabels(*this);
2383
2384         updateMacros();
2385 }
2386
2387
2388 string Buffer::bufferFormat() const
2389 {
2390         if (isDocBook())
2391                 return "docbook";
2392         if (isLiterate())
2393                 return "literate";
2394         return "latex";
2395 }
2396
2397
2398 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2399         string & result_file) const
2400 {
2401         string backend_format;
2402         OutputParams runparams(&params().encoding());
2403         runparams.flavor = OutputParams::LATEX;
2404         runparams.linelen = lyxrc.plaintext_linelen;
2405         vector<string> backs = backends();
2406         if (find(backs.begin(), backs.end(), format) == backs.end()) {
2407                 // Get shortest path to format
2408                 Graph::EdgePath path;
2409                 for (vector<string>::const_iterator it = backs.begin();
2410                      it != backs.end(); ++it) {
2411                         Graph::EdgePath p = theConverters().getPath(*it, format);
2412                         if (!p.empty() && (path.empty() || p.size() < path.size())) {
2413                                 backend_format = *it;
2414                                 path = p;
2415                         }
2416                 }
2417                 if (!path.empty())
2418                         runparams.flavor = theConverters().getFlavor(path);
2419                 else {
2420                         Alert::error(_("Couldn't export file"),
2421                                 bformat(_("No information for exporting the format %1$s."),
2422                                    formats.prettyName(format)));
2423                         return false;
2424                 }
2425         } else {
2426                 backend_format = format;
2427                 // FIXME: Don't hardcode format names here, but use a flag
2428                 if (backend_format == "pdflatex")
2429                         runparams.flavor = OutputParams::PDFLATEX;
2430         }
2431
2432         string filename = latexName(false);
2433         filename = addName(temppath(), filename);
2434         filename = changeExtension(filename,
2435                                    formats.extension(backend_format));
2436
2437         // fix macros
2438         updateMacroInstances();
2439
2440         // Plain text backend
2441         if (backend_format == "text")
2442                 writePlaintextFile(*this, FileName(filename), runparams);
2443         // no backend
2444         else if (backend_format == "lyx")
2445                 writeFile(FileName(filename));
2446         // Docbook backend
2447         else if (isDocBook()) {
2448                 runparams.nice = !put_in_tempdir;
2449                 makeDocBookFile(FileName(filename), runparams);
2450         }
2451         // LaTeX backend
2452         else if (backend_format == format) {
2453                 runparams.nice = true;
2454                 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2455                         return false;
2456         } else if (!lyxrc.tex_allows_spaces
2457                    && contains(filePath(), ' ')) {
2458                 Alert::error(_("File name error"),
2459                            _("The directory path to the document cannot contain spaces."));
2460                 return false;
2461         } else {
2462                 runparams.nice = false;
2463                 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2464                         return false;
2465         }
2466
2467         string const error_type = (format == "program")
2468                 ? "Build" : bufferFormat();
2469         string const ext = formats.extension(format);
2470         FileName const tmp_result_file(changeExtension(filename, ext));
2471         bool const success = theConverters().convert(this, FileName(filename),
2472                 tmp_result_file, FileName(absFileName()), backend_format, format,
2473                 errorList(error_type));
2474         // Emit the signal to show the error list.
2475         if (format != backend_format)
2476                 errors(error_type);
2477         if (!success)
2478                 return false;
2479
2480         if (put_in_tempdir)
2481                 result_file = tmp_result_file.absFilename();
2482         else {
2483                 result_file = changeExtension(absFileName(), ext);
2484                 // We need to copy referenced files (e. g. included graphics
2485                 // if format == "dvi") to the result dir.
2486                 vector<ExportedFile> const files =
2487                         runparams.exportdata->externalFiles(format);
2488                 string const dest = onlyPath(result_file);
2489                 CopyStatus status = SUCCESS;
2490                 for (vector<ExportedFile>::const_iterator it = files.begin();
2491                                 it != files.end() && status != CANCEL; ++it) {
2492                         string const fmt =
2493                                 formats.getFormatFromFile(it->sourceName);
2494                         status = copyFile(fmt, it->sourceName,
2495                                           makeAbsPath(it->exportName, dest),
2496                                           it->exportName, status == FORCE);
2497                 }
2498                 if (status == CANCEL) {
2499                         message(_("Document export cancelled."));
2500                 } else if (tmp_result_file.exists()) {
2501                         // Finally copy the main file
2502                         status = copyFile(format, tmp_result_file,
2503                                           FileName(result_file), result_file,
2504                                           status == FORCE);
2505                         message(bformat(_("Document exported as %1$s "
2506                                                                "to file `%2$s'"),
2507                                                 formats.prettyName(format),
2508                                                 makeDisplayPath(result_file)));
2509                 } else {
2510                         // This must be a dummy converter like fax (bug 1888)
2511                         message(bformat(_("Document exported as %1$s"),
2512                                                 formats.prettyName(format)));
2513                 }
2514         }
2515
2516         return true;
2517 }
2518
2519
2520 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2521 {
2522         string result_file;
2523         return doExport(format, put_in_tempdir, result_file);
2524 }
2525
2526
2527 bool Buffer::preview(string const & format) const
2528 {
2529         string result_file;
2530         if (!doExport(format, true, result_file))
2531                 return false;
2532         return formats.view(*this, FileName(result_file), format);
2533 }
2534
2535
2536 bool Buffer::isExportable(string const & format) const
2537 {
2538         vector<string> backs = backends();
2539         for (vector<string>::const_iterator it = backs.begin();
2540              it != backs.end(); ++it)
2541                 if (theConverters().isReachable(*it, format))
2542                         return true;
2543         return false;
2544 }
2545
2546
2547 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2548 {
2549         vector<string> backs = backends();
2550         vector<Format const *> result =
2551                 theConverters().getReachable(backs[0], only_viewable, true);
2552         for (vector<string>::const_iterator it = backs.begin() + 1;
2553              it != backs.end(); ++it) {
2554                 vector<Format const *>  r =
2555                         theConverters().getReachable(*it, only_viewable, false);
2556                 result.insert(result.end(), r.begin(), r.end());
2557         }
2558         return result;
2559 }
2560
2561
2562 vector<string> Buffer::backends() const
2563 {
2564         vector<string> v;
2565         if (params().getTextClass().isTeXClassAvailable()) {
2566                 v.push_back(bufferFormat());
2567                 // FIXME: Don't hardcode format names here, but use a flag
2568                 if (v.back() == "latex")
2569                         v.push_back("pdflatex");
2570         }
2571         v.push_back("text");
2572         v.push_back("lyx");
2573         return v;
2574 }
2575
2576
2577 bool Buffer::readFileHelper(FileName const & s)
2578 {
2579         // File information about normal file
2580         if (!s.exists()) {
2581                 docstring const file = makeDisplayPath(s.absFilename(), 50);
2582                 docstring text = bformat(_("The specified document\n%1$s"
2583                                                      "\ncould not be read."), file);
2584                 Alert::error(_("Could not read document"), text);
2585                 return false;
2586         }
2587
2588         // Check if emergency save file exists and is newer.
2589         FileName const e(s.absFilename() + ".emergency");
2590
2591         if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2592                 docstring const file = makeDisplayPath(s.absFilename(), 20);
2593                 docstring const text =
2594                         bformat(_("An emergency save of the document "
2595                                   "%1$s exists.\n\n"
2596                                                "Recover emergency save?"), file);
2597                 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2598                                       _("&Recover"),  _("&Load Original"),
2599                                       _("&Cancel")))
2600                 {
2601                 case 0:
2602                         // the file is not saved if we load the emergency file.
2603                         markDirty();
2604                         return readFile(e);
2605                 case 1:
2606                         break;
2607                 default:
2608                         return false;
2609                 }
2610         }
2611
2612         // Now check if autosave file is newer.
2613         FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2614
2615         if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2616                 docstring const file = makeDisplayPath(s.absFilename(), 20);
2617                 docstring const text =
2618                         bformat(_("The backup of the document "
2619                                   "%1$s is newer.\n\nLoad the "
2620                                                "backup instead?"), file);
2621                 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2622                                       _("&Load backup"), _("Load &original"),
2623                                       _("&Cancel") ))
2624                 {
2625                 case 0:
2626                         // the file is not saved if we load the autosave file.
2627                         markDirty();
2628                         return readFile(a);
2629                 case 1:
2630                         // Here we delete the autosave
2631                         a.removeFile();
2632                         break;
2633                 default:
2634                         return false;
2635                 }
2636         }
2637         return readFile(s);
2638 }
2639
2640
2641 bool Buffer::loadLyXFile(FileName const & s)
2642 {
2643         if (s.isReadableFile()) {
2644                 if (readFileHelper(s)) {
2645                         lyxvc().file_found_hook(s);
2646                         if (!s.isWritable())
2647                                 setReadonly(true);
2648                         return true;
2649                 }
2650         } else {
2651                 docstring const file = makeDisplayPath(s.absFilename(), 20);
2652                 // Here we probably should run
2653                 if (LyXVC::file_not_found_hook(s)) {
2654                         docstring const text =
2655                                 bformat(_("Do you want to retrieve the document"
2656                                                        " %1$s from version control?"), file);
2657                         int const ret = Alert::prompt(_("Retrieve from version control?"),
2658                                 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2659
2660                         if (ret == 0) {
2661                                 // How can we know _how_ to do the checkout?
2662                                 // With the current VC support it has to be,
2663                                 // a RCS file since CVS do not have special ,v files.
2664                                 RCS::retrieve(s);
2665                                 return loadLyXFile(s);
2666                         }
2667                 }
2668         }
2669         return false;
2670 }
2671
2672
2673 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2674 {
2675         TeXErrors::Errors::const_iterator cit = terr.begin();
2676         TeXErrors::Errors::const_iterator end = terr.end();
2677
2678         for (; cit != end; ++cit) {
2679                 int id_start = -1;
2680                 int pos_start = -1;
2681                 int errorRow = cit->error_in_line;
2682                 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2683                                                        pos_start);
2684                 int id_end = -1;
2685                 int pos_end = -1;
2686                 do {
2687                         ++errorRow;
2688                         found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2689                 } while (found && id_start == id_end && pos_start == pos_end);
2690
2691                 errorList.push_back(ErrorItem(cit->error_desc,
2692                         cit->error_text, id_start, pos_start, pos_end));
2693         }
2694 }
2695
2696 } // namespace lyx