]> git.lyx.org Git - lyx.git/blob - src/Buffer.cpp
6a3581e6419094a864d86a6825a3375cda710eb5
[lyx.git] / src / Buffer.cpp
1 /**
2  * \file Buffer.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Stefan Schimanski
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "Buffer.h"
15
16 #include "Author.h"
17 #include "LayoutFile.h"
18 #include "BiblioInfo.h"
19 #include "BranchList.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
23 #include "Bullet.h"
24 #include "Chktex.h"
25 #include "Converter.h"
26 #include "Counters.h"
27 #include "Cursor.h"
28 #include "CutAndPaste.h"
29 #include "DispatchResult.h"
30 #include "DocIterator.h"
31 #include "Encoding.h"
32 #include "ErrorList.h"
33 #include "Exporter.h"
34 #include "Format.h"
35 #include "FuncRequest.h"
36 #include "FuncStatus.h"
37 #include "IndicesList.h"
38 #include "InsetIterator.h"
39 #include "InsetList.h"
40 #include "Language.h"
41 #include "LaTeXFeatures.h"
42 #include "LaTeX.h"
43 #include "Layout.h"
44 #include "Lexer.h"
45 #include "LyXAction.h"
46 #include "LyX.h"
47 #include "LyXRC.h"
48 #include "LyXVC.h"
49 #include "output_docbook.h"
50 #include "output.h"
51 #include "output_latex.h"
52 #include "output_xhtml.h"
53 #include "output_plaintext.h"
54 #include "Paragraph.h"
55 #include "ParagraphParameters.h"
56 #include "ParIterator.h"
57 #include "PDFOptions.h"
58 #include "SpellChecker.h"
59 #include "sgml.h"
60 #include "TexRow.h"
61 #include "TexStream.h"
62 #include "Text.h"
63 #include "TextClass.h"
64 #include "TocBackend.h"
65 #include "Undo.h"
66 #include "VCBackend.h"
67 #include "version.h"
68 #include "WordLangTuple.h"
69 #include "WordList.h"
70
71 #include "insets/InsetBibtex.h"
72 #include "insets/InsetBranch.h"
73 #include "insets/InsetInclude.h"
74 #include "insets/InsetTabular.h"
75 #include "insets/InsetText.h"
76
77 #include "mathed/InsetMathHull.h"
78 #include "mathed/MacroTable.h"
79 #include "mathed/MathMacroTemplate.h"
80 #include "mathed/MathSupport.h"
81
82 #include "graphics/PreviewLoader.h"
83
84 #include "frontends/alert.h"
85 #include "frontends/Delegates.h"
86 #include "frontends/WorkAreaManager.h"
87
88 #include "support/lassert.h"
89 #include "support/convert.h"
90 #include "support/debug.h"
91 #include "support/docstring_list.h"
92 #include "support/ExceptionMessage.h"
93 #include "support/FileName.h"
94 #include "support/FileNameList.h"
95 #include "support/filetools.h"
96 #include "support/ForkedCalls.h"
97 #include "support/gettext.h"
98 #include "support/gzstream.h"
99 #include "support/lstrings.h"
100 #include "support/lyxalgo.h"
101 #include "support/os.h"
102 #include "support/Package.h"
103 #include "support/PathChanger.h"
104 #include "support/Systemcall.h"
105 #include "support/TempFile.h"
106 #include "support/textutils.h"
107 #include "support/types.h"
108
109 #include "support/bind.h"
110 #include "support/shared_ptr.h"
111
112 #include <algorithm>
113 #include <fstream>
114 #include <iomanip>
115 #include <map>
116 #include <set>
117 #include <sstream>
118 #include <vector>
119
120 using namespace std;
121 using namespace lyx::support;
122 using namespace lyx::graphics;
123
124 namespace lyx {
125
126 namespace Alert = frontend::Alert;
127 namespace os = support::os;
128
129 namespace {
130
131 int const LYX_FORMAT = LYX_FORMAT_LYX;
132
133 typedef map<string, bool> DepClean;
134 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
135
136 void showPrintError(string const & name)
137 {
138         docstring str = bformat(_("Could not print the document %1$s.\n"
139                                             "Check that your printer is set up correctly."),
140                              makeDisplayPath(name, 50));
141         Alert::error(_("Print document failed"), str);
142 }
143
144 } // namespace anon
145
146
147 // A storehouse for the cloned buffers.
148 list<CloneList *> cloned_buffers;
149
150
151 class Buffer::Impl
152 {
153 public:
154         Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
155
156         ~Impl()
157         {
158                 delete preview_loader_;
159                 if (wa_) {
160                         wa_->closeAll();
161                         delete wa_;
162                 }
163                 delete inset;
164         }
165
166         /// search for macro in local (buffer) table or in children
167         MacroData const * getBufferMacro(docstring const & name,
168                 DocIterator const & pos) const;
169
170         /// Update macro table starting with position of it \param it in some
171         /// text inset.
172         void updateMacros(DocIterator & it, DocIterator & scope);
173         ///
174         void setLabel(ParIterator & it, UpdateType utype) const;
175
176         /** If we have branches that use the file suffix
177             feature, return the file name with suffix appended.
178         */
179         support::FileName exportFileName() const;
180
181         Buffer * owner_;
182
183         BufferParams params;
184         LyXVC lyxvc;
185         FileName temppath;
186         mutable TexRow texrow;
187
188         /// need to regenerate .tex?
189         DepClean dep_clean;
190
191         /// is save needed?
192         mutable bool lyx_clean;
193
194         /// is autosave needed?
195         mutable bool bak_clean;
196
197         /// is this an unnamed file (New...)?
198         bool unnamed;
199
200         /// is this an internal bufffer?
201         bool internal_buffer;
202
203         /// buffer is r/o
204         bool read_only;
205
206         /// name of the file the buffer is associated with.
207         FileName filename;
208
209         /** Set to true only when the file is fully loaded.
210          *  Used to prevent the premature generation of previews
211          *  and by the citation inset.
212          */
213         bool file_fully_loaded;
214
215         /// Ignore the parent (e.g. when exporting a child standalone)?
216         bool ignore_parent;
217
218         ///
219         mutable TocBackend toc_backend;
220
221         /// macro tables
222         typedef pair<DocIterator, MacroData> ScopeMacro;
223         typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
224         typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
225         /// map from the macro name to the position map,
226         /// which maps the macro definition position to the scope and the MacroData.
227         NamePositionScopeMacroMap macros;
228         /// This seem to change the way Buffer::getMacro() works
229         mutable bool macro_lock;
230
231         /// positions of child buffers in the buffer
232         typedef map<Buffer const * const, DocIterator> BufferPositionMap;
233         typedef pair<DocIterator, Buffer const *> ScopeBuffer;
234         typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
235         /// position of children buffers in this buffer
236         BufferPositionMap children_positions;
237         /// map from children inclusion positions to their scope and their buffer
238         PositionScopeBufferMap position_to_children;
239
240         /// Container for all sort of Buffer dependant errors.
241         map<string, ErrorList> errorLists;
242
243         /// timestamp and checksum used to test if the file has been externally
244         /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
245         time_t timestamp_;
246         unsigned long checksum_;
247
248         ///
249         frontend::WorkAreaManager * wa_;
250         ///
251         frontend::GuiBufferDelegate * gui_;
252
253         ///
254         Undo undo_;
255
256         /// A cache for the bibfiles (including bibfiles of loaded child
257         /// documents), needed for appropriate update of natbib labels.
258         mutable support::FileNameList bibfiles_cache_;
259
260         // FIXME The caching mechanism could be improved. At present, we have a
261         // cache for each Buffer, that caches all the bibliography info for that
262         // Buffer. A more efficient solution would be to have a global cache per
263         // file, and then to construct the Buffer's bibinfo from that.
264         /// A cache for bibliography info
265         mutable BiblioInfo bibinfo_;
266         /// whether the bibinfo cache is valid
267         mutable bool bibinfo_cache_valid_;
268         /// whether the bibfile cache is valid
269         mutable bool bibfile_cache_valid_;
270         /// Cache of timestamps of .bib files
271         map<FileName, time_t> bibfile_status_;
272         /// Indicates whether the bibinfo has changed since the last time
273         /// we ran updateBuffer(), i.e., whether citation labels may need
274         /// to be updated.
275         mutable bool cite_labels_valid_;
276
277         mutable RefCache ref_cache_;
278
279         /// our Text that should be wrapped in an InsetText
280         InsetText * inset;
281
282         ///
283         PreviewLoader * preview_loader_;
284
285         /// This is here to force the test to be done whenever parent_buffer
286         /// is accessed.
287         Buffer const * parent() const
288         {
289                 // ignore_parent temporarily "orphans" a buffer
290                 // (e.g. if a child is compiled standalone)
291                 if (ignore_parent)
292                         return 0;
293                 // if parent_buffer is not loaded, then it has been unloaded,
294                 // which means that parent_buffer is an invalid pointer. So we
295                 // set it to null in that case.
296                 // however, the BufferList doesn't know about cloned buffers, so
297                 // they will always be regarded as unloaded. in that case, we hope
298                 // for the best.
299                 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
300                         parent_buffer = 0;
301                 return parent_buffer;
302         }
303
304         ///
305         void setParent(Buffer const * pb)
306         {
307                 if (parent_buffer == pb)
308                         // nothing to do
309                         return;
310                 if (!cloned_buffer_ && parent_buffer && pb)
311                         LYXERR0("Warning: a buffer should not have two parents!");
312                 parent_buffer = pb;
313                 if (!cloned_buffer_ && parent_buffer) {
314                         parent_buffer->invalidateBibfileCache();
315                         parent_buffer->invalidateBibinfoCache();
316                 }
317         }
318
319         /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
320         /// This one is useful for preview detached in a thread.
321         Buffer const * cloned_buffer_;
322         ///
323         CloneList * clone_list_;
324         /// are we in the process of exporting this buffer?
325         mutable bool doing_export;
326  
327         /// compute statistics
328         /// \p from initial position
329         /// \p to points to the end position
330         void updateStatistics(DocIterator & from, DocIterator & to,
331                               bool skipNoOutput = true);
332         /// statistics accessor functions
333         int wordCount() const
334         {
335                 return word_count_;
336         }
337         int charCount(bool with_blanks) const
338         {
339                 return char_count_
340                 + (with_blanks ? blank_count_ : 0);
341         }
342
343 private:
344         /// So we can force access via the accessors.
345         mutable Buffer const * parent_buffer;
346
347         int word_count_;
348         int char_count_;
349         int blank_count_;
350
351 };
352
353
354 /// Creates the per buffer temporary directory
355 static FileName createBufferTmpDir()
356 {
357         static int count;
358         // We are in our own directory.  Why bother to mangle name?
359         // In fact I wrote this code to circumvent a problematic behaviour
360         // (bug?) of EMX mkstemp().
361         FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
362                 convert<string>(count++));
363
364         if (!tmpfl.createDirectory(0777)) {
365                 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
366                         _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
367                         from_utf8(tmpfl.absFileName())));
368         }
369         return tmpfl;
370 }
371
372
373 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
374         Buffer const * cloned_buffer)
375         : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
376           internal_buffer(false), read_only(readonly_), filename(file),
377           file_fully_loaded(false), ignore_parent(false), toc_backend(owner),
378           macro_lock(false), timestamp_(0), checksum_(0), wa_(0), gui_(0),
379           undo_(*owner), bibinfo_cache_valid_(false), bibfile_cache_valid_(false),
380           cite_labels_valid_(false), preview_loader_(0),
381           cloned_buffer_(cloned_buffer), clone_list_(0),
382           doing_export(false), parent_buffer(0)
383 {
384         if (!cloned_buffer_) {
385                 temppath = createBufferTmpDir();
386                 lyxvc.setBuffer(owner_);
387                 if (use_gui)
388                         wa_ = new frontend::WorkAreaManager;
389                 return;
390         }
391         temppath = cloned_buffer_->d->temppath;
392         file_fully_loaded = true;
393         params = cloned_buffer_->d->params;
394         bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
395         bibinfo_ = cloned_buffer_->d->bibinfo_;
396         bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
397         bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
398         bibfile_status_ = cloned_buffer_->d->bibfile_status_;
399         cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
400         unnamed = cloned_buffer_->d->unnamed;
401         internal_buffer = cloned_buffer_->d->internal_buffer;
402 }
403
404
405 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
406         : d(new Impl(this, FileName(file), readonly, cloned_buffer))
407 {
408         LYXERR(Debug::INFO, "Buffer::Buffer()");
409         if (cloned_buffer) {
410                 d->inset = new InsetText(*cloned_buffer->d->inset);
411                 d->inset->setBuffer(*this);
412                 // FIXME: optimize this loop somewhat, maybe by creating a new
413                 // general recursive Inset::setId().
414                 DocIterator it = doc_iterator_begin(this);
415                 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
416                 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
417                         it.paragraph().setId(cloned_it.paragraph().id());
418         } else
419                 d->inset = new InsetText(this);
420         d->inset->setAutoBreakRows(true);
421         d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
422 }
423
424
425 Buffer::~Buffer()
426 {
427         LYXERR(Debug::INFO, "Buffer::~Buffer()");
428         // here the buffer should take care that it is
429         // saved properly, before it goes into the void.
430
431         // GuiView already destroyed
432         d->gui_ = 0;
433
434         if (isInternal()) {
435                 // No need to do additional cleanups for internal buffer.
436                 delete d;
437                 return;
438         }
439
440         if (isClone()) {
441                 // this is in case of recursive includes: we won't try to delete
442                 // ourselves as a child.
443                 d->clone_list_->erase(this);
444                 // loop over children
445                 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
446                 Impl::BufferPositionMap::iterator end = d->children_positions.end();
447                 for (; it != end; ++it) {
448                         Buffer * child = const_cast<Buffer *>(it->first);
449                                 if (d->clone_list_->erase(child))
450                                         delete child;
451                 }
452                 // if we're the master buffer, then we should get rid of the list
453                 // of clones
454                 if (!parent()) {
455                         // If this is not empty, we have leaked something. Worse, one of the
456                         // children still has a reference to this list. But we will try to
457                         // continue, rather than shut down.
458                         LATTEST(d->clone_list_->empty());
459                         list<CloneList *>::iterator it =
460                                 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
461                         if (it == cloned_buffers.end()) {
462                                 // We will leak in this case, but it is safe to continue.
463                                 LATTEST(false);
464                         } else
465                                 cloned_buffers.erase(it);
466                         delete d->clone_list_;
467                 }
468                 // FIXME Do we really need to do this right before we delete d?
469                 // clear references to children in macro tables
470                 d->children_positions.clear();
471                 d->position_to_children.clear();
472         } else {
473                 // loop over children
474                 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
475                 Impl::BufferPositionMap::iterator end = d->children_positions.end();
476                 for (; it != end; ++it) {
477                         Buffer * child = const_cast<Buffer *>(it->first);
478                         if (theBufferList().isLoaded(child))
479                                 theBufferList().releaseChild(this, child);
480                 }
481
482                 if (!isClean()) {
483                         docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
484                         msg += emergencyWrite();
485                         Alert::warning(_("Attempting to close changed document!"), msg);
486                 }
487
488                 // FIXME Do we really need to do this right before we delete d?
489                 // clear references to children in macro tables
490                 d->children_positions.clear();
491                 d->position_to_children.clear();
492
493                 if (!d->temppath.destroyDirectory()) {
494                         Alert::warning(_("Could not remove temporary directory"),
495                                 bformat(_("Could not remove the temporary directory %1$s"),
496                                 from_utf8(d->temppath.absFileName())));
497                 }
498                 removePreviews();
499         }
500
501         delete d;
502 }
503
504
505 Buffer * Buffer::cloneFromMaster() const
506 {
507         BufferMap bufmap;
508         cloned_buffers.push_back(new CloneList);
509         CloneList * clones = cloned_buffers.back();
510
511         masterBuffer()->cloneWithChildren(bufmap, clones);
512
513         // make sure we got cloned
514         BufferMap::const_iterator bit = bufmap.find(this);
515         LASSERT(bit != bufmap.end(), return 0);
516         Buffer * cloned_buffer = bit->second;
517
518         return cloned_buffer;
519 }
520
521
522 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList * clones) const
523 {
524         // have we already been cloned?
525         if (bufmap.find(this) != bufmap.end())
526                 return;
527
528         Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
529
530         // The clone needs its own DocumentClass, since running updateBuffer() will
531         // modify it, and we would otherwise be sharing it with the original Buffer.
532         buffer_clone->params().makeDocumentClass();
533         ErrorList el;
534         cap::switchBetweenClasses(
535                         params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
536                         static_cast<InsetText &>(buffer_clone->inset()), el);
537
538         bufmap[this] = buffer_clone;
539         clones->insert(buffer_clone);
540         buffer_clone->d->clone_list_ = clones;
541         buffer_clone->d->macro_lock = true;
542         buffer_clone->d->children_positions.clear();
543
544         // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
545         // math macro caches need to be rethought and simplified.
546         // I am not sure wether we should handle Buffer cloning here or in BufferList.
547         // Right now BufferList knows nothing about buffer clones.
548         Impl::PositionScopeBufferMap::iterator it = d->position_to_children.begin();
549         Impl::PositionScopeBufferMap::iterator end = d->position_to_children.end();
550         for (; it != end; ++it) {
551                 DocIterator dit = it->first.clone(buffer_clone);
552                 dit.setBuffer(buffer_clone);
553                 Buffer * child = const_cast<Buffer *>(it->second.second);
554
555                 child->cloneWithChildren(bufmap, clones);
556                 BufferMap::iterator const bit = bufmap.find(child);
557                 LASSERT(bit != bufmap.end(), continue);
558                 Buffer * child_clone = bit->second;
559
560                 Inset * inset = dit.nextInset();
561                 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
562                 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
563                 inset_inc->setChildBuffer(child_clone);
564                 child_clone->d->setParent(buffer_clone);
565                 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
566                 buffer_clone->setChild(dit, child_clone);
567         }
568         buffer_clone->d->macro_lock = false;
569         return;
570 }
571
572
573 Buffer * Buffer::cloneBufferOnly() const {
574         cloned_buffers.push_back(new CloneList);
575         CloneList * clones = cloned_buffers.back();
576         Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
577
578         // The clone needs its own DocumentClass, since running updateBuffer() will
579         // modify it, and we would otherwise be sharing it with the original Buffer.
580         buffer_clone->params().makeDocumentClass();
581         ErrorList el;
582         cap::switchBetweenClasses(
583                         params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
584                         static_cast<InsetText &>(buffer_clone->inset()), el);
585
586         clones->insert(buffer_clone);
587         buffer_clone->d->clone_list_ = clones;
588
589         // we won't be cloning the children
590         buffer_clone->d->children_positions.clear();
591         return buffer_clone;
592 }
593
594
595 bool Buffer::isClone() const
596 {
597         return d->cloned_buffer_;
598 }
599
600
601 void Buffer::changed(bool update_metrics) const
602 {
603         if (d->wa_)
604                 d->wa_->redrawAll(update_metrics);
605 }
606
607
608 frontend::WorkAreaManager & Buffer::workAreaManager() const
609 {
610         LBUFERR(d->wa_);
611         return *d->wa_;
612 }
613
614
615 Text & Buffer::text() const
616 {
617         return d->inset->text();
618 }
619
620
621 Inset & Buffer::inset() const
622 {
623         return *d->inset;
624 }
625
626
627 BufferParams & Buffer::params()
628 {
629         return d->params;
630 }
631
632
633 BufferParams const & Buffer::params() const
634 {
635         return d->params;
636 }
637
638
639 ParagraphList & Buffer::paragraphs()
640 {
641         return text().paragraphs();
642 }
643
644
645 ParagraphList const & Buffer::paragraphs() const
646 {
647         return text().paragraphs();
648 }
649
650
651 LyXVC & Buffer::lyxvc()
652 {
653         return d->lyxvc;
654 }
655
656
657 LyXVC const & Buffer::lyxvc() const
658 {
659         return d->lyxvc;
660 }
661
662
663 string const Buffer::temppath() const
664 {
665         return d->temppath.absFileName();
666 }
667
668
669 TexRow & Buffer::texrow()
670 {
671         return d->texrow;
672 }
673
674
675 TexRow const & Buffer::texrow() const
676 {
677         return d->texrow;
678 }
679
680
681 TocBackend & Buffer::tocBackend() const
682 {
683         return d->toc_backend;
684 }
685
686
687 Undo & Buffer::undo()
688 {
689         return d->undo_;
690 }
691
692
693 void Buffer::setChild(DocIterator const & dit, Buffer * child)
694 {
695         d->children_positions[child] = dit;
696 }
697
698
699 string Buffer::latexName(bool const no_path) const
700 {
701         FileName latex_name =
702                 makeLatexName(d->exportFileName());
703         return no_path ? latex_name.onlyFileName()
704                 : latex_name.absFileName();
705 }
706
707
708 FileName Buffer::Impl::exportFileName() const
709 {
710         docstring const branch_suffix =
711                 params.branchlist().getFileNameSuffix();
712         if (branch_suffix.empty())
713                 return filename;
714
715         string const name = filename.onlyFileNameWithoutExt()
716                 + to_utf8(branch_suffix);
717         FileName res(filename.onlyPath().absFileName() + "/" + name);
718         res.changeExtension(filename.extension());
719
720         return res;
721 }
722
723
724 string Buffer::logName(LogType * type) const
725 {
726         string const filename = latexName(false);
727
728         if (filename.empty()) {
729                 if (type)
730                         *type = latexlog;
731                 return string();
732         }
733
734         string const path = temppath();
735
736         FileName const fname(addName(temppath(),
737                                      onlyFileName(changeExtension(filename,
738                                                                   ".log"))));
739
740         // FIXME: how do we know this is the name of the build log?
741         FileName const bname(
742                 addName(path, onlyFileName(
743                         changeExtension(filename,
744                                         formats.extension(params().bufferFormat()) + ".out"))));
745
746         // Also consider the master buffer log file
747         FileName masterfname = fname;
748         LogType mtype;
749         if (masterBuffer() != this) {
750                 string const mlogfile = masterBuffer()->logName(&mtype);
751                 masterfname = FileName(mlogfile);
752         }
753
754         // If no Latex log or Build log is newer, show Build log
755         if (bname.exists() &&
756             ((!fname.exists() && !masterfname.exists())
757              || (fname.lastModified() < bname.lastModified()
758                  && masterfname.lastModified() < bname.lastModified()))) {
759                 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
760                 if (type)
761                         *type = buildlog;
762                 return bname.absFileName();
763         // If we have a newer master file log or only a master log, show this
764         } else if (fname != masterfname
765                    && (!fname.exists() && (masterfname.exists()
766                    || fname.lastModified() < masterfname.lastModified()))) {
767                 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
768                 if (type)
769                         *type = mtype;
770                 return masterfname.absFileName();
771         }
772         LYXERR(Debug::FILES, "Log name calculated as: " << fname);
773         if (type)
774                         *type = latexlog;
775         return fname.absFileName();
776 }
777
778
779 void Buffer::setReadonly(bool const flag)
780 {
781         if (d->read_only != flag) {
782                 d->read_only = flag;
783                 changed(false);
784         }
785 }
786
787
788 void Buffer::setFileName(FileName const & fname)
789 {
790         bool const changed = fname != d->filename;
791         d->filename = fname;
792         if (changed)
793                 lyxvc().file_found_hook(fname);
794         setReadonly(d->filename.isReadOnly());
795         saveCheckSum();
796         updateTitles();
797 }
798
799
800 int Buffer::readHeader(Lexer & lex)
801 {
802         int unknown_tokens = 0;
803         int line = -1;
804         int begin_header_line = -1;
805
806         // Initialize parameters that may be/go lacking in header:
807         params().branchlist().clear();
808         params().preamble.erase();
809         params().options.erase();
810         params().master.erase();
811         params().float_placement.erase();
812         params().paperwidth.erase();
813         params().paperheight.erase();
814         params().leftmargin.erase();
815         params().rightmargin.erase();
816         params().topmargin.erase();
817         params().bottommargin.erase();
818         params().headheight.erase();
819         params().headsep.erase();
820         params().footskip.erase();
821         params().columnsep.erase();
822         params().fonts_cjk.erase();
823         params().listings_params.clear();
824         params().clearLayoutModules();
825         params().clearRemovedModules();
826         params().clearIncludedChildren();
827         params().pdfoptions().clear();
828         params().indiceslist().clear();
829         params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
830         params().isbackgroundcolor = false;
831         params().fontcolor = RGBColor(0, 0, 0);
832         params().isfontcolor = false;
833         params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
834         params().boxbgcolor = RGBColor(0xFF, 0, 0);
835         params().html_latex_start.clear();
836         params().html_latex_end.clear();
837         params().html_math_img_scale = 1.0;
838         params().output_sync_macro.erase();
839         params().setLocalLayout(string(), false);
840         params().setLocalLayout(string(), true);
841
842         for (int i = 0; i < 4; ++i) {
843                 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
844                 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
845         }
846
847         ErrorList & errorList = d->errorLists["Parse"];
848
849         while (lex.isOK()) {
850                 string token;
851                 lex >> token;
852
853                 if (token.empty())
854                         continue;
855
856                 if (token == "\\end_header")
857                         break;
858
859                 ++line;
860                 if (token == "\\begin_header") {
861                         begin_header_line = line;
862                         continue;
863                 }
864
865                 LYXERR(Debug::PARSER, "Handling document header token: `"
866                                       << token << '\'');
867
868                 string unknown = params().readToken(lex, token, d->filename.onlyPath());
869                 if (!unknown.empty()) {
870                         if (unknown[0] != '\\' && token == "\\textclass") {
871                                 Alert::warning(_("Unknown document class"),
872                        bformat(_("Using the default document class, because the "
873                                               "class %1$s is unknown."), from_utf8(unknown)));
874                         } else {
875                                 ++unknown_tokens;
876                                 docstring const s = bformat(_("Unknown token: "
877                                                                         "%1$s %2$s\n"),
878                                                          from_utf8(token),
879                                                          lex.getDocString());
880                                 errorList.push_back(ErrorItem(_("Document header error"),
881                                         s, -1, 0, 0));
882                         }
883                 }
884         }
885         if (begin_header_line) {
886                 docstring const s = _("\\begin_header is missing");
887                 errorList.push_back(ErrorItem(_("Document header error"),
888                         s, -1, 0, 0));
889         }
890
891         params().makeDocumentClass();
892
893         return unknown_tokens;
894 }
895
896
897 // Uwe C. Schroeder
898 // changed to be public and have one parameter
899 // Returns true if "\end_document" is not read (Asger)
900 bool Buffer::readDocument(Lexer & lex)
901 {
902         ErrorList & errorList = d->errorLists["Parse"];
903         errorList.clear();
904
905         // remove dummy empty par
906         paragraphs().clear();
907
908         if (!lex.checkFor("\\begin_document")) {
909                 docstring const s = _("\\begin_document is missing");
910                 errorList.push_back(ErrorItem(_("Document header error"),
911                         s, -1, 0, 0));
912         }
913
914         readHeader(lex);
915
916         if (params().outputChanges) {
917                 bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
918                 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
919                                   LaTeXFeatures::isAvailable("xcolor");
920
921                 if (!dvipost && !xcolorulem) {
922                         Alert::warning(_("Changes not shown in LaTeX output"),
923                                        _("Changes will not be highlighted in LaTeX output, "
924                                          "because neither dvipost nor xcolor/ulem are installed.\n"
925                                          "Please install these packages or redefine "
926                                          "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
927                 } else if (!xcolorulem) {
928                         Alert::warning(_("Changes not shown in LaTeX output"),
929                                        _("Changes will not be highlighted in LaTeX output "
930                                          "when using pdflatex, because xcolor and ulem are not installed.\n"
931                                          "Please install both packages or redefine "
932                                          "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
933                 }
934         }
935
936         if (!params().master.empty()) {
937                 FileName const master_file = makeAbsPath(params().master,
938                            onlyPath(absFileName()));
939                 if (isLyXFileName(master_file.absFileName())) {
940                         Buffer * master =
941                                 checkAndLoadLyXFile(master_file, true);
942                         if (master) {
943                                 // necessary e.g. after a reload
944                                 // to re-register the child (bug 5873)
945                                 // FIXME: clean up updateMacros (here, only
946                                 // child registering is needed).
947                                 master->updateMacros();
948                                 // set master as master buffer, but only
949                                 // if we are a real child
950                                 if (master->isChild(this))
951                                         setParent(master);
952                                 // if the master is not fully loaded
953                                 // it is probably just loading this
954                                 // child. No warning needed then.
955                                 else if (master->isFullyLoaded())
956                                         LYXERR0("The master '"
957                                                 << params().master
958                                                 << "' assigned to this document ("
959                                                 << absFileName()
960                                                 << ") does not include "
961                                                 "this document. Ignoring the master assignment.");
962                         }
963                 }
964         }
965
966         // assure we have a default index
967         params().indiceslist().addDefault(B_("Index"));
968
969         // read main text
970         bool const res = text().read(lex, errorList, d->inset);
971
972         // inform parent buffer about local macros
973         if (parent()) {
974                 Buffer const * pbuf = parent();
975                 UserMacroSet::const_iterator cit = usermacros.begin();
976                 UserMacroSet::const_iterator end = usermacros.end();
977                 for (; cit != end; ++cit)
978                         pbuf->usermacros.insert(*cit);
979         }
980         usermacros.clear();
981         updateMacros();
982         updateMacroInstances(InternalUpdate);
983         return res;
984 }
985
986
987 bool Buffer::importString(string const & format, docstring const & contents, ErrorList & errorList)
988 {
989         Format const * fmt = formats.getFormat(format);
990         if (!fmt)
991                 return false;
992         // It is important to use the correct extension here, since some
993         // converters create a wrong output file otherwise (e.g. html2latex)
994         TempFile const tempfile("Buffer_importStringXXXXXX." + fmt->extension());
995         FileName const name(tempfile.name());
996         ofdocstream os(name.toFilesystemEncoding().c_str());
997         bool const success = (os << contents);
998         os.close();
999
1000         bool converted = false;
1001         if (success) {
1002                 params().compressed = false;
1003
1004                 // remove dummy empty par
1005                 paragraphs().clear();
1006
1007                 converted = importFile(format, name, errorList);
1008         }
1009
1010         if (name.exists())
1011                 name.removeFile();
1012         return converted;
1013 }
1014
1015
1016 bool Buffer::importFile(string const & format, FileName const & name, ErrorList & errorList)
1017 {
1018         if (!theConverters().isReachable(format, "lyx"))
1019                 return false;
1020
1021         TempFile const tempfile("Buffer_importFileXXXXXX.lyx");
1022         FileName const lyx(tempfile.name());
1023         if (theConverters().convert(0, name, lyx, name, format, "lyx", errorList))
1024                 return readFile(lyx) == ReadSuccess;
1025
1026         return false;
1027 }
1028
1029
1030 bool Buffer::readString(string const & s)
1031 {
1032         params().compressed = false;
1033
1034         Lexer lex;
1035         istringstream is(s);
1036         lex.setStream(is);
1037         FileName const fn = FileName::tempName("Buffer_readString");
1038
1039         int file_format;
1040         bool success = parseLyXFormat(lex, fn, file_format) == ReadSuccess;
1041
1042         if (success && file_format != LYX_FORMAT) {
1043                 // We need to call lyx2lyx, so write the input to a file
1044                 ofstream os(fn.toFilesystemEncoding().c_str());
1045                 os << s;
1046                 os.close();
1047                 // lyxvc in readFile
1048                 if (readFile(fn) != ReadSuccess)
1049                         success = false;
1050         }
1051         else if (success)
1052                 if (readDocument(lex))
1053                         success = false;
1054         if (fn.exists())
1055                 fn.removeFile();
1056         return success;
1057 }
1058
1059
1060 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
1061 {
1062         FileName fname(fn);
1063         Lexer lex;
1064         if (!lex.setFile(fname)) {
1065                 Alert::error(_("File Not Found"),
1066                         bformat(_("Unable to open file `%1$s'."),
1067                                 from_utf8(fn.absFileName())));
1068                 return ReadFileNotFound;
1069         }
1070
1071         int file_format;
1072         ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
1073         if (ret_plf != ReadSuccess)
1074                 return ret_plf;
1075
1076         if (file_format != LYX_FORMAT) {
1077                 FileName tmpFile;
1078                 ReadStatus const ret_clf = convertLyXFormat(fn, tmpFile, file_format);
1079                 if (ret_clf != ReadSuccess)
1080                         return ret_clf;
1081                 return readFile(tmpFile);
1082         }
1083
1084         // FIXME: InsetInfo needs to know whether the file is under VCS
1085         // during the parse process, so this has to be done before.
1086         lyxvc().file_found_hook(d->filename);
1087
1088         if (readDocument(lex)) {
1089                 Alert::error(_("Document format failure"),
1090                         bformat(_("%1$s ended unexpectedly, which means"
1091                                 " that it is probably corrupted."),
1092                                         from_utf8(fn.absFileName())));
1093                 return ReadDocumentFailure;
1094         }
1095
1096         d->file_fully_loaded = true;
1097         d->read_only = !d->filename.isWritable();
1098         params().compressed = formats.isZippedFile(d->filename);
1099         saveCheckSum();
1100         return ReadSuccess;
1101 }
1102
1103
1104 bool Buffer::isFullyLoaded() const
1105 {
1106         return d->file_fully_loaded;
1107 }
1108
1109
1110 void Buffer::setFullyLoaded(bool value)
1111 {
1112         d->file_fully_loaded = value;
1113 }
1114
1115
1116 PreviewLoader * Buffer::loader() const
1117 {
1118         if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1119                 return 0;
1120         if (!d->preview_loader_)
1121                 d->preview_loader_ = new PreviewLoader(*this);
1122         return d->preview_loader_;
1123 }
1124
1125
1126 void Buffer::removePreviews() const
1127 {
1128         delete d->preview_loader_;
1129         d->preview_loader_ = 0;
1130 }
1131
1132
1133 void Buffer::updatePreviews() const
1134 {
1135         PreviewLoader * ploader = loader();
1136         if (!ploader)
1137                 return;
1138
1139         InsetIterator it = inset_iterator_begin(*d->inset);
1140         InsetIterator const end = inset_iterator_end(*d->inset);
1141         for (; it != end; ++it)
1142                 it->addPreview(it, *ploader);
1143
1144         ploader->startLoading();
1145 }
1146
1147
1148 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1149         FileName const & fn, int & file_format) const
1150 {
1151         if(!lex.checkFor("\\lyxformat")) {
1152                 Alert::error(_("Document format failure"),
1153                         bformat(_("%1$s is not a readable LyX document."),
1154                                 from_utf8(fn.absFileName())));
1155                 return ReadNoLyXFormat;
1156         }
1157
1158         string tmp_format;
1159         lex >> tmp_format;
1160
1161         // LyX formats 217 and earlier were written as 2.17. This corresponds
1162         // to files from LyX versions < 1.1.6.3. We just remove the dot in
1163         // these cases. See also: www.lyx.org/trac/changeset/1313.
1164         size_t dot = tmp_format.find_first_of(".,");
1165         if (dot != string::npos)
1166                 tmp_format.erase(dot, 1);
1167
1168         file_format = convert<int>(tmp_format);
1169         return ReadSuccess;
1170 }
1171
1172
1173 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1174         FileName & tmpfile, int from_format)
1175 {
1176         tmpfile = FileName::tempName("Buffer_convertLyXFormatXXXXXX.lyx");
1177         if(tmpfile.empty()) {
1178                 Alert::error(_("Conversion failed"),
1179                         bformat(_("%1$s is from a different"
1180                                 " version of LyX, but a temporary"
1181                                 " file for converting it could"
1182                                 " not be created."),
1183                                 from_utf8(fn.absFileName())));
1184                 return LyX2LyXNoTempFile;
1185         }
1186
1187         FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1188         if (lyx2lyx.empty()) {
1189                 Alert::error(_("Conversion script not found"),
1190                      bformat(_("%1$s is from a different"
1191                                " version of LyX, but the"
1192                                " conversion script lyx2lyx"
1193                                " could not be found."),
1194                                from_utf8(fn.absFileName())));
1195                 return LyX2LyXNotFound;
1196         }
1197
1198         // Run lyx2lyx:
1199         //   $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1200         ostringstream command;
1201         command << os::python()
1202                 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1203                 << " -t " << convert<string>(LYX_FORMAT)
1204                 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
1205                 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1206         string const command_str = command.str();
1207
1208         LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1209
1210         cmd_ret const ret = runCommand(command_str);
1211         if (ret.first != 0) {
1212                 if (from_format < LYX_FORMAT) {
1213                         Alert::error(_("Conversion script failed"),
1214                                 bformat(_("%1$s is from an older version"
1215                                         " of LyX and the lyx2lyx script"
1216                                         " failed to convert it."),
1217                                         from_utf8(fn.absFileName())));
1218                         return LyX2LyXOlderFormat;
1219                 } else {
1220                         Alert::error(_("Conversion script failed"),
1221                                 bformat(_("%1$s is from a newer version"
1222                                         " of LyX and the lyx2lyx script"
1223                                         " failed to convert it."),
1224                                         from_utf8(fn.absFileName())));
1225                         return LyX2LyXNewerFormat;
1226                 }
1227         }
1228         return ReadSuccess;
1229 }
1230
1231
1232 // Should probably be moved to somewhere else: BufferView? GuiView?
1233 bool Buffer::save() const
1234 {
1235         docstring const file = makeDisplayPath(absFileName(), 20);
1236         d->filename.refresh();
1237
1238         // check the read-only status before moving the file as a backup
1239         if (d->filename.exists()) {
1240                 bool const read_only = !d->filename.isWritable();
1241                 if (read_only) {
1242                         Alert::warning(_("File is read-only"),
1243                                 bformat(_("The file %1$s cannot be written because it "
1244                                 "is marked as read-only."), file));
1245                         return false;
1246                 }
1247         }
1248
1249         // ask if the disk file has been externally modified (use checksum method)
1250         if (fileName().exists() && isExternallyModified(checksum_method)) {
1251                 docstring text =
1252                         bformat(_("Document %1$s has been externally modified. "
1253                                 "Are you sure you want to overwrite this file?"), file);
1254                 int const ret = Alert::prompt(_("Overwrite modified file?"),
1255                         text, 1, 1, _("&Overwrite"), _("&Cancel"));
1256                 if (ret == 1)
1257                         return false;
1258         }
1259
1260         // We don't need autosaves in the immediate future. (Asger)
1261         resetAutosaveTimers();
1262
1263         FileName backupName;
1264         bool madeBackup = false;
1265
1266         // make a backup if the file already exists
1267         if (lyxrc.make_backup && fileName().exists()) {
1268                 backupName = FileName(absFileName() + '~');
1269                 if (!lyxrc.backupdir_path.empty()) {
1270                         string const mangledName =
1271                                 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1272                         backupName = FileName(addName(lyxrc.backupdir_path,
1273                                                       mangledName));
1274                 }
1275
1276                 // Except file is symlink do not copy because of #6587.
1277                 // Hard links have bad luck.
1278                 if (fileName().isSymLink())
1279                         madeBackup = fileName().copyTo(backupName);
1280                 else
1281                         madeBackup = fileName().moveTo(backupName);
1282
1283                 if (!madeBackup) {
1284                         Alert::error(_("Backup failure"),
1285                                      bformat(_("Cannot create backup file %1$s.\n"
1286                                                "Please check whether the directory exists and is writable."),
1287                                              from_utf8(backupName.absFileName())));
1288                         //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1289                 }
1290         }
1291
1292         if (writeFile(d->filename)) {
1293                 markClean();
1294                 return true;
1295         } else {
1296                 // Saving failed, so backup is not backup
1297                 if (madeBackup)
1298                         backupName.moveTo(d->filename);
1299                 return false;
1300         }
1301 }
1302
1303
1304 bool Buffer::writeFile(FileName const & fname) const
1305 {
1306         if (d->read_only && fname == d->filename)
1307                 return false;
1308
1309         bool retval = false;
1310
1311         docstring const str = bformat(_("Saving document %1$s..."),
1312                 makeDisplayPath(fname.absFileName()));
1313         message(str);
1314
1315         string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1316
1317         if (params().compressed) {
1318                 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1319                 retval = ofs && write(ofs);
1320         } else {
1321                 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1322                 retval = ofs && write(ofs);
1323         }
1324
1325         if (!retval) {
1326                 message(str + _(" could not write file!"));
1327                 return false;
1328         }
1329
1330         // see bug 6587
1331         // removeAutosaveFile();
1332
1333         saveCheckSum();
1334         message(str + _(" done."));
1335
1336         return true;
1337 }
1338
1339
1340 docstring Buffer::emergencyWrite()
1341 {
1342         // No need to save if the buffer has not changed.
1343         if (isClean())
1344                 return docstring();
1345
1346         string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1347
1348         docstring user_message = bformat(
1349                 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1350
1351         // We try to save three places:
1352         // 1) Same place as document. Unless it is an unnamed doc.
1353         if (!isUnnamed()) {
1354                 string s = absFileName();
1355                 s += ".emergency";
1356                 LYXERR0("  " << s);
1357                 if (writeFile(FileName(s))) {
1358                         markClean();
1359                         user_message += "  " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1360                         return user_message;
1361                 } else {
1362                         user_message += "  " + _("Save failed! Trying again...\n");
1363                 }
1364         }
1365
1366         // 2) In HOME directory.
1367         string s = addName(Package::get_home_dir().absFileName(), absFileName());
1368         s += ".emergency";
1369         lyxerr << ' ' << s << endl;
1370         if (writeFile(FileName(s))) {
1371                 markClean();
1372                 user_message += "  " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1373                 return user_message;
1374         }
1375
1376         user_message += "  " + _("Save failed! Trying yet again...\n");
1377
1378         // 3) In "/tmp" directory.
1379         // MakeAbsPath to prepend the current
1380         // drive letter on OS/2
1381         s = addName(package().temp_dir().absFileName(), absFileName());
1382         s += ".emergency";
1383         lyxerr << ' ' << s << endl;
1384         if (writeFile(FileName(s))) {
1385                 markClean();
1386                 user_message += "  " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1387                 return user_message;
1388         }
1389
1390         user_message += "  " + _("Save failed! Bummer. Document is lost.");
1391         // Don't try again.
1392         markClean();
1393         return user_message;
1394 }
1395
1396
1397 bool Buffer::write(ostream & ofs) const
1398 {
1399 #ifdef HAVE_LOCALE
1400         // Use the standard "C" locale for file output.
1401         ofs.imbue(locale::classic());
1402 #endif
1403
1404         // The top of the file should not be written by params().
1405
1406         // write out a comment in the top of the file
1407         // Important: Keep the version formatting in sync with lyx2lyx and
1408         //            tex2lyx (bug 7951)
1409         ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1410             << " created this file. For more info see http://www.lyx.org/\n"
1411             << "\\lyxformat " << LYX_FORMAT << "\n"
1412             << "\\begin_document\n";
1413
1414         /// For each author, set 'used' to true if there is a change
1415         /// by this author in the document; otherwise set it to 'false'.
1416         AuthorList::Authors::const_iterator a_it = params().authors().begin();
1417         AuthorList::Authors::const_iterator a_end = params().authors().end();
1418         for (; a_it != a_end; ++a_it)
1419                 a_it->setUsed(false);
1420
1421         ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1422         ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1423         for ( ; it != end; ++it)
1424                 it->checkAuthors(params().authors());
1425
1426         // now write out the buffer parameters.
1427         ofs << "\\begin_header\n";
1428         params().writeFile(ofs);
1429         ofs << "\\end_header\n";
1430
1431         // write the text
1432         ofs << "\n\\begin_body\n";
1433         text().write(ofs);
1434         ofs << "\n\\end_body\n";
1435
1436         // Write marker that shows file is complete
1437         ofs << "\\end_document" << endl;
1438
1439         // Shouldn't really be needed....
1440         //ofs.close();
1441
1442         // how to check if close went ok?
1443         // Following is an attempt... (BE 20001011)
1444
1445         // good() returns false if any error occured, including some
1446         //        formatting error.
1447         // bad()  returns true if something bad happened in the buffer,
1448         //        which should include file system full errors.
1449
1450         bool status = true;
1451         if (!ofs) {
1452                 status = false;
1453                 lyxerr << "File was not closed properly." << endl;
1454         }
1455
1456         return status;
1457 }
1458
1459
1460 bool Buffer::makeLaTeXFile(FileName const & fname,
1461                            string const & original_path,
1462                            OutputParams const & runparams_in,
1463                            OutputWhat output) const
1464 {
1465         OutputParams runparams = runparams_in;
1466
1467         // This is necessary for LuaTeX/XeTeX with tex fonts.
1468         // See FIXME in BufferParams::encoding()
1469         if (runparams.isFullUnicode())
1470                 runparams.encoding = encodings.fromLyXName("utf8-plain");
1471
1472         string const encoding = runparams.encoding->iconvName();
1473         LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1474
1475         ofdocstream ofs;
1476         try { ofs.reset(encoding); }
1477         catch (iconv_codecvt_facet_exception const & e) {
1478                 lyxerr << "Caught iconv exception: " << e.what() << endl;
1479                 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1480                         "verify that the support software for your encoding (%1$s) is "
1481                         "properly installed"), from_ascii(encoding)));
1482                 return false;
1483         }
1484         if (!openFileWrite(ofs, fname))
1485                 return false;
1486
1487         //TexStream ts(ofs.rdbuf(), &texrow());
1488         ErrorList & errorList = d->errorLists["Export"];
1489         errorList.clear();
1490         bool failed_export = false;
1491         otexstream os(ofs, d->texrow);
1492
1493         // make sure we are ready to export
1494         // this needs to be done before we validate
1495         // FIXME Do we need to do this all the time? I.e., in children
1496         // of a master we are exporting?
1497         updateBuffer();
1498         updateMacroInstances(OutputUpdate);
1499
1500         try {
1501                 os.texrow().reset();
1502                 writeLaTeXSource(os, original_path, runparams, output);
1503         }
1504         catch (EncodingException const & e) {
1505                 odocstringstream ods;
1506                 ods.put(e.failed_char);
1507                 ostringstream oss;
1508                 oss << "0x" << hex << e.failed_char << dec;
1509                 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1510                                           " (code point %2$s)"),
1511                                           ods.str(), from_utf8(oss.str()));
1512                 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1513                                 "representable in the chosen encoding.\n"
1514                                 "Changing the document encoding to utf8 could help."),
1515                                 e.par_id, e.pos, e.pos + 1));
1516                 failed_export = true;
1517         }
1518         catch (iconv_codecvt_facet_exception const & e) {
1519                 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1520                         _(e.what()), -1, 0, 0));
1521                 failed_export = true;
1522         }
1523         catch (exception const & e) {
1524                 errorList.push_back(ErrorItem(_("conversion failed"),
1525                         _(e.what()), -1, 0, 0));
1526                 failed_export = true;
1527         }
1528         catch (...) {
1529                 lyxerr << "Caught some really weird exception..." << endl;
1530                 lyx_exit(1);
1531         }
1532
1533         ofs.close();
1534         if (ofs.fail()) {
1535                 failed_export = true;
1536                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1537         }
1538
1539         errors("Export");
1540         return !failed_export;
1541 }
1542
1543
1544 void Buffer::writeLaTeXSource(otexstream & os,
1545                            string const & original_path,
1546                            OutputParams const & runparams_in,
1547                            OutputWhat output) const
1548 {
1549         // The child documents, if any, shall be already loaded at this point.
1550
1551         OutputParams runparams = runparams_in;
1552
1553         // If we are compiling a file standalone, even if this is the
1554         // child of some other buffer, let's cut the link here, so the
1555         // file is really independent and no concurring settings from
1556         // the master (e.g. branch state) interfere (see #8100).
1557         if (!runparams.is_child)
1558                 d->ignore_parent = true;
1559
1560         // Classify the unicode characters appearing in math insets
1561         Encodings::initUnicodeMath(*this);
1562
1563         // validate the buffer.
1564         LYXERR(Debug::LATEX, "  Validating buffer...");
1565         LaTeXFeatures features(*this, params(), runparams);
1566         validate(features);
1567         // This is only set once per document (in master)
1568         if (!runparams.is_child)
1569                 runparams.use_polyglossia = features.usePolyglossia();
1570         LYXERR(Debug::LATEX, "  Buffer validation done.");
1571
1572         bool const output_preamble =
1573                 output == FullSource || output == OnlyPreamble;
1574         bool const output_body =
1575                 output == FullSource || output == OnlyBody;
1576
1577         // The starting paragraph of the coming rows is the
1578         // first paragraph of the document. (Asger)
1579         if (output_preamble && runparams.nice) {
1580                 os << "%% LyX " << lyx_version << " created this file.  "
1581                         "For more info, see http://www.lyx.org/.\n"
1582                         "%% Do not edit unless you really know what "
1583                         "you are doing.\n";
1584         }
1585         LYXERR(Debug::INFO, "lyx document header finished");
1586
1587         // There are a few differences between nice LaTeX and usual files:
1588         // usual files have \batchmode and special input@path to allow
1589         // inclusion of figures specified by an explicitly relative path
1590         // (i.e., a path starting with './' or '../') with either \input or
1591         // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1592         // input@path is set when the actual parameter original_path is set.
1593         // This is done for usual tex-file, but not for nice-latex-file.
1594         // (Matthias 250696)
1595         // Note that input@path is only needed for something the user does
1596         // in the preamble, included .tex files or ERT, files included by
1597         // LyX work without it.
1598         if (output_preamble) {
1599                 if (!runparams.nice) {
1600                         // code for usual, NOT nice-latex-file
1601                         os << "\\batchmode\n"; // changed from \nonstopmode
1602                 }
1603                 if (!original_path.empty()) {
1604                         // FIXME UNICODE
1605                         // We don't know the encoding of inputpath
1606                         docstring const inputpath = from_utf8(original_path);
1607                         docstring uncodable_glyphs;
1608                         Encoding const * const enc = runparams.encoding;
1609                         if (enc) {
1610                                 for (size_t n = 0; n < inputpath.size(); ++n) {
1611                                         if (!enc->encodable(inputpath[n])) {
1612                                                 docstring const glyph(1, inputpath[n]);
1613                                                 LYXERR0("Uncodable character '"
1614                                                         << glyph
1615                                                         << "' in input path!");
1616                                                 uncodable_glyphs += glyph;
1617                                         }
1618                                 }
1619                         }
1620
1621                         // warn user if we found uncodable glyphs.
1622                         if (!uncodable_glyphs.empty()) {
1623                                 frontend::Alert::warning(
1624                                         _("Uncodable character in file path"),
1625                                         support::bformat(
1626                                           _("The path of your document\n"
1627                                             "(%1$s)\n"
1628                                             "contains glyphs that are unknown "
1629                                             "in the current document encoding "
1630                                             "(namely %2$s). This may result in "
1631                                             "incomplete output, unless "
1632                                             "TEXINPUTS contains the document "
1633                                             "directory and you don't use "
1634                                             "explicitly relative paths (i.e., "
1635                                             "paths starting with './' or "
1636                                             "'../') in the preamble or in ERT."
1637                                             "\n\nIn case of problems, choose "
1638                                             "an appropriate document encoding\n"
1639                                             "(such as utf8) or change the "
1640                                             "file path name."),
1641                                           inputpath, uncodable_glyphs));
1642                         } else {
1643                                 string docdir =
1644                                         support::latex_path(original_path);
1645                                 if (contains(docdir, '#')) {
1646                                         docdir = subst(docdir, "#", "\\#");
1647                                         os << "\\catcode`\\#=11"
1648                                               "\\def\\#{#}\\catcode`\\#=6\n";
1649                                 }
1650                                 if (contains(docdir, '%')) {
1651                                         docdir = subst(docdir, "%", "\\%");
1652                                         os << "\\catcode`\\%=11"
1653                                               "\\def\\%{%}\\catcode`\\%=14\n";
1654                                 }
1655                                 os << "\\makeatletter\n"
1656                                    << "\\def\\input@path{{"
1657                                    << docdir << "/}}\n"
1658                                    << "\\makeatother\n";
1659                         }
1660                 }
1661
1662                 // get parent macros (if this buffer has a parent) which will be
1663                 // written at the document begin further down.
1664                 MacroSet parentMacros;
1665                 listParentMacros(parentMacros, features);
1666
1667                 // Write the preamble
1668                 runparams.use_babel = params().writeLaTeX(os, features,
1669                                                           d->filename.onlyPath());
1670
1671                 // Japanese might be required only in some children of a document,
1672                 // but once required, we must keep use_japanese true.
1673                 runparams.use_japanese |= features.isRequired("japanese");
1674
1675                 if (!output_body) {
1676                         // Restore the parenthood if needed
1677                         if (!runparams.is_child)
1678                                 d->ignore_parent = false;
1679                         return;
1680                 }
1681
1682                 // make the body.
1683                 os << "\\begin{document}\n";
1684
1685                 // output the parent macros
1686                 MacroSet::iterator it = parentMacros.begin();
1687                 MacroSet::iterator end = parentMacros.end();
1688                 for (; it != end; ++it) {
1689                         int num_lines = (*it)->write(os.os(), true);
1690                         os.texrow().newlines(num_lines);
1691                 }
1692
1693         } // output_preamble
1694
1695         os.texrow().start(paragraphs().begin()->id(), 0);
1696
1697         LYXERR(Debug::INFO, "preamble finished, now the body.");
1698
1699         // the real stuff
1700         latexParagraphs(*this, text(), os, runparams);
1701
1702         // Restore the parenthood if needed
1703         if (!runparams.is_child)
1704                 d->ignore_parent = false;
1705
1706         // add this just in case after all the paragraphs
1707         os << endl;
1708
1709         if (output_preamble) {
1710                 os << "\\end{document}\n";
1711                 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1712         } else {
1713                 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1714         }
1715         runparams_in.encoding = runparams.encoding;
1716
1717         // Just to be sure. (Asger)
1718         os.texrow().newline();
1719
1720         //for (int i = 0; i<d->texrow.rows(); i++) {
1721         // int id,pos;
1722         // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1723         //      lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1724         //}
1725
1726         LYXERR(Debug::INFO, "Finished making LaTeX file.");
1727         LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1728 }
1729
1730
1731 void Buffer::makeDocBookFile(FileName const & fname,
1732                               OutputParams const & runparams,
1733                               OutputWhat output) const
1734 {
1735         LYXERR(Debug::LATEX, "makeDocBookFile...");
1736
1737         ofdocstream ofs;
1738         if (!openFileWrite(ofs, fname))
1739                 return;
1740
1741         // make sure we are ready to export
1742         // this needs to be done before we validate
1743         updateBuffer();
1744         updateMacroInstances(OutputUpdate);
1745
1746         writeDocBookSource(ofs, fname.absFileName(), runparams, output);
1747
1748         ofs.close();
1749         if (ofs.fail())
1750                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1751 }
1752
1753
1754 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1755                              OutputParams const & runparams,
1756                              OutputWhat output) const
1757 {
1758         LaTeXFeatures features(*this, params(), runparams);
1759         validate(features);
1760
1761         d->texrow.reset();
1762
1763         DocumentClass const & tclass = params().documentClass();
1764         string const top_element = tclass.latexname();
1765
1766         bool const output_preamble =
1767                 output == FullSource || output == OnlyPreamble;
1768         bool const output_body =
1769           output == FullSource || output == OnlyBody;
1770
1771         if (output_preamble) {
1772                 if (runparams.flavor == OutputParams::XML)
1773                         os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1774
1775                 // FIXME UNICODE
1776                 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1777
1778                 // FIXME UNICODE
1779                 if (! tclass.class_header().empty())
1780                         os << from_ascii(tclass.class_header());
1781                 else if (runparams.flavor == OutputParams::XML)
1782                         os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1783                             << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1784                 else
1785                         os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1786
1787                 docstring preamble = from_utf8(params().preamble);
1788                 if (runparams.flavor != OutputParams::XML ) {
1789                         preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1790                         preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1791                         preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1792                         preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1793                 }
1794
1795                 string const name = runparams.nice
1796                         ? changeExtension(absFileName(), ".sgml") : fname;
1797                 preamble += features.getIncludedFiles(name);
1798                 preamble += features.getLyXSGMLEntities();
1799
1800                 if (!preamble.empty()) {
1801                         os << "\n [ " << preamble << " ]";
1802                 }
1803                 os << ">\n\n";
1804         }
1805
1806         if (output_body) {
1807                 string top = top_element;
1808                 top += " lang=\"";
1809                 if (runparams.flavor == OutputParams::XML)
1810                         top += params().language->code();
1811                 else
1812                         top += params().language->code().substr(0, 2);
1813                 top += '"';
1814
1815                 if (!params().options.empty()) {
1816                         top += ' ';
1817                         top += params().options;
1818                 }
1819
1820                 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1821                                 << " file was created by LyX " << lyx_version
1822                                 << "\n  See http://www.lyx.org/ for more information -->\n";
1823
1824                 params().documentClass().counters().reset();
1825
1826                 sgml::openTag(os, top);
1827                 os << '\n';
1828                 docbookParagraphs(text(), *this, os, runparams);
1829                 sgml::closeTag(os, top_element);
1830         }
1831 }
1832
1833
1834 void Buffer::makeLyXHTMLFile(FileName const & fname,
1835                               OutputParams const & runparams) const
1836 {
1837         LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1838
1839         ofdocstream ofs;
1840         if (!openFileWrite(ofs, fname))
1841                 return;
1842
1843         // make sure we are ready to export
1844         // this has to be done before we validate
1845         updateBuffer(UpdateMaster, OutputUpdate);
1846         updateMacroInstances(OutputUpdate);
1847
1848         writeLyXHTMLSource(ofs, runparams, FullSource);
1849
1850         ofs.close();
1851         if (ofs.fail())
1852                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1853 }
1854
1855
1856 void Buffer::writeLyXHTMLSource(odocstream & os,
1857                              OutputParams const & runparams,
1858                              OutputWhat output) const
1859 {
1860         LaTeXFeatures features(*this, params(), runparams);
1861         validate(features);
1862         d->bibinfo_.makeCitationLabels(*this);
1863
1864         bool const output_preamble =
1865                 output == FullSource || output == OnlyPreamble;
1866         bool const output_body =
1867           output == FullSource || output == OnlyBody || output == IncludedFile;
1868
1869         if (output_preamble) {
1870                 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1871                    << "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN\" \"http://www.w3.org/TR/2001/REC-MathML2-20010221/dtd/xhtml-math11-f.dtd\">\n"
1872                    // FIXME Language should be set properly.
1873                    << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1874                    << "<head>\n"
1875                    << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1876                    // FIXME Presumably need to set this right
1877                    << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1878
1879                 docstring const & doctitle = features.htmlTitle();
1880                 os << "<title>"
1881                    << (doctitle.empty() ?
1882                          from_ascii("LyX Document") :
1883                          html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
1884                    << "</title>\n";
1885
1886                 docstring styles = features.getTClassHTMLPreamble();
1887                 if (!styles.empty())
1888                         os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
1889
1890                 styles = from_utf8(features.getPreambleSnippets());
1891                 if (!styles.empty())
1892                         os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
1893
1894                 // we will collect CSS information in a stream, and then output it
1895                 // either here, as part of the header, or else in a separate file.
1896                 odocstringstream css;
1897                 styles = from_utf8(features.getCSSSnippets());
1898                 if (!styles.empty())
1899                         css << "/* LyX Provided Styles */\n" << styles << '\n';
1900
1901                 styles = features.getTClassHTMLStyles();
1902                 if (!styles.empty())
1903                         css << "/* Layout-provided Styles */\n" << styles << '\n';
1904
1905                 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
1906                 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
1907                 if (needfg || needbg) {
1908                                 css << "\nbody {\n";
1909                                 if (needfg)
1910                                    css << "  color: "
1911                                             << from_ascii(X11hexname(params().fontcolor))
1912                                             << ";\n";
1913                                 if (needbg)
1914                                    css << "  background-color: "
1915                                             << from_ascii(X11hexname(params().backgroundcolor))
1916                                             << ";\n";
1917                                 css << "}\n";
1918                 }
1919                 
1920                 docstring const dstyles = css.str();
1921                 if (!dstyles.empty()) {
1922                         bool written = false;
1923                         if (params().html_css_as_file) {
1924                                 // open a file for CSS info
1925                                 ofdocstream ocss;
1926                                 string const fcssname = addName(temppath(), "docstyle.css");
1927                                 FileName const fcssfile = FileName(fcssname);
1928                                 if (openFileWrite(ocss, fcssfile)) {
1929                                         ocss << dstyles;
1930                                         ocss.close();
1931                                         written = true;
1932                                         // write link to header
1933                                         os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
1934                                         // register file
1935                                         runparams.exportdata->addExternalFile("xhtml", fcssfile);
1936                                 }
1937                         }
1938                         // we are here if the CSS is supposed to be written to the header
1939                         // or if we failed to write it to an external file.
1940                         if (!written) {
1941                                 os << "<style type='text/css'>\n"
1942                                          << dstyles
1943                                          << "\n</style>\n";
1944                         }
1945                 }
1946                 os << "</head>\n";
1947         }
1948
1949         if (output_body) {
1950                 bool const output_body_tag = (output != IncludedFile);
1951                 if (output_body_tag)
1952                         os << "<body>\n";
1953                 XHTMLStream xs(os);
1954                 if (output != IncludedFile)
1955                         // if we're an included file, the counters are in the master.
1956                         params().documentClass().counters().reset();
1957                 xhtmlParagraphs(text(), *this, xs, runparams);
1958                 if (output_body_tag)
1959                         os << "</body>\n";
1960         }
1961
1962         if (output_preamble)
1963                 os << "</html>\n";
1964 }
1965
1966
1967 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1968 // Other flags: -wall -v0 -x
1969 int Buffer::runChktex()
1970 {
1971         setBusy(true);
1972
1973         // get LaTeX-Filename
1974         FileName const path(temppath());
1975         string const name = addName(path.absFileName(), latexName());
1976         string const org_path = filePath();
1977
1978         PathChanger p(path); // path to LaTeX file
1979         message(_("Running chktex..."));
1980
1981         // Generate the LaTeX file if neccessary
1982         OutputParams runparams(&params().encoding());
1983         runparams.flavor = OutputParams::LATEX;
1984         runparams.nice = false;
1985         runparams.linelen = lyxrc.plaintext_linelen;
1986         makeLaTeXFile(FileName(name), org_path, runparams);
1987
1988         TeXErrors terr;
1989         Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
1990         int const res = chktex.run(terr); // run chktex
1991
1992         if (res == -1) {
1993                 Alert::error(_("chktex failure"),
1994                              _("Could not run chktex successfully."));
1995         } else {
1996                 ErrorList & errlist = d->errorLists["ChkTeX"];
1997                 errlist.clear();
1998                 bufferErrors(terr, errlist);
1999         }
2000
2001         setBusy(false);
2002
2003         errors("ChkTeX");
2004
2005         return res;
2006 }
2007
2008
2009 void Buffer::validate(LaTeXFeatures & features) const
2010 {
2011         // Validate the buffer params, but not for included
2012         // files, since they also use the parent buffer's
2013         // params (# 5941)
2014         if (!features.runparams().is_child)
2015                 params().validate(features);
2016
2017         for_each(paragraphs().begin(), paragraphs().end(),
2018                  bind(&Paragraph::validate, _1, ref(features)));
2019
2020         if (lyxerr.debugging(Debug::LATEX)) {
2021                 features.showStruct();
2022         }
2023 }
2024
2025
2026 void Buffer::getLabelList(vector<docstring> & list) const
2027 {
2028         // If this is a child document, use the master's list instead.
2029         if (parent()) {
2030                 masterBuffer()->getLabelList(list);
2031                 return;
2032         }
2033
2034         list.clear();
2035         Toc & toc = d->toc_backend.toc("label");
2036         TocIterator toc_it = toc.begin();
2037         TocIterator end = toc.end();
2038         for (; toc_it != end; ++toc_it) {
2039                 if (toc_it->depth() == 0)
2040                         list.push_back(toc_it->str());
2041         }
2042 }
2043
2044
2045 void Buffer::updateBibfilesCache(UpdateScope scope) const
2046 {
2047         // FIXME This is probably unnecssary, given where we call this.
2048         // If this is a child document, use the parent's cache instead.
2049         if (parent() && scope != UpdateChildOnly) {
2050                 masterBuffer()->updateBibfilesCache();
2051                 return;
2052         }
2053
2054         d->bibfiles_cache_.clear();
2055         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2056                 if (it->lyxCode() == BIBTEX_CODE) {
2057                         InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
2058                         support::FileNameList const bibfiles = inset.getBibFiles();
2059                         d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2060                                 bibfiles.begin(),
2061                                 bibfiles.end());
2062                 } else if (it->lyxCode() == INCLUDE_CODE) {
2063                         InsetInclude & inset = static_cast<InsetInclude &>(*it);
2064                         Buffer const * const incbuf = inset.getChildBuffer();
2065                         if (!incbuf)
2066                                 continue;
2067                         support::FileNameList const & bibfiles =
2068                                         incbuf->getBibfilesCache(UpdateChildOnly);
2069                         if (!bibfiles.empty()) {
2070                                 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2071                                         bibfiles.begin(),
2072                                         bibfiles.end());
2073                         }
2074                 }
2075         }
2076         d->bibfile_cache_valid_ = true;
2077         d->bibinfo_cache_valid_ = false;
2078         d->cite_labels_valid_ = false;
2079 }
2080
2081
2082 void Buffer::invalidateBibinfoCache() const
2083 {
2084         d->bibinfo_cache_valid_ = false;
2085         d->cite_labels_valid_ = false;
2086         // also invalidate the cache for the parent buffer
2087         Buffer const * const pbuf = d->parent();
2088         if (pbuf)
2089                 pbuf->invalidateBibinfoCache();
2090 }
2091
2092
2093 void Buffer::invalidateBibfileCache() const
2094 {
2095         d->bibfile_cache_valid_ = false;
2096         d->bibinfo_cache_valid_ = false;
2097         d->cite_labels_valid_ = false;
2098         // also invalidate the cache for the parent buffer
2099         Buffer const * const pbuf = d->parent();
2100         if (pbuf)
2101                 pbuf->invalidateBibfileCache();
2102 }
2103
2104
2105 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
2106 {
2107         // FIXME This is probably unnecessary, given where we call this.
2108         // If this is a child document, use the master's cache instead.
2109         Buffer const * const pbuf = masterBuffer();
2110         if (pbuf != this && scope != UpdateChildOnly)
2111                 return pbuf->getBibfilesCache();
2112
2113         if (!d->bibfile_cache_valid_)
2114                 this->updateBibfilesCache(scope);
2115
2116         return d->bibfiles_cache_;
2117 }
2118
2119
2120 BiblioInfo const & Buffer::masterBibInfo() const
2121 {
2122         Buffer const * const tmp = masterBuffer();
2123         if (tmp != this)
2124                 return tmp->masterBibInfo();
2125         return d->bibinfo_;
2126 }
2127
2128
2129 void Buffer::checkIfBibInfoCacheIsValid() const
2130 {
2131         // use the master's cache
2132         Buffer const * const tmp = masterBuffer();
2133         if (tmp != this) {
2134                 tmp->checkIfBibInfoCacheIsValid();
2135                 return;
2136         }
2137
2138         // compare the cached timestamps with the actual ones.
2139         FileNameList const & bibfiles_cache = getBibfilesCache();
2140         FileNameList::const_iterator ei = bibfiles_cache.begin();
2141         FileNameList::const_iterator en = bibfiles_cache.end();
2142         for (; ei != en; ++ ei) {
2143                 time_t lastw = ei->lastModified();
2144                 time_t prevw = d->bibfile_status_[*ei];
2145                 if (lastw != prevw) {
2146                         d->bibinfo_cache_valid_ = false;
2147                         d->cite_labels_valid_ = false;
2148                         d->bibfile_status_[*ei] = lastw;
2149                 }
2150         }
2151 }
2152
2153
2154 void Buffer::reloadBibInfoCache() const
2155 {
2156         // use the master's cache
2157         Buffer const * const tmp = masterBuffer();
2158         if (tmp != this) {
2159                 tmp->reloadBibInfoCache();
2160                 return;
2161         }
2162
2163         checkIfBibInfoCacheIsValid();
2164         if (d->bibinfo_cache_valid_)
2165                 return;
2166
2167         d->bibinfo_.clear();
2168         collectBibKeys();
2169         d->bibinfo_cache_valid_ = true;
2170 }
2171
2172
2173 void Buffer::collectBibKeys() const
2174 {
2175         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2176                 it->collectBibKeys(it);
2177 }
2178
2179
2180 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
2181 {
2182         Buffer const * tmp = masterBuffer();
2183         BiblioInfo & masterbi = (tmp == this) ?
2184                 d->bibinfo_ : tmp->d->bibinfo_;
2185         masterbi.mergeBiblioInfo(bi);
2186 }
2187
2188
2189 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
2190 {
2191         Buffer const * tmp = masterBuffer();
2192         BiblioInfo & masterbi = (tmp == this) ?
2193                 d->bibinfo_ : tmp->d->bibinfo_;
2194         masterbi[key] = bi;
2195 }
2196
2197
2198 void Buffer::makeCitationLabels() const
2199 {
2200         Buffer const * const master = masterBuffer();
2201         return d->bibinfo_.makeCitationLabels(*master);
2202 }
2203
2204
2205 bool Buffer::citeLabelsValid() const
2206 {
2207         return masterBuffer()->d->cite_labels_valid_;
2208 }
2209
2210
2211 void Buffer::removeBiblioTempFiles() const
2212 {
2213         // We remove files that contain LaTeX commands specific to the
2214         // particular bibliographic style being used, in order to avoid
2215         // LaTeX errors when we switch style.
2216         FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2217         FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2218         LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2219         aux_file.removeFile();
2220         LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2221         bbl_file.removeFile();
2222         // Also for the parent buffer
2223         Buffer const * const pbuf = parent();
2224         if (pbuf)
2225                 pbuf->removeBiblioTempFiles();
2226 }
2227
2228
2229 bool Buffer::isDepClean(string const & name) const
2230 {
2231         DepClean::const_iterator const it = d->dep_clean.find(name);
2232         if (it == d->dep_clean.end())
2233                 return true;
2234         return it->second;
2235 }
2236
2237
2238 void Buffer::markDepClean(string const & name)
2239 {
2240         d->dep_clean[name] = true;
2241 }
2242
2243
2244 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2245 {
2246         if (isInternal()) {
2247                 // FIXME? if there is an Buffer LFUN that can be dispatched even
2248                 // if internal, put a switch '(cmd.action)' here.
2249                 return false;
2250         }
2251
2252         bool enable = true;
2253
2254         switch (cmd.action()) {
2255
2256         case LFUN_BUFFER_TOGGLE_READ_ONLY:
2257                 flag.setOnOff(isReadonly());
2258                 break;
2259
2260                 // FIXME: There is need for a command-line import.
2261                 //case LFUN_BUFFER_IMPORT:
2262
2263         case LFUN_BUFFER_AUTO_SAVE:
2264                 break;
2265
2266         case LFUN_BUFFER_EXPORT_CUSTOM:
2267                 // FIXME: Nothing to check here?
2268                 break;
2269
2270         case LFUN_BUFFER_EXPORT: {
2271                 docstring const arg = cmd.argument();
2272                 if (arg == "custom") {
2273                         enable = true;
2274                         break;
2275                 }
2276                 string format = to_utf8(arg);
2277                 size_t pos = format.find(' ');
2278                 if (pos != string::npos)
2279                         format = format.substr(0, pos);
2280                 enable = params().isExportable(format);
2281                 if (!enable)
2282                         flag.message(bformat(
2283                                              _("Don't know how to export to format: %1$s"), arg));
2284                 break;
2285         }
2286
2287         case LFUN_BUFFER_CHKTEX:
2288                 enable = params().isLatex() && !lyxrc.chktex_command.empty();
2289                 break;
2290
2291         case LFUN_BUILD_PROGRAM:
2292                 enable = params().isExportable("program");
2293                 break;
2294
2295         case LFUN_BRANCH_ACTIVATE:
2296         case LFUN_BRANCH_DEACTIVATE:
2297         case LFUN_BRANCH_MASTER_ACTIVATE:
2298         case LFUN_BRANCH_MASTER_DEACTIVATE: {
2299                 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2300                                      || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2301                 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2302                         : params().branchlist();
2303                 docstring const branchName = cmd.argument();
2304                 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2305                 break;
2306         }
2307
2308         case LFUN_BRANCH_ADD:
2309         case LFUN_BRANCHES_RENAME:
2310         case LFUN_BUFFER_PRINT:
2311                 // if no Buffer is present, then of course we won't be called!
2312                 break;
2313
2314         case LFUN_BUFFER_LANGUAGE:
2315                 enable = !isReadonly();
2316                 break;
2317
2318         default:
2319                 return false;
2320         }
2321         flag.setEnabled(enable);
2322         return true;
2323 }
2324
2325
2326 void Buffer::dispatch(string const & command, DispatchResult & result)
2327 {
2328         return dispatch(lyxaction.lookupFunc(command), result);
2329 }
2330
2331
2332 // NOTE We can end up here even if we have no GUI, because we are called
2333 // by LyX::exec to handled command-line requests. So we may need to check
2334 // whether we have a GUI or not. The boolean use_gui holds this information.
2335 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2336 {
2337         if (isInternal()) {
2338                 // FIXME? if there is an Buffer LFUN that can be dispatched even
2339                 // if internal, put a switch '(cmd.action())' here.
2340                 dr.dispatched(false);
2341                 return;
2342         }
2343         string const argument = to_utf8(func.argument());
2344         // We'll set this back to false if need be.
2345         bool dispatched = true;
2346         undo().beginUndoGroup();
2347
2348         switch (func.action()) {
2349         case LFUN_BUFFER_TOGGLE_READ_ONLY:
2350                 if (lyxvc().inUse()) {
2351                         string log = lyxvc().toggleReadOnly();
2352                         if (!log.empty())
2353                                 dr.setMessage(log);
2354                 }
2355                 else
2356                         setReadonly(!isReadonly());
2357                 break;
2358
2359         case LFUN_BUFFER_EXPORT: {
2360                 ExportStatus const status = doExport(argument, false);
2361                 dr.setError(status != ExportSuccess);
2362                 if (status != ExportSuccess)
2363                         dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2364                                               func.argument()));
2365                 break;
2366         }
2367
2368         case LFUN_BUILD_PROGRAM:
2369                 doExport("program", true);
2370                 break;
2371
2372         case LFUN_BUFFER_CHKTEX:
2373                 runChktex();
2374                 break;
2375
2376         case LFUN_BUFFER_EXPORT_CUSTOM: {
2377                 string format_name;
2378                 string command = split(argument, format_name, ' ');
2379                 Format const * format = formats.getFormat(format_name);
2380                 if (!format) {
2381                         lyxerr << "Format \"" << format_name
2382                                 << "\" not recognized!"
2383                                 << endl;
2384                         break;
2385                 }
2386
2387                 // The name of the file created by the conversion process
2388                 string filename;
2389
2390                 // Output to filename
2391                 if (format->name() == "lyx") {
2392                         string const latexname = latexName(false);
2393                         filename = changeExtension(latexname,
2394                                 format->extension());
2395                         filename = addName(temppath(), filename);
2396
2397                         if (!writeFile(FileName(filename)))
2398                                 break;
2399
2400                 } else {
2401                         doExport(format_name, true, filename);
2402                 }
2403
2404                 // Substitute $$FName for filename
2405                 if (!contains(command, "$$FName"))
2406                         command = "( " + command + " ) < $$FName";
2407                 command = subst(command, "$$FName", filename);
2408
2409                 // Execute the command in the background
2410                 Systemcall call;
2411                 call.startscript(Systemcall::DontWait, command, filePath());
2412                 break;
2413         }
2414
2415         // FIXME: There is need for a command-line import.
2416         /*
2417         case LFUN_BUFFER_IMPORT:
2418                 doImport(argument);
2419                 break;
2420         */
2421
2422         case LFUN_BUFFER_AUTO_SAVE:
2423                 autoSave();
2424                 resetAutosaveTimers();
2425                 break;
2426
2427         case LFUN_BRANCH_ACTIVATE:
2428         case LFUN_BRANCH_DEACTIVATE:
2429         case LFUN_BRANCH_MASTER_ACTIVATE:
2430         case LFUN_BRANCH_MASTER_DEACTIVATE: {
2431                 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2432                                      || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2433                 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2434                                       : this;
2435
2436                 docstring const branch_name = func.argument();
2437                 // the case without a branch name is handled elsewhere
2438                 if (branch_name.empty()) {
2439                         dispatched = false;
2440                         break;
2441                 }
2442                 Branch * branch = buf->params().branchlist().find(branch_name);
2443                 if (!branch) {
2444                         LYXERR0("Branch " << branch_name << " does not exist.");
2445                         dr.setError(true);
2446                         docstring const msg =
2447                                 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2448                         dr.setMessage(msg);
2449                         break;
2450                 }
2451                 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2452                                        || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2453                 if (branch->isSelected() != activate) {
2454                         buf->undo().recordUndoFullDocument(CursorData());
2455                         branch->setSelected(activate);
2456                         dr.setError(false);
2457                         dr.screenUpdate(Update::Force);
2458                         dr.forceBufferUpdate();
2459                 }
2460                 break;
2461         }
2462
2463         case LFUN_BRANCH_ADD: {
2464                 docstring branch_name = func.argument();
2465                 if (branch_name.empty()) {
2466                         dispatched = false;
2467                         break;
2468                 }
2469                 BranchList & branch_list = params().branchlist();
2470                 vector<docstring> const branches =
2471                         getVectorFromString(branch_name, branch_list.separator());
2472                 docstring msg;
2473                 for (vector<docstring>::const_iterator it = branches.begin();
2474                      it != branches.end(); ++it) {
2475                         branch_name = *it;
2476                         Branch * branch = branch_list.find(branch_name);
2477                         if (branch) {
2478                                 LYXERR0("Branch " << branch_name << " already exists.");
2479                                 dr.setError(true);
2480                                 if (!msg.empty())
2481                                         msg += ("\n");
2482                                 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2483                         } else {
2484                                 branch_list.add(branch_name);
2485                                 branch = branch_list.find(branch_name);
2486                                 string const x11hexname = X11hexname(branch->color());
2487                                 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2488                                 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2489                                 dr.setError(false);
2490                                 dr.screenUpdate(Update::Force);
2491                         }
2492                 }
2493                 if (!msg.empty())
2494                         dr.setMessage(msg);
2495                 break;
2496         }
2497
2498         case LFUN_BRANCHES_RENAME: {
2499                 if (func.argument().empty())
2500                         break;
2501
2502                 docstring const oldname = from_utf8(func.getArg(0));
2503                 docstring const newname = from_utf8(func.getArg(1));
2504                 InsetIterator it  = inset_iterator_begin(inset());
2505                 InsetIterator const end = inset_iterator_end(inset());
2506                 bool success = false;
2507                 for (; it != end; ++it) {
2508                         if (it->lyxCode() == BRANCH_CODE) {
2509                                 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2510                                 if (ins.branch() == oldname) {
2511                                         undo().recordUndo(CursorData(it));
2512                                         ins.rename(newname);
2513                                         success = true;
2514                                         continue;
2515                                 }
2516                         }
2517                         if (it->lyxCode() == INCLUDE_CODE) {
2518                                 // get buffer of external file
2519                                 InsetInclude const & ins =
2520                                         static_cast<InsetInclude const &>(*it);
2521                                 Buffer * child = ins.getChildBuffer();
2522                                 if (!child)
2523                                         continue;
2524                                 child->dispatch(func, dr);
2525                         }
2526                 }
2527
2528                 if (success) {
2529                         dr.screenUpdate(Update::Force);
2530                         dr.forceBufferUpdate();
2531                 }
2532                 break;
2533         }
2534
2535         case LFUN_BUFFER_PRINT: {
2536                 // we'll assume there's a problem until we succeed
2537                 dr.setError(true);
2538                 string target = func.getArg(0);
2539                 string target_name = func.getArg(1);
2540                 string command = func.getArg(2);
2541
2542                 if (target.empty()
2543                     || target_name.empty()
2544                     || command.empty()) {
2545                         LYXERR0("Unable to parse " << func.argument());
2546                         docstring const msg =
2547                                 bformat(_("Unable to parse \"%1$s\""), func.argument());
2548                         dr.setMessage(msg);
2549                         break;
2550                 }
2551                 if (target != "printer" && target != "file") {
2552                         LYXERR0("Unrecognized target \"" << target << '"');
2553                         docstring const msg =
2554                                 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2555                         dr.setMessage(msg);
2556                         break;
2557                 }
2558
2559                 if (!doExport("dvi", true)) {
2560                         showPrintError(absFileName());
2561                         dr.setMessage(_("Error exporting to DVI."));
2562                         break;
2563                 }
2564
2565                 // Push directory path.
2566                 string const path = temppath();
2567                 // Prevent the compiler from optimizing away p
2568                 FileName pp(path);
2569                 PathChanger p(pp);
2570
2571                 // there are three cases here:
2572                 // 1. we print to a file
2573                 // 2. we print directly to a printer
2574                 // 3. we print using a spool command (print to file first)
2575                 Systemcall one;
2576                 int res = 0;
2577                 string const dviname = changeExtension(latexName(true), "dvi");
2578
2579                 if (target == "printer") {
2580                         if (!lyxrc.print_spool_command.empty()) {
2581                                 // case 3: print using a spool
2582                                 string const psname = changeExtension(dviname,".ps");
2583                                 command += ' ' + lyxrc.print_to_file
2584                                         + quoteName(psname)
2585                                         + ' '
2586                                         + quoteName(dviname);
2587
2588                                 string command2 = lyxrc.print_spool_command + ' ';
2589                                 if (target_name != "default") {
2590                                         command2 += lyxrc.print_spool_printerprefix
2591                                                 + target_name
2592                                                 + ' ';
2593                                 }
2594                                 command2 += quoteName(psname);
2595                                 // First run dvips.
2596                                 // If successful, then spool command
2597                                 res = one.startscript(Systemcall::Wait, command,
2598                                                       filePath());
2599
2600                                 if (res == 0) {
2601                                         // If there's no GUI, we have to wait on this command. Otherwise,
2602                                         // LyX deletes the temporary directory, and with it the spooled
2603                                         // file, before it can be printed!!
2604                                         Systemcall::Starttype stype = use_gui ?
2605                                                 Systemcall::DontWait : Systemcall::Wait;
2606                                         res = one.startscript(stype, command2,
2607                                                               filePath());
2608                                 }
2609                         } else {
2610                                 // case 2: print directly to a printer
2611                                 if (target_name != "default")
2612                                         command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2613                                 // as above....
2614                                 Systemcall::Starttype stype = use_gui ?
2615                                         Systemcall::DontWait : Systemcall::Wait;
2616                                 res = one.startscript(stype, command +
2617                                                 quoteName(dviname), filePath());
2618                         }
2619
2620                 } else {
2621                         // case 1: print to a file
2622                         FileName const filename(makeAbsPath(target_name, filePath()));
2623                         FileName const dvifile(makeAbsPath(dviname, path));
2624                         if (filename.exists()) {
2625                                 docstring text = bformat(
2626                                         _("The file %1$s already exists.\n\n"
2627                                           "Do you want to overwrite that file?"),
2628                                         makeDisplayPath(filename.absFileName()));
2629                                 if (Alert::prompt(_("Overwrite file?"),
2630                                                   text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2631                                         break;
2632                         }
2633                         command += ' ' + lyxrc.print_to_file
2634                                 + quoteName(filename.toFilesystemEncoding())
2635                                 + ' '
2636                                 + quoteName(dvifile.toFilesystemEncoding());
2637                         // as above....
2638                         Systemcall::Starttype stype = use_gui ?
2639                                 Systemcall::DontWait : Systemcall::Wait;
2640                         res = one.startscript(stype, command, filePath());
2641                 }
2642
2643                 if (res == 0)
2644                         dr.setError(false);
2645                 else {
2646                         dr.setMessage(_("Error running external commands."));
2647                         showPrintError(absFileName());
2648                 }
2649                 break;
2650         }
2651
2652         default:
2653                 dispatched = false;
2654                 break;
2655         }
2656         dr.dispatched(dispatched);
2657         undo().endUndoGroup();
2658 }
2659
2660
2661 void Buffer::changeLanguage(Language const * from, Language const * to)
2662 {
2663         LASSERT(from, return);
2664         LASSERT(to, return);
2665
2666         for_each(par_iterator_begin(),
2667                  par_iterator_end(),
2668                  bind(&Paragraph::changeLanguage, _1, params(), from, to));
2669 }
2670
2671
2672 bool Buffer::isMultiLingual() const
2673 {
2674         ParConstIterator end = par_iterator_end();
2675         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2676                 if (it->isMultiLingual(params()))
2677                         return true;
2678
2679         return false;
2680 }
2681
2682
2683 std::set<Language const *> Buffer::getLanguages() const
2684 {
2685         std::set<Language const *> languages;
2686         getLanguages(languages);
2687         return languages;
2688 }
2689
2690
2691 void Buffer::getLanguages(std::set<Language const *> & languages) const
2692 {
2693         ParConstIterator end = par_iterator_end();
2694         // add the buffer language, even if it's not actively used
2695         languages.insert(language());
2696         // iterate over the paragraphs
2697         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2698                 it->getLanguages(languages);
2699         // also children
2700         ListOfBuffers clist = getDescendents();
2701         ListOfBuffers::const_iterator cit = clist.begin();
2702         ListOfBuffers::const_iterator const cen = clist.end();
2703         for (; cit != cen; ++cit)
2704                 (*cit)->getLanguages(languages);
2705 }
2706
2707
2708 DocIterator Buffer::getParFromID(int const id) const
2709 {
2710         Buffer * buf = const_cast<Buffer *>(this);
2711         if (id < 0) {
2712                 // John says this is called with id == -1 from undo
2713                 lyxerr << "getParFromID(), id: " << id << endl;
2714                 return doc_iterator_end(buf);
2715         }
2716
2717         for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2718                 if (it.paragraph().id() == id)
2719                         return it;
2720
2721         return doc_iterator_end(buf);
2722 }
2723
2724
2725 bool Buffer::hasParWithID(int const id) const
2726 {
2727         return !getParFromID(id).atEnd();
2728 }
2729
2730
2731 ParIterator Buffer::par_iterator_begin()
2732 {
2733         return ParIterator(doc_iterator_begin(this));
2734 }
2735
2736
2737 ParIterator Buffer::par_iterator_end()
2738 {
2739         return ParIterator(doc_iterator_end(this));
2740 }
2741
2742
2743 ParConstIterator Buffer::par_iterator_begin() const
2744 {
2745         return ParConstIterator(doc_iterator_begin(this));
2746 }
2747
2748
2749 ParConstIterator Buffer::par_iterator_end() const
2750 {
2751         return ParConstIterator(doc_iterator_end(this));
2752 }
2753
2754
2755 Language const * Buffer::language() const
2756 {
2757         return params().language;
2758 }
2759
2760
2761 docstring const Buffer::B_(string const & l10n) const
2762 {
2763         return params().B_(l10n);
2764 }
2765
2766
2767 bool Buffer::isClean() const
2768 {
2769         return d->lyx_clean;
2770 }
2771
2772
2773 bool Buffer::isExternallyModified(CheckMethod method) const
2774 {
2775         LASSERT(d->filename.exists(), return false);
2776         // if method == timestamp, check timestamp before checksum
2777         return (method == checksum_method
2778                 || d->timestamp_ != d->filename.lastModified())
2779                 && d->checksum_ != d->filename.checksum();
2780 }
2781
2782
2783 void Buffer::saveCheckSum() const
2784 {
2785         FileName const & file = d->filename;
2786
2787         file.refresh();
2788         if (file.exists()) {
2789                 d->timestamp_ = file.lastModified();
2790                 d->checksum_ = file.checksum();
2791         } else {
2792                 // in the case of save to a new file.
2793                 d->timestamp_ = 0;
2794                 d->checksum_ = 0;
2795         }
2796 }
2797
2798
2799 void Buffer::markClean() const
2800 {
2801         if (!d->lyx_clean) {
2802                 d->lyx_clean = true;
2803                 updateTitles();
2804         }
2805         // if the .lyx file has been saved, we don't need an
2806         // autosave
2807         d->bak_clean = true;
2808         d->undo_.markDirty();
2809 }
2810
2811
2812 void Buffer::setUnnamed(bool flag)
2813 {
2814         d->unnamed = flag;
2815 }
2816
2817
2818 bool Buffer::isUnnamed() const
2819 {
2820         return d->unnamed;
2821 }
2822
2823
2824 /// \note
2825 /// Don't check unnamed, here: isInternal() is used in
2826 /// newBuffer(), where the unnamed flag has not been set by anyone
2827 /// yet. Also, for an internal buffer, there should be no need for
2828 /// retrieving fileName() nor for checking if it is unnamed or not.
2829 bool Buffer::isInternal() const
2830 {
2831         return d->internal_buffer;
2832 }
2833
2834
2835 void Buffer::setInternal(bool flag)
2836 {
2837         d->internal_buffer = flag;
2838 }
2839
2840
2841 void Buffer::markDirty()
2842 {
2843         if (d->lyx_clean) {
2844                 d->lyx_clean = false;
2845                 updateTitles();
2846         }
2847         d->bak_clean = false;
2848
2849         DepClean::iterator it = d->dep_clean.begin();
2850         DepClean::const_iterator const end = d->dep_clean.end();
2851
2852         for (; it != end; ++it)
2853                 it->second = false;
2854 }
2855
2856
2857 FileName Buffer::fileName() const
2858 {
2859         return d->filename;
2860 }
2861
2862
2863 string Buffer::absFileName() const
2864 {
2865         return d->filename.absFileName();
2866 }
2867
2868
2869 string Buffer::filePath() const
2870 {
2871         string const abs = d->filename.onlyPath().absFileName();
2872         if (abs.empty())
2873                 return abs;
2874         int last = abs.length() - 1;
2875
2876         return abs[last] == '/' ? abs : abs + '/';
2877 }
2878
2879
2880 bool Buffer::isReadonly() const
2881 {
2882         return d->read_only;
2883 }
2884
2885
2886 void Buffer::setParent(Buffer const * buffer)
2887 {
2888         // Avoids recursive include.
2889         d->setParent(buffer == this ? 0 : buffer);
2890         updateMacros();
2891 }
2892
2893
2894 Buffer const * Buffer::parent() const
2895 {
2896         return d->parent();
2897 }
2898
2899
2900 ListOfBuffers Buffer::allRelatives() const
2901 {
2902         ListOfBuffers lb = masterBuffer()->getDescendents();
2903         lb.push_front(const_cast<Buffer *>(masterBuffer()));
2904         return lb;
2905 }
2906
2907
2908 Buffer const * Buffer::masterBuffer() const
2909 {
2910         // FIXME Should be make sure we are not in some kind
2911         // of recursive include? A -> B -> A will crash this.
2912         Buffer const * const pbuf = d->parent();
2913         if (!pbuf)
2914                 return this;
2915
2916         return pbuf->masterBuffer();
2917 }
2918
2919
2920 bool Buffer::isChild(Buffer * child) const
2921 {
2922         return d->children_positions.find(child) != d->children_positions.end();
2923 }
2924
2925
2926 DocIterator Buffer::firstChildPosition(Buffer const * child)
2927 {
2928         Impl::BufferPositionMap::iterator it;
2929         it = d->children_positions.find(child);
2930         if (it == d->children_positions.end())
2931                 return DocIterator(this);
2932         return it->second;
2933 }
2934
2935
2936 bool Buffer::hasChildren() const
2937 {
2938         return !d->children_positions.empty();
2939 }
2940
2941
2942 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
2943 {
2944         // loop over children
2945         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2946         Impl::BufferPositionMap::iterator end = d->children_positions.end();
2947         for (; it != end; ++it) {
2948                 Buffer * child = const_cast<Buffer *>(it->first);
2949                 // No duplicates
2950                 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
2951                 if (bit != clist.end())
2952                         continue;
2953                 clist.push_back(child);
2954                 if (grand_children)
2955                         // there might be grandchildren
2956                         child->collectChildren(clist, true);
2957         }
2958 }
2959
2960
2961 ListOfBuffers Buffer::getChildren() const
2962 {
2963         ListOfBuffers v;
2964         collectChildren(v, false);
2965         // Make sure we have not included ourselves.
2966         ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
2967         if (bit != v.end()) {
2968                 LYXERR0("Recursive include detected in `" << fileName() << "'.");
2969                 v.erase(bit);
2970         }
2971         return v;
2972 }
2973
2974
2975 ListOfBuffers Buffer::getDescendents() const
2976 {
2977         ListOfBuffers v;
2978         collectChildren(v, true);
2979         // Make sure we have not included ourselves.
2980         ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
2981         if (bit != v.end()) {
2982                 LYXERR0("Recursive include detected in `" << fileName() << "'.");
2983                 v.erase(bit);
2984         }
2985         return v;
2986 }
2987
2988
2989 template<typename M>
2990 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
2991 {
2992         if (m.empty())
2993                 return m.end();
2994
2995         typename M::const_iterator it = m.lower_bound(x);
2996         if (it == m.begin())
2997                 return m.end();
2998
2999         it--;
3000         return it;
3001 }
3002
3003
3004 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3005                                          DocIterator const & pos) const
3006 {
3007         LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3008
3009         // if paragraphs have no macro context set, pos will be empty
3010         if (pos.empty())
3011                 return 0;
3012
3013         // we haven't found anything yet
3014         DocIterator bestPos = owner_->par_iterator_begin();
3015         MacroData const * bestData = 0;
3016
3017         // find macro definitions for name
3018         NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3019         if (nameIt != macros.end()) {
3020                 // find last definition in front of pos or at pos itself
3021                 PositionScopeMacroMap::const_iterator it
3022                         = greatest_below(nameIt->second, pos);
3023                 if (it != nameIt->second.end()) {
3024                         while (true) {
3025                                 // scope ends behind pos?
3026                                 if (pos < it->second.first) {
3027                                         // Looks good, remember this. If there
3028                                         // is no external macro behind this,
3029                                         // we found the right one already.
3030                                         bestPos = it->first;
3031                                         bestData = &it->second.second;
3032                                         break;
3033                                 }
3034
3035                                 // try previous macro if there is one
3036                                 if (it == nameIt->second.begin())
3037                                         break;
3038                                 --it;
3039                         }
3040                 }
3041         }
3042
3043         // find macros in included files
3044         PositionScopeBufferMap::const_iterator it
3045                 = greatest_below(position_to_children, pos);
3046         if (it == position_to_children.end())
3047                 // no children before
3048                 return bestData;
3049
3050         while (true) {
3051                 // do we know something better (i.e. later) already?
3052                 if (it->first < bestPos )
3053                         break;
3054
3055                 // scope ends behind pos?
3056                 if (pos < it->second.first
3057                         && (cloned_buffer_ ||
3058                             theBufferList().isLoaded(it->second.second))) {
3059                         // look for macro in external file
3060                         macro_lock = true;
3061                         MacroData const * data
3062                                 = it->second.second->getMacro(name, false);
3063                         macro_lock = false;
3064                         if (data) {
3065                                 bestPos = it->first;
3066                                 bestData = data;
3067                                 break;
3068                         }
3069                 }
3070
3071                 // try previous file if there is one
3072                 if (it == position_to_children.begin())
3073                         break;
3074                 --it;
3075         }
3076
3077         // return the best macro we have found
3078         return bestData;
3079 }
3080
3081
3082 MacroData const * Buffer::getMacro(docstring const & name,
3083         DocIterator const & pos, bool global) const
3084 {
3085         if (d->macro_lock)
3086                 return 0;
3087
3088         // query buffer macros
3089         MacroData const * data = d->getBufferMacro(name, pos);
3090         if (data != 0)
3091                 return data;
3092
3093         // If there is a master buffer, query that
3094         Buffer const * const pbuf = d->parent();
3095         if (pbuf) {
3096                 d->macro_lock = true;
3097                 MacroData const * macro = pbuf->getMacro(
3098                         name, *this, false);
3099                 d->macro_lock = false;
3100                 if (macro)
3101                         return macro;
3102         }
3103
3104         if (global) {
3105                 data = MacroTable::globalMacros().get(name);
3106                 if (data != 0)
3107                         return data;
3108         }
3109
3110         return 0;
3111 }
3112
3113
3114 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3115 {
3116         // set scope end behind the last paragraph
3117         DocIterator scope = par_iterator_begin();
3118         scope.pit() = scope.lastpit() + 1;
3119
3120         return getMacro(name, scope, global);
3121 }
3122
3123
3124 MacroData const * Buffer::getMacro(docstring const & name,
3125         Buffer const & child, bool global) const
3126 {
3127         // look where the child buffer is included first
3128         Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3129         if (it == d->children_positions.end())
3130                 return 0;
3131
3132         // check for macros at the inclusion position
3133         return getMacro(name, it->second, global);
3134 }
3135
3136
3137 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3138 {
3139         pit_type const lastpit = it.lastpit();
3140
3141         // look for macros in each paragraph
3142         while (it.pit() <= lastpit) {
3143                 Paragraph & par = it.paragraph();
3144
3145                 // iterate over the insets of the current paragraph
3146                 InsetList const & insets = par.insetList();
3147                 InsetList::const_iterator iit = insets.begin();
3148                 InsetList::const_iterator end = insets.end();
3149                 for (; iit != end; ++iit) {
3150                         it.pos() = iit->pos;
3151
3152                         // is it a nested text inset?
3153                         if (iit->inset->asInsetText()) {
3154                                 // Inset needs its own scope?
3155                                 InsetText const * itext = iit->inset->asInsetText();
3156                                 bool newScope = itext->isMacroScope();
3157
3158                                 // scope which ends just behind the inset
3159                                 DocIterator insetScope = it;
3160                                 ++insetScope.pos();
3161
3162                                 // collect macros in inset
3163                                 it.push_back(CursorSlice(*iit->inset));
3164                                 updateMacros(it, newScope ? insetScope : scope);
3165                                 it.pop_back();
3166                                 continue;
3167                         }
3168
3169                         if (iit->inset->asInsetTabular()) {
3170                                 CursorSlice slice(*iit->inset);
3171                                 size_t const numcells = slice.nargs();
3172                                 for (; slice.idx() < numcells; slice.forwardIdx()) {
3173                                         it.push_back(slice);
3174                                         updateMacros(it, scope);
3175                                         it.pop_back();
3176                                 }
3177                                 continue;
3178                         }
3179
3180                         // is it an external file?
3181                         if (iit->inset->lyxCode() == INCLUDE_CODE) {
3182                                 // get buffer of external file
3183                                 InsetInclude const & inset =
3184                                         static_cast<InsetInclude const &>(*iit->inset);
3185                                 macro_lock = true;
3186                                 Buffer * child = inset.getChildBuffer();
3187                                 macro_lock = false;
3188                                 if (!child)
3189                                         continue;
3190
3191                                 // register its position, but only when it is
3192                                 // included first in the buffer
3193                                 if (children_positions.find(child) ==
3194                                         children_positions.end())
3195                                                 children_positions[child] = it;
3196
3197                                 // register child with its scope
3198                                 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3199                                 continue;
3200                         }
3201
3202                         InsetMath * im = iit->inset->asInsetMath();
3203                         if (doing_export && im)  {
3204                                 InsetMathHull * hull = im->asHullInset();
3205                                 if (hull)
3206                                         hull->recordLocation(it);
3207                         }
3208
3209                         if (iit->inset->lyxCode() != MATHMACRO_CODE)
3210                                 continue;
3211
3212                         // get macro data
3213                         MathMacroTemplate & macroTemplate =
3214                                 *iit->inset->asInsetMath()->asMacroTemplate();
3215                         MacroContext mc(owner_, it);
3216                         macroTemplate.updateToContext(mc);
3217
3218                         // valid?
3219                         bool valid = macroTemplate.validMacro();
3220                         // FIXME: Should be fixNameAndCheckIfValid() in fact,
3221                         // then the BufferView's cursor will be invalid in
3222                         // some cases which leads to crashes.
3223                         if (!valid)
3224                                 continue;
3225
3226                         // register macro
3227                         // FIXME (Abdel), I don't understandt why we pass 'it' here
3228                         // instead of 'macroTemplate' defined above... is this correct?
3229                         macros[macroTemplate.name()][it] =
3230                                 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3231                 }
3232
3233                 // next paragraph
3234                 it.pit()++;
3235                 it.pos() = 0;
3236         }
3237 }
3238
3239
3240 void Buffer::updateMacros() const
3241 {
3242         if (d->macro_lock)
3243                 return;
3244
3245         LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3246
3247         // start with empty table
3248         d->macros.clear();
3249         d->children_positions.clear();
3250         d->position_to_children.clear();
3251
3252         // Iterate over buffer, starting with first paragraph
3253         // The scope must be bigger than any lookup DocIterator
3254         // later. For the global lookup, lastpit+1 is used, hence
3255         // we use lastpit+2 here.
3256         DocIterator it = par_iterator_begin();
3257         DocIterator outerScope = it;
3258         outerScope.pit() = outerScope.lastpit() + 2;
3259         d->updateMacros(it, outerScope);
3260 }
3261
3262
3263 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3264 {
3265         InsetIterator it  = inset_iterator_begin(inset());
3266         InsetIterator const end = inset_iterator_end(inset());
3267         for (; it != end; ++it) {
3268                 if (it->lyxCode() == BRANCH_CODE) {
3269                         InsetBranch & br = static_cast<InsetBranch &>(*it);
3270                         docstring const name = br.branch();
3271                         if (!from_master && !params().branchlist().find(name))
3272                                 result.push_back(name);
3273                         else if (from_master && !masterBuffer()->params().branchlist().find(name))
3274                                 result.push_back(name);
3275                         continue;
3276                 }
3277                 if (it->lyxCode() == INCLUDE_CODE) {
3278                         // get buffer of external file
3279                         InsetInclude const & ins =
3280                                 static_cast<InsetInclude const &>(*it);
3281                         Buffer * child = ins.getChildBuffer();
3282                         if (!child)
3283                                 continue;
3284                         child->getUsedBranches(result, true);
3285                 }
3286         }
3287         // remove duplicates
3288         result.unique();
3289 }
3290
3291
3292 void Buffer::updateMacroInstances(UpdateType utype) const
3293 {
3294         LYXERR(Debug::MACROS, "updateMacroInstances for "
3295                 << d->filename.onlyFileName());
3296         DocIterator it = doc_iterator_begin(this);
3297         it.forwardInset();
3298         DocIterator const end = doc_iterator_end(this);
3299         for (; it != end; it.forwardInset()) {
3300                 // look for MathData cells in InsetMathNest insets
3301                 InsetMath * minset = it.nextInset()->asInsetMath();
3302                 if (!minset)
3303                         continue;
3304
3305                 // update macro in all cells of the InsetMathNest
3306                 DocIterator::idx_type n = minset->nargs();
3307                 MacroContext mc = MacroContext(this, it);
3308                 for (DocIterator::idx_type i = 0; i < n; ++i) {
3309                         MathData & data = minset->cell(i);
3310                         data.updateMacros(0, mc, utype);
3311                 }
3312         }
3313 }
3314
3315
3316 void Buffer::listMacroNames(MacroNameSet & macros) const
3317 {
3318         if (d->macro_lock)
3319                 return;
3320
3321         d->macro_lock = true;
3322
3323         // loop over macro names
3324         Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3325         Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3326         for (; nameIt != nameEnd; ++nameIt)
3327                 macros.insert(nameIt->first);
3328
3329         // loop over children
3330         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3331         Impl::BufferPositionMap::iterator end = d->children_positions.end();
3332         for (; it != end; ++it)
3333                 it->first->listMacroNames(macros);
3334
3335         // call parent
3336         Buffer const * const pbuf = d->parent();
3337         if (pbuf)
3338                 pbuf->listMacroNames(macros);
3339
3340         d->macro_lock = false;
3341 }
3342
3343
3344 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3345 {
3346         Buffer const * const pbuf = d->parent();
3347         if (!pbuf)
3348                 return;
3349
3350         MacroNameSet names;
3351         pbuf->listMacroNames(names);
3352
3353         // resolve macros
3354         MacroNameSet::iterator it = names.begin();
3355         MacroNameSet::iterator end = names.end();
3356         for (; it != end; ++it) {
3357                 // defined?
3358                 MacroData const * data =
3359                 pbuf->getMacro(*it, *this, false);
3360                 if (data) {
3361                         macros.insert(data);
3362
3363                         // we cannot access the original MathMacroTemplate anymore
3364                         // here to calls validate method. So we do its work here manually.
3365                         // FIXME: somehow make the template accessible here.
3366                         if (data->optionals() > 0)
3367                                 features.require("xargs");
3368                 }
3369         }
3370 }
3371
3372
3373 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3374 {
3375         if (d->parent())
3376                 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3377
3378         RefCache::iterator it = d->ref_cache_.find(label);
3379         if (it != d->ref_cache_.end())
3380                 return it->second.second;
3381
3382         static InsetLabel const * dummy_il = 0;
3383         static References const dummy_refs;
3384         it = d->ref_cache_.insert(
3385                 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3386         return it->second.second;
3387 }
3388
3389
3390 Buffer::References const & Buffer::references(docstring const & label) const
3391 {
3392         return const_cast<Buffer *>(this)->getReferenceCache(label);
3393 }
3394
3395
3396 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3397 {
3398         References & refs = getReferenceCache(label);
3399         refs.push_back(make_pair(inset, it));
3400 }
3401
3402
3403 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3404 {
3405         masterBuffer()->d->ref_cache_[label].first = il;
3406 }
3407
3408
3409 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3410 {
3411         return masterBuffer()->d->ref_cache_[label].first;
3412 }
3413
3414
3415 void Buffer::clearReferenceCache() const
3416 {
3417         if (!d->parent())
3418                 d->ref_cache_.clear();
3419 }
3420
3421
3422 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
3423 {
3424         //FIXME: This does not work for child documents yet.
3425         reloadBibInfoCache();
3426
3427         // Check if the label 'from' appears more than once
3428         BiblioInfo const & keys = masterBibInfo();
3429         BiblioInfo::const_iterator bit  = keys.begin();
3430         BiblioInfo::const_iterator bend = keys.end();
3431         vector<docstring> labels;
3432
3433         for (; bit != bend; ++bit)
3434                 // FIXME UNICODE
3435                 labels.push_back(bit->first);
3436
3437         if (count(labels.begin(), labels.end(), from) > 1)
3438                 return;
3439
3440         string const paramName = "key";
3441         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3442                 if (it->lyxCode() != CITE_CODE) 
3443                         continue;
3444                 InsetCommand * inset = it->asInsetCommand();
3445                 docstring const oldValue = inset->getParam(paramName);
3446                 if (oldValue == from)
3447                         inset->setParam(paramName, to);
3448         }
3449 }
3450
3451
3452 void Buffer::getSourceCode(odocstream & os, string const format,
3453                            pit_type par_begin, pit_type par_end,
3454                            OutputWhat output, bool master) const
3455 {
3456         OutputParams runparams(&params().encoding());
3457         runparams.nice = true;
3458         runparams.flavor = params().getOutputFlavor(format);
3459         runparams.linelen = lyxrc.plaintext_linelen;
3460         // No side effect of file copying and image conversion
3461         runparams.dryrun = true;
3462
3463         if (output == CurrentParagraph) {
3464                 runparams.par_begin = par_begin;
3465                 runparams.par_end = par_end;
3466                 if (par_begin + 1 == par_end) {
3467                         os << "% "
3468                            << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3469                            << "\n\n";
3470                 } else {
3471                         os << "% "
3472                            << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3473                                         convert<docstring>(par_begin),
3474                                         convert<docstring>(par_end - 1))
3475                            << "\n\n";
3476                 }
3477                 // output paragraphs
3478                 if (runparams.flavor == OutputParams::LYX) {
3479                         Paragraph const & par = text().paragraphs()[par_begin];
3480                         ostringstream ods;
3481                         depth_type dt = par.getDepth();
3482                         par.write(ods, params(), dt);
3483                         os << from_utf8(ods.str());
3484                 } else if (runparams.flavor == OutputParams::HTML) {
3485                         XHTMLStream xs(os);
3486                         setMathFlavor(runparams);
3487                         xhtmlParagraphs(text(), *this, xs, runparams);
3488                 } else if (runparams.flavor == OutputParams::TEXT) {
3489                         bool dummy;
3490                         // FIXME Handles only one paragraph, unlike the others.
3491                         // Probably should have some routine with a signature like them.
3492                         writePlaintextParagraph(*this,
3493                                 text().paragraphs()[par_begin], os, runparams, dummy);
3494                 } else if (params().isDocBook()) {
3495                         docbookParagraphs(text(), *this, os, runparams);
3496                 } else {
3497                         // If we are previewing a paragraph, even if this is the
3498                         // child of some other buffer, let's cut the link here,
3499                         // so that no concurring settings from the master
3500                         // (e.g. branch state) interfere (see #8101).
3501                         if (!master)
3502                                 d->ignore_parent = true;
3503                         // We need to validate the Buffer params' features here
3504                         // in order to know if we should output polyglossia
3505                         // macros (instead of babel macros)
3506                         LaTeXFeatures features(*this, params(), runparams);
3507                         params().validate(features);
3508                         runparams.use_polyglossia = features.usePolyglossia();
3509                         TexRow texrow;
3510                         texrow.reset();
3511                         texrow.newline();
3512                         texrow.newline();
3513                         // latex or literate
3514                         otexstream ots(os, texrow);
3515
3516                         // the real stuff
3517                         latexParagraphs(*this, text(), ots, runparams);
3518
3519                         // Restore the parenthood
3520                         if (!master)
3521                                 d->ignore_parent = false;
3522                 }
3523         } else {
3524                 os << "% ";
3525                 if (output == FullSource)
3526                         os << _("Preview source code");
3527                 else if (output == OnlyPreamble)
3528                         os << _("Preview preamble");
3529                 else if (output == OnlyBody)
3530                         os << _("Preview body");
3531                 os << "\n\n";
3532                 if (runparams.flavor == OutputParams::LYX) {
3533                         ostringstream ods;
3534                         if (output == FullSource)
3535                                 write(ods);
3536                         else if (output == OnlyPreamble)
3537                                 params().writeFile(ods);
3538                         else if (output == OnlyBody)
3539                                 text().write(ods);
3540                         os << from_utf8(ods.str());
3541                 } else if (runparams.flavor == OutputParams::HTML) {
3542                         writeLyXHTMLSource(os, runparams, output);
3543                 } else if (runparams.flavor == OutputParams::TEXT) {
3544                         if (output == OnlyPreamble) {
3545                                 os << "% "<< _("Plain text does not have a preamble.");
3546                         } else
3547                                 writePlaintextFile(*this, os, runparams);
3548                 } else if (params().isDocBook()) {
3549                                 writeDocBookSource(os, absFileName(), runparams, output);
3550                 } else {
3551                         // latex or literate
3552                         d->texrow.reset();
3553                         d->texrow.newline();
3554                         d->texrow.newline();
3555                         otexstream ots(os, d->texrow);
3556                         if (master)
3557                                 runparams.is_child = true;
3558                         writeLaTeXSource(ots, string(), runparams, output);
3559                 }
3560         }
3561 }
3562
3563
3564 ErrorList & Buffer::errorList(string const & type) const
3565 {
3566         return d->errorLists[type];
3567 }
3568
3569
3570 void Buffer::updateTocItem(std::string const & type,
3571         DocIterator const & dit) const
3572 {
3573         if (d->gui_)
3574                 d->gui_->updateTocItem(type, dit);
3575 }
3576
3577
3578 void Buffer::structureChanged() const
3579 {
3580         if (d->gui_)
3581                 d->gui_->structureChanged();
3582 }
3583
3584
3585 void Buffer::errors(string const & err, bool from_master) const
3586 {
3587         if (d->gui_)
3588                 d->gui_->errors(err, from_master);
3589 }
3590
3591
3592 void Buffer::message(docstring const & msg) const
3593 {
3594         if (d->gui_)
3595                 d->gui_->message(msg);
3596 }
3597
3598
3599 void Buffer::setBusy(bool on) const
3600 {
3601         if (d->gui_)
3602                 d->gui_->setBusy(on);
3603 }
3604
3605
3606 void Buffer::updateTitles() const
3607 {
3608         if (d->wa_)
3609                 d->wa_->updateTitles();
3610 }
3611
3612
3613 void Buffer::resetAutosaveTimers() const
3614 {
3615         if (d->gui_)
3616                 d->gui_->resetAutosaveTimers();
3617 }
3618
3619
3620 bool Buffer::hasGuiDelegate() const
3621 {
3622         return d->gui_;
3623 }
3624
3625
3626 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3627 {
3628         d->gui_ = gui;
3629 }
3630
3631
3632
3633 namespace {
3634
3635 class AutoSaveBuffer : public ForkedProcess {
3636 public:
3637         ///
3638         AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3639                 : buffer_(buffer), fname_(fname) {}
3640         ///
3641         virtual shared_ptr<ForkedProcess> clone() const
3642         {
3643                 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3644         }
3645         ///
3646         int start()
3647         {
3648                 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3649                                                  from_utf8(fname_.absFileName())));
3650                 return run(DontWait);
3651         }
3652 private:
3653         ///
3654         virtual int generateChild();
3655         ///
3656         Buffer const & buffer_;
3657         FileName fname_;
3658 };
3659
3660
3661 int AutoSaveBuffer::generateChild()
3662 {
3663 #if defined(__APPLE__)
3664         /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3665          *   We should use something else like threads.
3666          *
3667          * Since I do not know how to determine at run time what is the OS X
3668          * version, I just disable forking altogether for now (JMarc)
3669          */
3670         pid_t const pid = -1;
3671 #else
3672         // tmp_ret will be located (usually) in /tmp
3673         // will that be a problem?
3674         // Note that this calls ForkedCalls::fork(), so it's
3675         // ok cross-platform.
3676         pid_t const pid = fork();
3677         // If you want to debug the autosave
3678         // you should set pid to -1, and comment out the fork.
3679         if (pid != 0 && pid != -1)
3680                 return pid;
3681 #endif
3682
3683         // pid = -1 signifies that lyx was unable
3684         // to fork. But we will do the save
3685         // anyway.
3686         bool failed = false;
3687         FileName const tmp_ret = FileName::tempName("lyxauto");
3688         if (!tmp_ret.empty()) {
3689                 buffer_.writeFile(tmp_ret);
3690                 // assume successful write of tmp_ret
3691                 if (!tmp_ret.moveTo(fname_))
3692                         failed = true;
3693         } else
3694                 failed = true;
3695
3696         if (failed) {
3697                 // failed to write/rename tmp_ret so try writing direct
3698                 if (!buffer_.writeFile(fname_)) {
3699                         // It is dangerous to do this in the child,
3700                         // but safe in the parent, so...
3701                         if (pid == -1) // emit message signal.
3702                                 buffer_.message(_("Autosave failed!"));
3703                 }
3704         }
3705
3706         if (pid == 0) // we are the child so...
3707                 _exit(0);
3708
3709         return pid;
3710 }
3711
3712 } // namespace anon
3713
3714
3715 FileName Buffer::getEmergencyFileName() const
3716 {
3717         return FileName(d->filename.absFileName() + ".emergency");
3718 }
3719
3720
3721 FileName Buffer::getAutosaveFileName() const
3722 {
3723         // if the document is unnamed try to save in the backup dir, else
3724         // in the default document path, and as a last try in the filePath,
3725         // which will most often be the temporary directory
3726         string fpath;
3727         if (isUnnamed())
3728                 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3729                         : lyxrc.backupdir_path;
3730         if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3731                 fpath = filePath();
3732
3733         string const fname = "#" + d->filename.onlyFileName() + "#";
3734
3735         return makeAbsPath(fname, fpath);
3736 }
3737
3738
3739 void Buffer::removeAutosaveFile() const
3740 {
3741         FileName const f = getAutosaveFileName();
3742         if (f.exists())
3743                 f.removeFile();
3744 }
3745
3746
3747 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3748 {
3749         FileName const newauto = getAutosaveFileName();
3750         oldauto.refresh();
3751         if (newauto != oldauto && oldauto.exists())
3752                 if (!oldauto.moveTo(newauto))
3753                         LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3754 }
3755
3756
3757 bool Buffer::autoSave() const
3758 {
3759         Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3760         if (buf->d->bak_clean || isReadonly())
3761                 return true;
3762
3763         message(_("Autosaving current document..."));
3764         buf->d->bak_clean = true;
3765
3766         FileName const fname = getAutosaveFileName();
3767         LASSERT(d->cloned_buffer_, return false);
3768
3769         // If this buffer is cloned, we assume that
3770         // we are running in a separate thread already.
3771         FileName const tmp_ret = FileName::tempName("lyxauto");
3772         if (!tmp_ret.empty()) {
3773                 writeFile(tmp_ret);
3774                 // assume successful write of tmp_ret
3775                 if (tmp_ret.moveTo(fname))
3776                         return true;
3777         }
3778         // failed to write/rename tmp_ret so try writing direct
3779         return writeFile(fname);
3780 }
3781
3782
3783 void Buffer::setExportStatus(bool e) const
3784 {
3785         d->doing_export = e;
3786         ListOfBuffers clist = getDescendents();
3787         ListOfBuffers::const_iterator cit = clist.begin();
3788         ListOfBuffers::const_iterator const cen = clist.end();
3789         for (; cit != cen; ++cit)
3790                 (*cit)->d->doing_export = e;
3791 }
3792
3793
3794 bool Buffer::isExporting() const
3795 {
3796         return d->doing_export;
3797 }
3798
3799
3800 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
3801         const
3802 {
3803         string result_file;
3804         return doExport(target, put_in_tempdir, result_file);
3805 }
3806
3807 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3808         string & result_file) const
3809 {
3810         bool const update_unincluded =
3811                         params().maintain_unincluded_children
3812                         && !params().getIncludedChildren().empty();
3813
3814         // (1) export with all included children (omit \includeonly)
3815         if (update_unincluded) {
3816                 ExportStatus const status =
3817                         doExport(target, put_in_tempdir, true, result_file);
3818                 if (status != ExportSuccess)
3819                         return status;
3820         }
3821         // (2) export with included children only
3822         return doExport(target, put_in_tempdir, false, result_file);
3823 }
3824
3825
3826 void Buffer::setMathFlavor(OutputParams & op) const
3827 {
3828         switch (params().html_math_output) {
3829         case BufferParams::MathML:
3830                 op.math_flavor = OutputParams::MathAsMathML;
3831                 break;
3832         case BufferParams::HTML:
3833                 op.math_flavor = OutputParams::MathAsHTML;
3834                 break;
3835         case BufferParams::Images:
3836                 op.math_flavor = OutputParams::MathAsImages;
3837                 break;
3838         case BufferParams::LaTeX:
3839                 op.math_flavor = OutputParams::MathAsLaTeX;
3840                 break;
3841         }
3842 }
3843
3844
3845 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3846         bool includeall, string & result_file) const
3847 {
3848         LYXERR(Debug::FILES, "target=" << target);
3849         OutputParams runparams(&params().encoding());
3850         string format = target;
3851         string dest_filename;
3852         size_t pos = target.find(' ');
3853         if (pos != string::npos) {
3854                 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
3855                 format = target.substr(0, pos);
3856                 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
3857                 FileName(dest_filename).onlyPath().createPath();
3858                 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
3859         }
3860         MarkAsExporting exporting(this);
3861         string backend_format;
3862         runparams.flavor = OutputParams::LATEX;
3863         runparams.linelen = lyxrc.plaintext_linelen;
3864         runparams.includeall = includeall;
3865         vector<string> backs = params().backends();
3866         Converters converters = theConverters();
3867         bool need_nice_file = false;
3868         if (find(backs.begin(), backs.end(), format) == backs.end()) {
3869                 // Get shortest path to format
3870                 converters.buildGraph();
3871                 Graph::EdgePath path;
3872                 for (vector<string>::const_iterator it = backs.begin();
3873                      it != backs.end(); ++it) {
3874                         Graph::EdgePath p = converters.getPath(*it, format);
3875                         if (!p.empty() && (path.empty() || p.size() < path.size())) {
3876                                 backend_format = *it;
3877                                 path = p;
3878                         }
3879                 }
3880                 if (path.empty()) {
3881                         if (!put_in_tempdir) {
3882                                 // Only show this alert if this is an export to a non-temporary
3883                                 // file (not for previewing).
3884                                 Alert::error(_("Couldn't export file"), bformat(
3885                                         _("No information for exporting the format %1$s."),
3886                                         formats.prettyName(format)));
3887                         }
3888                         return ExportNoPathToFormat;
3889                 }
3890                 runparams.flavor = converters.getFlavor(path, this);
3891                 Graph::EdgePath::const_iterator it = path.begin();
3892                 Graph::EdgePath::const_iterator en = path.end();
3893                 for (; it != en; ++it)
3894                         if (theConverters().get(*it).nice) {
3895                                 need_nice_file = true;
3896                                 break;
3897                         }
3898
3899         } else {
3900                 backend_format = format;
3901                 LYXERR(Debug::FILES, "backend_format=" << backend_format);
3902                 // FIXME: Don't hardcode format names here, but use a flag
3903                 if (backend_format == "pdflatex")
3904                         runparams.flavor = OutputParams::PDFLATEX;
3905                 else if (backend_format == "luatex")
3906                         runparams.flavor = OutputParams::LUATEX;
3907                 else if (backend_format == "dviluatex")
3908                         runparams.flavor = OutputParams::DVILUATEX;
3909                 else if (backend_format == "xetex")
3910                         runparams.flavor = OutputParams::XETEX;
3911         }
3912
3913         string filename = latexName(false);
3914         filename = addName(temppath(), filename);
3915         filename = changeExtension(filename,
3916                                    formats.extension(backend_format));
3917         LYXERR(Debug::FILES, "filename=" << filename);
3918
3919         // Plain text backend
3920         if (backend_format == "text") {
3921                 runparams.flavor = OutputParams::TEXT;
3922                 writePlaintextFile(*this, FileName(filename), runparams);
3923         }
3924         // HTML backend
3925         else if (backend_format == "xhtml") {
3926                 runparams.flavor = OutputParams::HTML;
3927                 setMathFlavor(runparams);
3928                 makeLyXHTMLFile(FileName(filename), runparams);
3929         } else if (backend_format == "lyx")
3930                 writeFile(FileName(filename));
3931         // Docbook backend
3932         else if (params().isDocBook()) {
3933                 runparams.nice = !put_in_tempdir;
3934                 makeDocBookFile(FileName(filename), runparams);
3935         }
3936         // LaTeX backend
3937         else if (backend_format == format || need_nice_file) {
3938                 runparams.nice = true;
3939                 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
3940                 if (d->cloned_buffer_)
3941                         d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
3942                 if (!success)
3943                         return ExportError;
3944         } else if (!lyxrc.tex_allows_spaces
3945                    && contains(filePath(), ' ')) {
3946                 Alert::error(_("File name error"),
3947                            _("The directory path to the document cannot contain spaces."));
3948                 return ExportTexPathHasSpaces;
3949         } else {
3950                 runparams.nice = false;
3951                 bool const success = makeLaTeXFile(
3952                         FileName(filename), filePath(), runparams);
3953                 if (d->cloned_buffer_)
3954                         d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
3955                 if (!success)
3956                         return ExportError;
3957         }
3958
3959         string const error_type = (format == "program")
3960                 ? "Build" : params().bufferFormat();
3961         ErrorList & error_list = d->errorLists[error_type];
3962         string const ext = formats.extension(format);
3963         FileName const tmp_result_file(changeExtension(filename, ext));
3964         bool const success = converters.convert(this, FileName(filename),
3965                 tmp_result_file, FileName(absFileName()), backend_format, format,
3966                 error_list);
3967
3968         // Emit the signal to show the error list or copy it back to the
3969         // cloned Buffer so that it can be emitted afterwards.
3970         if (format != backend_format) {
3971                 if (d->cloned_buffer_) {
3972                         d->cloned_buffer_->d->errorLists[error_type] =
3973                                 d->errorLists[error_type];
3974                 } else
3975                         errors(error_type);
3976                 // also to the children, in case of master-buffer-view
3977                 ListOfBuffers clist = getDescendents();
3978                 ListOfBuffers::const_iterator cit = clist.begin();
3979                 ListOfBuffers::const_iterator const cen = clist.end();
3980                 for (; cit != cen; ++cit) {
3981                         if (d->cloned_buffer_) {
3982                                 // Enable reverse search by copying back the
3983                                 // texrow object to the cloned buffer.
3984                                 // FIXME: this is not thread safe.
3985                                 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
3986                                 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
3987                                         (*cit)->d->errorLists[error_type];
3988                         } else
3989                                 (*cit)->errors(error_type, true);
3990                 }
3991         }
3992
3993         if (d->cloned_buffer_) {
3994                 // Enable reverse dvi or pdf to work by copying back the texrow
3995                 // object to the cloned buffer.
3996                 // FIXME: There is a possibility of concurrent access to texrow
3997                 // here from the main GUI thread that should be securized.
3998                 d->cloned_buffer_->d->texrow = d->texrow;
3999                 string const error_type = params().bufferFormat();
4000                 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
4001         }
4002
4003         if (!success)
4004                 return ExportConverterError;
4005
4006         if (put_in_tempdir) {
4007                 result_file = tmp_result_file.absFileName();
4008                 return ExportSuccess;
4009         }
4010
4011         if (dest_filename.empty())
4012                 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4013         else
4014                 result_file = dest_filename;
4015         // We need to copy referenced files (e. g. included graphics
4016         // if format == "dvi") to the result dir.
4017         vector<ExportedFile> const files =
4018                 runparams.exportdata->externalFiles(format);
4019         string const dest = runparams.export_folder.empty() ?
4020                 onlyPath(result_file) : runparams.export_folder;
4021         bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4022                                  : force_overwrite == ALL_FILES;
4023         CopyStatus status = use_force ? FORCE : SUCCESS;
4024
4025         vector<ExportedFile>::const_iterator it = files.begin();
4026         vector<ExportedFile>::const_iterator const en = files.end();
4027         for (; it != en && status != CANCEL; ++it) {
4028                 string const fmt = formats.getFormatFromFile(it->sourceName);
4029                 string fixedName = it->exportName;
4030                 if (!runparams.export_folder.empty()) {
4031                         // Relative pathnames starting with ../ will be sanitized
4032                         // if exporting to a different folder
4033                         while (fixedName.substr(0, 3) == "../")
4034                                 fixedName = fixedName.substr(3, fixedName.length() - 3);
4035                 }
4036                 FileName fixedFileName = makeAbsPath(fixedName, dest);
4037                 fixedFileName.onlyPath().createPath();
4038                 status = copyFile(fmt, it->sourceName,
4039                         fixedFileName,
4040                         it->exportName, status == FORCE,
4041                         runparams.export_folder.empty());
4042         }
4043
4044         if (status == CANCEL) {
4045                 message(_("Document export cancelled."));
4046                 return ExportCancel;
4047         }
4048
4049         if (tmp_result_file.exists()) {
4050                 // Finally copy the main file
4051                 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4052                                     : force_overwrite != NO_FILES;
4053                 if (status == SUCCESS && use_force)
4054                         status = FORCE;
4055                 status = copyFile(format, tmp_result_file,
4056                         FileName(result_file), result_file,
4057                         status == FORCE);
4058                 if (status == CANCEL) {
4059                         message(_("Document export cancelled."));
4060                         return ExportCancel;
4061                 } else {
4062                         message(bformat(_("Document exported as %1$s "
4063                                 "to file `%2$s'"),
4064                                 formats.prettyName(format),
4065                                 makeDisplayPath(result_file)));
4066                 }
4067         } else {
4068                 // This must be a dummy converter like fax (bug 1888)
4069                 message(bformat(_("Document exported as %1$s"),
4070                         formats.prettyName(format)));
4071         }
4072
4073         return ExportSuccess;
4074 }
4075
4076
4077 Buffer::ExportStatus Buffer::preview(string const & format) const
4078 {
4079         bool const update_unincluded =
4080                         params().maintain_unincluded_children
4081                         && !params().getIncludedChildren().empty();
4082         return preview(format, update_unincluded);
4083 }
4084
4085 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4086 {
4087         MarkAsExporting exporting(this);
4088         string result_file;
4089         // (1) export with all included children (omit \includeonly)
4090         if (includeall) {
4091                 ExportStatus const status = doExport(format, true, true, result_file);
4092                 if (status != ExportSuccess)
4093                         return status;
4094         }
4095         // (2) export with included children only
4096         ExportStatus const status = doExport(format, true, false, result_file);
4097         if (status != ExportSuccess)
4098                 return status;
4099         if (!formats.view(*this, FileName(result_file), format))
4100                 return PreviewError;
4101         return PreviewSuccess;
4102 }
4103
4104
4105 Buffer::ReadStatus Buffer::extractFromVC()
4106 {
4107         bool const found = LyXVC::file_not_found_hook(d->filename);
4108         if (!found)
4109                 return ReadFileNotFound;
4110         if (!d->filename.isReadableFile())
4111                 return ReadVCError;
4112         return ReadSuccess;
4113 }
4114
4115
4116 Buffer::ReadStatus Buffer::loadEmergency()
4117 {
4118         FileName const emergencyFile = getEmergencyFileName();
4119         if (!emergencyFile.exists()
4120                   || emergencyFile.lastModified() <= d->filename.lastModified())
4121                 return ReadFileNotFound;
4122
4123         docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4124         docstring const text = bformat(_("An emergency save of the document "
4125                 "%1$s exists.\n\nRecover emergency save?"), file);
4126
4127         int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4128                 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4129
4130         switch (load_emerg)
4131         {
4132         case 0: {
4133                 docstring str;
4134                 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4135                 bool const success = (ret_llf == ReadSuccess);
4136                 if (success) {
4137                         if (isReadonly()) {
4138                                 Alert::warning(_("File is read-only"),
4139                                         bformat(_("An emergency file is successfully loaded, "
4140                                         "but the original file %1$s is marked read-only. "
4141                                         "Please make sure to save the document as a different "
4142                                         "file."), from_utf8(d->filename.absFileName())));
4143                         }
4144                         markDirty();
4145                         lyxvc().file_found_hook(d->filename);
4146                         str = _("Document was successfully recovered.");
4147                 } else
4148                         str = _("Document was NOT successfully recovered.");
4149                 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4150                         makeDisplayPath(emergencyFile.absFileName()));
4151
4152                 int const del_emerg =
4153                         Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4154                                 _("&Remove"), _("&Keep"));
4155                 if (del_emerg == 0) {
4156                         emergencyFile.removeFile();
4157                         if (success)
4158                                 Alert::warning(_("Emergency file deleted"),
4159                                         _("Do not forget to save your file now!"), true);
4160                         }
4161                 return success ? ReadSuccess : ReadEmergencyFailure;
4162         }
4163         case 1: {
4164                 int const del_emerg =
4165                         Alert::prompt(_("Delete emergency file?"),
4166                                 _("Remove emergency file now?"), 1, 1,
4167                                 _("&Remove"), _("&Keep"));
4168                 if (del_emerg == 0)
4169                         emergencyFile.removeFile();
4170                 return ReadOriginal;
4171         }
4172
4173         default:
4174                 break;
4175         }
4176         return ReadCancel;
4177 }
4178
4179
4180 Buffer::ReadStatus Buffer::loadAutosave()
4181 {
4182         // Now check if autosave file is newer.
4183         FileName const autosaveFile = getAutosaveFileName();
4184         if (!autosaveFile.exists()
4185                   || autosaveFile.lastModified() <= d->filename.lastModified())
4186                 return ReadFileNotFound;
4187
4188         docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4189         docstring const text = bformat(_("The backup of the document %1$s "
4190                 "is newer.\n\nLoad the backup instead?"), file);
4191         int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4192                 _("&Load backup"), _("Load &original"), _("&Cancel"));
4193
4194         switch (ret)
4195         {
4196         case 0: {
4197                 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4198                 // the file is not saved if we load the autosave file.
4199                 if (ret_llf == ReadSuccess) {
4200                         if (isReadonly()) {
4201                                 Alert::warning(_("File is read-only"),
4202                                         bformat(_("A backup file is successfully loaded, "
4203                                         "but the original file %1$s is marked read-only. "
4204                                         "Please make sure to save the document as a "
4205                                         "different file."),
4206                                         from_utf8(d->filename.absFileName())));
4207                         }
4208                         markDirty();
4209                         lyxvc().file_found_hook(d->filename);
4210                         return ReadSuccess;
4211                 }
4212                 return ReadAutosaveFailure;
4213         }
4214         case 1:
4215                 // Here we delete the autosave
4216                 autosaveFile.removeFile();
4217                 return ReadOriginal;
4218         default:
4219                 break;
4220         }
4221         return ReadCancel;
4222 }
4223
4224
4225 Buffer::ReadStatus Buffer::loadLyXFile()
4226 {
4227         if (!d->filename.isReadableFile()) {
4228                 ReadStatus const ret_rvc = extractFromVC();
4229                 if (ret_rvc != ReadSuccess)
4230                         return ret_rvc;
4231         }
4232
4233         ReadStatus const ret_re = loadEmergency();
4234         if (ret_re == ReadSuccess || ret_re == ReadCancel)
4235                 return ret_re;
4236
4237         ReadStatus const ret_ra = loadAutosave();
4238         if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4239                 return ret_ra;
4240
4241         return loadThisLyXFile(d->filename);
4242 }
4243
4244
4245 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4246 {
4247         return readFile(fn);
4248 }
4249
4250
4251 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4252 {
4253         TeXErrors::Errors::const_iterator it = terr.begin();
4254         TeXErrors::Errors::const_iterator end = terr.end();
4255         ListOfBuffers clist = getDescendents();
4256         ListOfBuffers::const_iterator cen = clist.end();
4257
4258         for (; it != end; ++it) {
4259                 int id_start = -1;
4260                 int pos_start = -1;
4261                 int errorRow = it->error_in_line;
4262                 Buffer const * buf = 0;
4263                 Impl const * p = d;
4264                 if (it->child_name.empty())
4265                     p->texrow.getIdFromRow(errorRow, id_start, pos_start);
4266                 else {
4267                         // The error occurred in a child
4268                         ListOfBuffers::const_iterator cit = clist.begin();
4269                         for (; cit != cen; ++cit) {
4270                                 string const child_name =
4271                                         DocFileName(changeExtension(
4272                                                 (*cit)->absFileName(), "tex")).
4273                                                         mangledFileName();
4274                                 if (it->child_name != child_name)
4275                                         continue;
4276                                 (*cit)->d->texrow.getIdFromRow(errorRow,
4277                                                         id_start, pos_start);
4278                                 if (id_start != -1) {
4279                                         buf = d->cloned_buffer_
4280                                                 ? (*cit)->d->cloned_buffer_->d->owner_
4281                                                 : (*cit)->d->owner_;
4282                                         p = (*cit)->d;
4283                                         break;
4284                                 }
4285                         }
4286                 }
4287                 int id_end = -1;
4288                 int pos_end = -1;
4289                 bool found;
4290                 do {
4291                         ++errorRow;
4292                         found = p->texrow.getIdFromRow(errorRow, id_end, pos_end);
4293                 } while (found && id_start == id_end && pos_start == pos_end);
4294
4295                 if (id_start != id_end) {
4296                         // Next registered position is outside the inset where
4297                         // the error occurred, so signal end-of-paragraph
4298                         pos_end = 0;
4299                 }
4300
4301                 errorList.push_back(ErrorItem(it->error_desc,
4302                         it->error_text, id_start, pos_start, pos_end, buf));
4303         }
4304 }
4305
4306
4307 void Buffer::setBuffersForInsets() const
4308 {
4309         inset().setBuffer(const_cast<Buffer &>(*this));
4310 }
4311
4312
4313 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4314 {
4315         LBUFERR(!text().paragraphs().empty());
4316
4317         // Use the master text class also for child documents
4318         Buffer const * const master = masterBuffer();
4319         DocumentClass const & textclass = master->params().documentClass();
4320
4321         // do this only if we are the top-level Buffer
4322         if (master == this) {
4323                 textclass.counters().reset(from_ascii("bibitem"));
4324                 reloadBibInfoCache();
4325         }
4326
4327         // keep the buffers to be children in this set. If the call from the
4328         // master comes back we can see which of them were actually seen (i.e.
4329         // via an InsetInclude). The remaining ones in the set need still be updated.
4330         static std::set<Buffer const *> bufToUpdate;
4331         if (scope == UpdateMaster) {
4332                 // If this is a child document start with the master
4333                 if (master != this) {
4334                         bufToUpdate.insert(this);
4335                         master->updateBuffer(UpdateMaster, utype);
4336                         // Do this here in case the master has no gui associated with it. Then,
4337                         // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
4338                         if (!master->d->gui_)
4339                                 structureChanged();
4340
4341                         // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4342                         if (bufToUpdate.find(this) == bufToUpdate.end())
4343                                 return;
4344                 }
4345
4346                 // start over the counters in the master
4347                 textclass.counters().reset();
4348         }
4349
4350         // update will be done below for this buffer
4351         bufToUpdate.erase(this);
4352
4353         // update all caches
4354         clearReferenceCache();
4355         updateMacros();
4356
4357         Buffer & cbuf = const_cast<Buffer &>(*this);
4358
4359         // do the real work
4360         ParIterator parit = cbuf.par_iterator_begin();
4361         updateBuffer(parit, utype);
4362
4363         if (master != this)
4364                 // TocBackend update will be done later.
4365                 return;
4366
4367         d->bibinfo_cache_valid_ = true;
4368         d->cite_labels_valid_ = true;
4369         cbuf.tocBackend().update(utype == OutputUpdate);
4370         if (scope == UpdateMaster)
4371                 cbuf.structureChanged();
4372 }
4373
4374
4375 static depth_type getDepth(DocIterator const & it)
4376 {
4377         depth_type depth = 0;
4378         for (size_t i = 0 ; i < it.depth() ; ++i)
4379                 if (!it[i].inset().inMathed())
4380                         depth += it[i].paragraph().getDepth() + 1;
4381         // remove 1 since the outer inset does not count
4382         return depth - 1;
4383 }
4384
4385 static depth_type getItemDepth(ParIterator const & it)
4386 {
4387         Paragraph const & par = *it;
4388         LabelType const labeltype = par.layout().labeltype;
4389
4390         if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4391                 return 0;
4392
4393         // this will hold the lowest depth encountered up to now.
4394         depth_type min_depth = getDepth(it);
4395         ParIterator prev_it = it;
4396         while (true) {
4397                 if (prev_it.pit())
4398                         --prev_it.top().pit();
4399                 else {
4400                         // start of nested inset: go to outer par
4401                         prev_it.pop_back();
4402                         if (prev_it.empty()) {
4403                                 // start of document: nothing to do
4404                                 return 0;
4405                         }
4406                 }
4407
4408                 // We search for the first paragraph with same label
4409                 // that is not more deeply nested.
4410                 Paragraph & prev_par = *prev_it;
4411                 depth_type const prev_depth = getDepth(prev_it);
4412                 if (labeltype == prev_par.layout().labeltype) {
4413                         if (prev_depth < min_depth)
4414                                 return prev_par.itemdepth + 1;
4415                         if (prev_depth == min_depth)
4416                                 return prev_par.itemdepth;
4417                 }
4418                 min_depth = min(min_depth, prev_depth);
4419                 // small optimization: if we are at depth 0, we won't
4420                 // find anything else
4421                 if (prev_depth == 0)
4422                         return 0;
4423         }
4424 }
4425
4426
4427 static bool needEnumCounterReset(ParIterator const & it)
4428 {
4429         Paragraph const & par = *it;
4430         LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
4431         depth_type const cur_depth = par.getDepth();
4432         ParIterator prev_it = it;
4433         while (prev_it.pit()) {
4434                 --prev_it.top().pit();
4435                 Paragraph const & prev_par = *prev_it;
4436                 if (prev_par.getDepth() <= cur_depth)
4437                         return  prev_par.layout().labeltype != LABEL_ENUMERATE;
4438         }
4439         // start of nested inset: reset
4440         return true;
4441 }
4442
4443
4444 // set the label of a paragraph. This includes the counters.
4445 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4446 {
4447         BufferParams const & bp = owner_->masterBuffer()->params();
4448         DocumentClass const & textclass = bp.documentClass();
4449         Paragraph & par = it.paragraph();
4450         Layout const & layout = par.layout();
4451         Counters & counters = textclass.counters();
4452
4453         if (par.params().startOfAppendix()) {
4454                 // We want to reset the counter corresponding to toplevel sectioning
4455                 Layout const & lay = textclass.getTOCLayout();
4456                 docstring const cnt = lay.counter;
4457                 if (!cnt.empty())
4458                         counters.reset(cnt);
4459                 counters.appendix(true);
4460         }
4461         par.params().appendix(counters.appendix());
4462
4463         // Compute the item depth of the paragraph
4464         par.itemdepth = getItemDepth(it);
4465
4466         if (layout.margintype == MARGIN_MANUAL) {
4467                 if (par.params().labelWidthString().empty())
4468                         par.params().labelWidthString(par.expandLabel(layout, bp));
4469         } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4470                 // we do not need to do anything here, since the empty case is
4471                 // handled during export.
4472         } else {
4473                 par.params().labelWidthString(docstring());
4474         }
4475
4476         switch(layout.labeltype) {
4477         case LABEL_ITEMIZE: {
4478                 // At some point of time we should do something more
4479                 // clever here, like:
4480                 //   par.params().labelString(
4481                 //    bp.user_defined_bullet(par.itemdepth).getText());
4482                 // for now, use a simple hardcoded label
4483                 docstring itemlabel;
4484                 switch (par.itemdepth) {
4485                 case 0:
4486                         itemlabel = char_type(0x2022);
4487                         break;
4488                 case 1:
4489                         itemlabel = char_type(0x2013);
4490                         break;
4491                 case 2:
4492                         itemlabel = char_type(0x2217);
4493                         break;
4494                 case 3:
4495                         itemlabel = char_type(0x2219); // or 0x00b7
4496                         break;
4497                 }
4498                 par.params().labelString(itemlabel);
4499                 break;
4500         }
4501
4502         case LABEL_ENUMERATE: {
4503                 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4504
4505                 switch (par.itemdepth) {
4506                 case 2:
4507                         enumcounter += 'i';
4508                 case 1:
4509                         enumcounter += 'i';
4510                 case 0:
4511                         enumcounter += 'i';
4512                         break;
4513                 case 3:
4514                         enumcounter += "iv";
4515                         break;
4516                 default:
4517                         // not a valid enumdepth...
4518                         break;
4519                 }
4520
4521                 // Maybe we have to reset the enumeration counter.
4522                 if (needEnumCounterReset(it))
4523                         counters.reset(enumcounter);
4524                 counters.step(enumcounter, utype);
4525
4526                 string const & lang = par.getParLanguage(bp)->code();
4527                 par.params().labelString(counters.theCounter(enumcounter, lang));
4528
4529                 break;
4530         }
4531
4532         case LABEL_SENSITIVE: {
4533                 string const & type = counters.current_float();
4534                 docstring full_label;
4535                 if (type.empty())
4536                         full_label = owner_->B_("Senseless!!! ");
4537                 else {
4538                         docstring name = owner_->B_(textclass.floats().getType(type).name());
4539                         if (counters.hasCounter(from_utf8(type))) {
4540                                 string const & lang = par.getParLanguage(bp)->code();
4541                                 counters.step(from_utf8(type), utype);
4542                                 full_label = bformat(from_ascii("%1$s %2$s:"),
4543                                                      name,
4544                                                      counters.theCounter(from_utf8(type), lang));
4545                         } else
4546                                 full_label = bformat(from_ascii("%1$s #:"), name);
4547                 }
4548                 par.params().labelString(full_label);
4549                 break;
4550         }
4551
4552         case LABEL_NO_LABEL:
4553                 par.params().labelString(docstring());
4554                 break;
4555
4556         case LABEL_ABOVE:
4557         case LABEL_CENTERED:
4558         case LABEL_STATIC: {
4559                 docstring const & lcounter = layout.counter;
4560                 if (!lcounter.empty()) {
4561                         if (layout.toclevel <= bp.secnumdepth
4562                                                 && (layout.latextype != LATEX_ENVIRONMENT
4563                                         || it.text()->isFirstInSequence(it.pit()))) {
4564                                 if (counters.hasCounter(lcounter))
4565                                         counters.step(lcounter, utype);
4566                                 par.params().labelString(par.expandLabel(layout, bp));
4567                         } else
4568                                 par.params().labelString(docstring());
4569                 } else
4570                         par.params().labelString(par.expandLabel(layout, bp));
4571                 break;
4572         }
4573
4574         case LABEL_MANUAL:
4575         case LABEL_BIBLIO:
4576                 par.params().labelString(par.expandLabel(layout, bp));
4577         }
4578 }
4579
4580
4581 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4582 {
4583         // LASSERT: Is it safe to continue here, or should we just return?
4584         LASSERT(parit.pit() == 0, /**/);
4585
4586         // Set the position of the text in the buffer to be able
4587         // to resolve macros in it.
4588         parit.text()->setMacrocontextPosition(parit);
4589
4590         depth_type maxdepth = 0;
4591         pit_type const lastpit = parit.lastpit();
4592         for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4593                 // reduce depth if necessary
4594                 if (parit->params().depth() > maxdepth) {
4595                         /** FIXME: this function is const, but
4596                          * nevertheless it modifies the buffer. To be
4597                          * cleaner, one should modify the buffer in
4598                          * another function, which is actually
4599                          * non-const. This would however be costly in
4600                          * terms of code duplication.
4601                          */
4602                         const_cast<Buffer *>(this)->undo().recordUndo(CursorData(parit));
4603                         parit->params().depth(maxdepth);
4604                 }
4605                 maxdepth = parit->getMaxDepthAfter();
4606
4607                 if (utype == OutputUpdate) {
4608                         // track the active counters
4609                         // we have to do this for the master buffer, since the local
4610                         // buffer isn't tracking anything.
4611                         masterBuffer()->params().documentClass().counters().
4612                                         setActiveLayout(parit->layout());
4613                 }
4614
4615                 // set the counter for this paragraph
4616                 d->setLabel(parit, utype);
4617
4618                 // now the insets
4619                 InsetList::const_iterator iit = parit->insetList().begin();
4620                 InsetList::const_iterator end = parit->insetList().end();
4621                 for (; iit != end; ++iit) {
4622                         parit.pos() = iit->pos;
4623                         iit->inset->updateBuffer(parit, utype);
4624                 }
4625         }
4626 }
4627
4628
4629 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4630         WordLangTuple & word_lang, docstring_list & suggestions) const
4631 {
4632         int progress = 0;
4633         WordLangTuple wl;
4634         suggestions.clear();
4635         word_lang = WordLangTuple();
4636         bool const to_end = to.empty();
4637         DocIterator const end = to_end ? doc_iterator_end(this) : to;
4638         // OK, we start from here.
4639         for (; from != end; from.forwardPos()) {
4640                 // We are only interested in text so remove the math CursorSlice.
4641                 while (from.inMathed()) {
4642                         from.pop_back();
4643                         from.pos()++;
4644                 }
4645                 // If from is at the end of the document (which is possible
4646                 // when leaving the mathed) LyX will crash later otherwise.
4647                 if (from.atEnd() || (!to_end && from >= end))
4648                         break;
4649                 to = from;
4650                 from.paragraph().spellCheck();
4651                 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4652                 if (SpellChecker::misspelled(res)) {
4653                         word_lang = wl;
4654                         break;
4655                 }
4656
4657                 // Do not increase progress when from == to, otherwise the word
4658                 // count will be wrong.
4659                 if (from != to) {
4660                         from = to;
4661                         ++progress;
4662                 }
4663         }
4664         return progress;
4665 }
4666
4667
4668 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
4669 {
4670         bool inword = false;
4671         word_count_ = 0;
4672         char_count_ = 0;
4673         blank_count_ = 0;
4674  
4675         for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
4676                 if (!dit.inTexted()) {
4677                         dit.forwardPos();
4678                         continue;
4679                 }
4680                 
4681                 Paragraph const & par = dit.paragraph();
4682                 pos_type const pos = dit.pos();
4683                 
4684                 // Copied and adapted from isWordSeparator() in Paragraph
4685                 if (pos == dit.lastpos()) {
4686                         inword = false;
4687                 } else {
4688                         Inset const * ins = par.getInset(pos);
4689                         if (ins && skipNoOutput && !ins->producesOutput()) {
4690                                 // skip this inset
4691                                 ++dit.top().pos();
4692                                 // stop if end of range was skipped
4693                                 if (!to.atEnd() && dit >= to)
4694                                         break;
4695                                 continue;
4696                         } else if (!par.isDeleted(pos)) {
4697                                 if (par.isWordSeparator(pos)) 
4698                                         inword = false;
4699                                 else if (!inword) {
4700                                         ++word_count_;
4701                                         inword = true;
4702                                 }
4703                                 if (ins && ins->isLetter())
4704                                         ++char_count_;
4705                                 else if (ins && ins->isSpace())
4706                                         ++blank_count_;
4707                                 else {
4708                                         char_type const c = par.getChar(pos);
4709                                         if (isPrintableNonspace(c))
4710                                                 ++char_count_;
4711                                         else if (isSpace(c))
4712                                                 ++blank_count_;
4713                                 }
4714                         }
4715                 }
4716                 dit.forwardPos();
4717         }
4718 }
4719
4720
4721 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
4722 {
4723         d->updateStatistics(from, to, skipNoOutput);
4724 }
4725
4726
4727 int Buffer::wordCount() const
4728 {
4729         return d->wordCount();
4730 }
4731
4732
4733 int Buffer::charCount(bool with_blanks) const
4734 {
4735         return d->charCount(with_blanks);
4736 }
4737
4738
4739 Buffer::ReadStatus Buffer::reload(bool clearUndo)
4740 {
4741         setBusy(true);
4742         // c.f. bug http://www.lyx.org/trac/ticket/6587
4743         removeAutosaveFile();
4744         // e.g., read-only status could have changed due to version control
4745         d->filename.refresh();
4746         docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4747
4748         // clear parent. this will get reset if need be.
4749         d->setParent(0);
4750         ReadStatus const status = loadLyXFile();
4751         if (status == ReadSuccess) {
4752                 updateBuffer();
4753                 changed(true);
4754                 updateTitles();
4755                 markClean();
4756                 message(bformat(_("Document %1$s reloaded."), disp_fn));
4757                 if (clearUndo)
4758                         d->undo_.clear();
4759         } else {
4760                 message(bformat(_("Could not reload document %1$s."), disp_fn));
4761         }
4762         setBusy(false);
4763         removePreviews();
4764         updatePreviews();
4765         errors("Parse");
4766         return status;
4767 }
4768
4769
4770 bool Buffer::saveAs(FileName const & fn)
4771 {
4772         FileName const old_name = fileName();
4773         FileName const old_auto = getAutosaveFileName();
4774         bool const old_unnamed = isUnnamed();
4775
4776         setFileName(fn);
4777         markDirty();
4778         setUnnamed(false);
4779
4780         if (save()) {
4781                 // bring the autosave file with us, just in case.
4782                 moveAutosaveFile(old_auto);
4783                 // validate version control data and
4784                 // correct buffer title
4785                 lyxvc().file_found_hook(fileName());
4786                 updateTitles();
4787                 // the file has now been saved to the new location.
4788                 // we need to check that the locations of child buffers
4789                 // are still valid.
4790                 checkChildBuffers();
4791                 checkMasterBuffer();
4792                 return true;
4793         } else {
4794                 // save failed
4795                 // reset the old filename and unnamed state
4796                 setFileName(old_name);
4797                 setUnnamed(old_unnamed);
4798                 return false;
4799         }
4800 }
4801
4802
4803 // FIXME We could do better here, but it is complicated. What would be
4804 // nice is to offer either (a) to save the child buffer to an appropriate
4805 // location, so that it would "move with the master", or else (b) to update
4806 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4807 // complicated, because the code for this lives in GuiView.
4808 void Buffer::checkChildBuffers()
4809 {
4810         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4811         Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4812         for (; it != en; ++it) {
4813                 DocIterator dit = it->second;
4814                 Buffer * cbuf = const_cast<Buffer *>(it->first);
4815                 if (!cbuf || !theBufferList().isLoaded(cbuf))
4816                         continue;
4817                 Inset * inset = dit.nextInset();
4818                 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4819                 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4820                 docstring const & incfile = inset_inc->getParam("filename");
4821                 string oldloc = cbuf->absFileName();
4822                 string newloc = makeAbsPath(to_utf8(incfile),
4823                                 onlyPath(absFileName())).absFileName();
4824                 if (oldloc == newloc)
4825                         continue;
4826                 // the location of the child file is incorrect.
4827                 Alert::warning(_("Included File Invalid"),
4828                                 bformat(_("Saving this document to a new location has made the file:\n"
4829                                 "  %1$s\n"
4830                                 "inaccessible. You will need to update the included filename."),
4831                                 from_utf8(oldloc)));
4832                 cbuf->setParent(0);
4833                 inset_inc->setChildBuffer(0);
4834         }
4835         // invalidate cache of children
4836         d->children_positions.clear();
4837         d->position_to_children.clear();
4838 }
4839
4840
4841 // If a child has been saved under a different name/path, it might have been
4842 // orphaned. Therefore the master needs to be reset (bug 8161).
4843 void Buffer::checkMasterBuffer()
4844 {
4845         Buffer const * const master = masterBuffer();
4846         if (master == this)
4847                 return;
4848
4849         // necessary to re-register the child (bug 5873)
4850         // FIXME: clean up updateMacros (here, only
4851         // child registering is needed).
4852         master->updateMacros();
4853         // (re)set master as master buffer, but only
4854         // if we are a real child
4855         if (master->isChild(this))
4856                 setParent(master);
4857         else
4858                 setParent(0);
4859 }
4860
4861 } // namespace lyx