]> git.lyx.org Git - lyx.git/blob - src/Buffer.cpp
0ac68c8db70b5d1e49b0d24afd0595916440a85d
[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 "BufferEncodings.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         if (runparams_in.silent)
1540                 errorList.clear();
1541         else
1542                 errors("Export");
1543         return !failed_export;
1544 }
1545
1546
1547 void Buffer::writeLaTeXSource(otexstream & os,
1548                            string const & original_path,
1549                            OutputParams const & runparams_in,
1550                            OutputWhat output) const
1551 {
1552         // The child documents, if any, shall be already loaded at this point.
1553
1554         OutputParams runparams = runparams_in;
1555
1556         // If we are compiling a file standalone, even if this is the
1557         // child of some other buffer, let's cut the link here, so the
1558         // file is really independent and no concurring settings from
1559         // the master (e.g. branch state) interfere (see #8100).
1560         if (!runparams.is_child)
1561                 d->ignore_parent = true;
1562
1563         // Classify the unicode characters appearing in math insets
1564         BufferEncodings::initUnicodeMath(*this);
1565
1566         // validate the buffer.
1567         LYXERR(Debug::LATEX, "  Validating buffer...");
1568         LaTeXFeatures features(*this, params(), runparams);
1569         validate(features);
1570         // This is only set once per document (in master)
1571         if (!runparams.is_child)
1572                 runparams.use_polyglossia = features.usePolyglossia();
1573         LYXERR(Debug::LATEX, "  Buffer validation done.");
1574
1575         bool const output_preamble =
1576                 output == FullSource || output == OnlyPreamble;
1577         bool const output_body =
1578                 output == FullSource || output == OnlyBody;
1579
1580         // The starting paragraph of the coming rows is the
1581         // first paragraph of the document. (Asger)
1582         if (output_preamble && runparams.nice) {
1583                 os << "%% LyX " << lyx_version << " created this file.  "
1584                         "For more info, see http://www.lyx.org/.\n"
1585                         "%% Do not edit unless you really know what "
1586                         "you are doing.\n";
1587         }
1588         LYXERR(Debug::INFO, "lyx document header finished");
1589
1590         // There are a few differences between nice LaTeX and usual files:
1591         // usual files have \batchmode and special input@path to allow
1592         // inclusion of figures specified by an explicitly relative path
1593         // (i.e., a path starting with './' or '../') with either \input or
1594         // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1595         // input@path is set when the actual parameter original_path is set.
1596         // This is done for usual tex-file, but not for nice-latex-file.
1597         // (Matthias 250696)
1598         // Note that input@path is only needed for something the user does
1599         // in the preamble, included .tex files or ERT, files included by
1600         // LyX work without it.
1601         if (output_preamble) {
1602                 if (!runparams.nice) {
1603                         // code for usual, NOT nice-latex-file
1604                         os << "\\batchmode\n"; // changed from \nonstopmode
1605                 }
1606                 if (!original_path.empty()) {
1607                         // FIXME UNICODE
1608                         // We don't know the encoding of inputpath
1609                         docstring const inputpath = from_utf8(original_path);
1610                         docstring uncodable_glyphs;
1611                         Encoding const * const enc = runparams.encoding;
1612                         if (enc) {
1613                                 for (size_t n = 0; n < inputpath.size(); ++n) {
1614                                         if (!enc->encodable(inputpath[n])) {
1615                                                 docstring const glyph(1, inputpath[n]);
1616                                                 LYXERR0("Uncodable character '"
1617                                                         << glyph
1618                                                         << "' in input path!");
1619                                                 uncodable_glyphs += glyph;
1620                                         }
1621                                 }
1622                         }
1623
1624                         // warn user if we found uncodable glyphs.
1625                         if (!uncodable_glyphs.empty()) {
1626                                 frontend::Alert::warning(
1627                                         _("Uncodable character in file path"),
1628                                         support::bformat(
1629                                           _("The path of your document\n"
1630                                             "(%1$s)\n"
1631                                             "contains glyphs that are unknown "
1632                                             "in the current document encoding "
1633                                             "(namely %2$s). This may result in "
1634                                             "incomplete output, unless "
1635                                             "TEXINPUTS contains the document "
1636                                             "directory and you don't use "
1637                                             "explicitly relative paths (i.e., "
1638                                             "paths starting with './' or "
1639                                             "'../') in the preamble or in ERT."
1640                                             "\n\nIn case of problems, choose "
1641                                             "an appropriate document encoding\n"
1642                                             "(such as utf8) or change the "
1643                                             "file path name."),
1644                                           inputpath, uncodable_glyphs));
1645                         } else {
1646                                 string docdir =
1647                                         support::latex_path(original_path);
1648                                 if (contains(docdir, '#')) {
1649                                         docdir = subst(docdir, "#", "\\#");
1650                                         os << "\\catcode`\\#=11"
1651                                               "\\def\\#{#}\\catcode`\\#=6\n";
1652                                 }
1653                                 if (contains(docdir, '%')) {
1654                                         docdir = subst(docdir, "%", "\\%");
1655                                         os << "\\catcode`\\%=11"
1656                                               "\\def\\%{%}\\catcode`\\%=14\n";
1657                                 }
1658                                 os << "\\makeatletter\n"
1659                                    << "\\def\\input@path{{"
1660                                    << docdir << "/}}\n"
1661                                    << "\\makeatother\n";
1662                         }
1663                 }
1664
1665                 // get parent macros (if this buffer has a parent) which will be
1666                 // written at the document begin further down.
1667                 MacroSet parentMacros;
1668                 listParentMacros(parentMacros, features);
1669
1670                 // Write the preamble
1671                 runparams.use_babel = params().writeLaTeX(os, features,
1672                                                           d->filename.onlyPath());
1673
1674                 // Japanese might be required only in some children of a document,
1675                 // but once required, we must keep use_japanese true.
1676                 runparams.use_japanese |= features.isRequired("japanese");
1677
1678                 if (!output_body) {
1679                         // Restore the parenthood if needed
1680                         if (!runparams.is_child)
1681                                 d->ignore_parent = false;
1682                         return;
1683                 }
1684
1685                 // make the body.
1686                 os << "\\begin{document}\n";
1687
1688                 // output the parent macros
1689                 MacroSet::iterator it = parentMacros.begin();
1690                 MacroSet::iterator end = parentMacros.end();
1691                 for (; it != end; ++it) {
1692                         int num_lines = (*it)->write(os.os(), true);
1693                         os.texrow().newlines(num_lines);
1694                 }
1695
1696         } // output_preamble
1697
1698         os.texrow().start(paragraphs().begin()->id(), 0);
1699
1700         LYXERR(Debug::INFO, "preamble finished, now the body.");
1701
1702         // the real stuff
1703         latexParagraphs(*this, text(), os, runparams);
1704
1705         // Restore the parenthood if needed
1706         if (!runparams.is_child)
1707                 d->ignore_parent = false;
1708
1709         // add this just in case after all the paragraphs
1710         os << endl;
1711
1712         if (output_preamble) {
1713                 os << "\\end{document}\n";
1714                 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1715         } else {
1716                 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1717         }
1718         runparams_in.encoding = runparams.encoding;
1719
1720         // Just to be sure. (Asger)
1721         os.texrow().newline();
1722
1723         //for (int i = 0; i<d->texrow.rows(); i++) {
1724         // int id,pos;
1725         // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1726         //      lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1727         //}
1728
1729         LYXERR(Debug::INFO, "Finished making LaTeX file.");
1730         LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1731 }
1732
1733
1734 void Buffer::makeDocBookFile(FileName const & fname,
1735                               OutputParams const & runparams,
1736                               OutputWhat output) const
1737 {
1738         LYXERR(Debug::LATEX, "makeDocBookFile...");
1739
1740         ofdocstream ofs;
1741         if (!openFileWrite(ofs, fname))
1742                 return;
1743
1744         // make sure we are ready to export
1745         // this needs to be done before we validate
1746         updateBuffer();
1747         updateMacroInstances(OutputUpdate);
1748
1749         writeDocBookSource(ofs, fname.absFileName(), runparams, output);
1750
1751         ofs.close();
1752         if (ofs.fail())
1753                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1754 }
1755
1756
1757 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1758                              OutputParams const & runparams,
1759                              OutputWhat output) const
1760 {
1761         LaTeXFeatures features(*this, params(), runparams);
1762         validate(features);
1763
1764         d->texrow.reset();
1765
1766         DocumentClass const & tclass = params().documentClass();
1767         string const top_element = tclass.latexname();
1768
1769         bool const output_preamble =
1770                 output == FullSource || output == OnlyPreamble;
1771         bool const output_body =
1772           output == FullSource || output == OnlyBody;
1773
1774         if (output_preamble) {
1775                 if (runparams.flavor == OutputParams::XML)
1776                         os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1777
1778                 // FIXME UNICODE
1779                 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1780
1781                 // FIXME UNICODE
1782                 if (! tclass.class_header().empty())
1783                         os << from_ascii(tclass.class_header());
1784                 else if (runparams.flavor == OutputParams::XML)
1785                         os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1786                             << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1787                 else
1788                         os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1789
1790                 docstring preamble = from_utf8(params().preamble);
1791                 if (runparams.flavor != OutputParams::XML ) {
1792                         preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1793                         preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1794                         preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1795                         preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1796                 }
1797
1798                 string const name = runparams.nice
1799                         ? changeExtension(absFileName(), ".sgml") : fname;
1800                 preamble += features.getIncludedFiles(name);
1801                 preamble += features.getLyXSGMLEntities();
1802
1803                 if (!preamble.empty()) {
1804                         os << "\n [ " << preamble << " ]";
1805                 }
1806                 os << ">\n\n";
1807         }
1808
1809         if (output_body) {
1810                 string top = top_element;
1811                 top += " lang=\"";
1812                 if (runparams.flavor == OutputParams::XML)
1813                         top += params().language->code();
1814                 else
1815                         top += params().language->code().substr(0, 2);
1816                 top += '"';
1817
1818                 if (!params().options.empty()) {
1819                         top += ' ';
1820                         top += params().options;
1821                 }
1822
1823                 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1824                                 << " file was created by LyX " << lyx_version
1825                                 << "\n  See http://www.lyx.org/ for more information -->\n";
1826
1827                 params().documentClass().counters().reset();
1828
1829                 sgml::openTag(os, top);
1830                 os << '\n';
1831                 docbookParagraphs(text(), *this, os, runparams);
1832                 sgml::closeTag(os, top_element);
1833         }
1834 }
1835
1836
1837 void Buffer::makeLyXHTMLFile(FileName const & fname,
1838                               OutputParams const & runparams) const
1839 {
1840         LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1841
1842         ofdocstream ofs;
1843         if (!openFileWrite(ofs, fname))
1844                 return;
1845
1846         // make sure we are ready to export
1847         // this has to be done before we validate
1848         updateBuffer(UpdateMaster, OutputUpdate);
1849         updateMacroInstances(OutputUpdate);
1850
1851         writeLyXHTMLSource(ofs, runparams, FullSource);
1852
1853         ofs.close();
1854         if (ofs.fail())
1855                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1856 }
1857
1858
1859 void Buffer::writeLyXHTMLSource(odocstream & os,
1860                              OutputParams const & runparams,
1861                              OutputWhat output) const
1862 {
1863         LaTeXFeatures features(*this, params(), runparams);
1864         validate(features);
1865         d->bibinfo_.makeCitationLabels(*this);
1866
1867         bool const output_preamble =
1868                 output == FullSource || output == OnlyPreamble;
1869         bool const output_body =
1870           output == FullSource || output == OnlyBody || output == IncludedFile;
1871
1872         if (output_preamble) {
1873                 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1874                    << "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN\" \"http://www.w3.org/Math/DTD/mathml2/xhtml-math11-f.dtd\">\n"
1875                    // FIXME Language should be set properly.
1876                    << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1877                    << "<head>\n"
1878                    << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1879                    // FIXME Presumably need to set this right
1880                    << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1881
1882                 docstring const & doctitle = features.htmlTitle();
1883                 os << "<title>"
1884                    << (doctitle.empty() ?
1885                          from_ascii("LyX Document") :
1886                          html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
1887                    << "</title>\n";
1888
1889                 docstring styles = features.getTClassHTMLPreamble();
1890                 if (!styles.empty())
1891                         os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
1892
1893                 styles = from_utf8(features.getPreambleSnippets());
1894                 if (!styles.empty())
1895                         os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
1896
1897                 // we will collect CSS information in a stream, and then output it
1898                 // either here, as part of the header, or else in a separate file.
1899                 odocstringstream css;
1900                 styles = from_utf8(features.getCSSSnippets());
1901                 if (!styles.empty())
1902                         css << "/* LyX Provided Styles */\n" << styles << '\n';
1903
1904                 styles = features.getTClassHTMLStyles();
1905                 if (!styles.empty())
1906                         css << "/* Layout-provided Styles */\n" << styles << '\n';
1907
1908                 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
1909                 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
1910                 if (needfg || needbg) {
1911                                 css << "\nbody {\n";
1912                                 if (needfg)
1913                                    css << "  color: "
1914                                             << from_ascii(X11hexname(params().fontcolor))
1915                                             << ";\n";
1916                                 if (needbg)
1917                                    css << "  background-color: "
1918                                             << from_ascii(X11hexname(params().backgroundcolor))
1919                                             << ";\n";
1920                                 css << "}\n";
1921                 }
1922
1923                 docstring const dstyles = css.str();
1924                 if (!dstyles.empty()) {
1925                         bool written = false;
1926                         if (params().html_css_as_file) {
1927                                 // open a file for CSS info
1928                                 ofdocstream ocss;
1929                                 string const fcssname = addName(temppath(), "docstyle.css");
1930                                 FileName const fcssfile = FileName(fcssname);
1931                                 if (openFileWrite(ocss, fcssfile)) {
1932                                         ocss << dstyles;
1933                                         ocss.close();
1934                                         written = true;
1935                                         // write link to header
1936                                         os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
1937                                         // register file
1938                                         runparams.exportdata->addExternalFile("xhtml", fcssfile);
1939                                 }
1940                         }
1941                         // we are here if the CSS is supposed to be written to the header
1942                         // or if we failed to write it to an external file.
1943                         if (!written) {
1944                                 os << "<style type='text/css'>\n"
1945                                          << dstyles
1946                                          << "\n</style>\n";
1947                         }
1948                 }
1949                 os << "</head>\n";
1950         }
1951
1952         if (output_body) {
1953                 bool const output_body_tag = (output != IncludedFile);
1954                 if (output_body_tag)
1955                         os << "<body>\n";
1956                 XHTMLStream xs(os);
1957                 if (output != IncludedFile)
1958                         // if we're an included file, the counters are in the master.
1959                         params().documentClass().counters().reset();
1960                 xhtmlParagraphs(text(), *this, xs, runparams);
1961                 if (output_body_tag)
1962                         os << "</body>\n";
1963         }
1964
1965         if (output_preamble)
1966                 os << "</html>\n";
1967 }
1968
1969
1970 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1971 // Other flags: -wall -v0 -x
1972 int Buffer::runChktex()
1973 {
1974         setBusy(true);
1975
1976         // get LaTeX-Filename
1977         FileName const path(temppath());
1978         string const name = addName(path.absFileName(), latexName());
1979         string const org_path = filePath();
1980
1981         PathChanger p(path); // path to LaTeX file
1982         message(_("Running chktex..."));
1983
1984         // Generate the LaTeX file if neccessary
1985         OutputParams runparams(&params().encoding());
1986         runparams.flavor = OutputParams::LATEX;
1987         runparams.nice = false;
1988         runparams.linelen = lyxrc.plaintext_linelen;
1989         makeLaTeXFile(FileName(name), org_path, runparams);
1990
1991         TeXErrors terr;
1992         Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
1993         int const res = chktex.run(terr); // run chktex
1994
1995         if (res == -1) {
1996                 Alert::error(_("chktex failure"),
1997                              _("Could not run chktex successfully."));
1998         } else {
1999                 ErrorList & errlist = d->errorLists["ChkTeX"];
2000                 errlist.clear();
2001                 bufferErrors(terr, errlist);
2002         }
2003
2004         setBusy(false);
2005
2006         if (runparams.silent)
2007                 d->errorLists["ChkTeX"].clear();
2008         else
2009                 errors("ChkTeX");
2010
2011         return res;
2012 }
2013
2014
2015 void Buffer::validate(LaTeXFeatures & features) const
2016 {
2017         // Validate the buffer params, but not for included
2018         // files, since they also use the parent buffer's
2019         // params (# 5941)
2020         if (!features.runparams().is_child)
2021                 params().validate(features);
2022
2023         for_each(paragraphs().begin(), paragraphs().end(),
2024                  bind(&Paragraph::validate, _1, ref(features)));
2025
2026         if (lyxerr.debugging(Debug::LATEX)) {
2027                 features.showStruct();
2028         }
2029 }
2030
2031
2032 void Buffer::getLabelList(vector<docstring> & list) const
2033 {
2034         // If this is a child document, use the master's list instead.
2035         if (parent()) {
2036                 masterBuffer()->getLabelList(list);
2037                 return;
2038         }
2039
2040         list.clear();
2041         Toc & toc = d->toc_backend.toc("label");
2042         TocIterator toc_it = toc.begin();
2043         TocIterator end = toc.end();
2044         for (; toc_it != end; ++toc_it) {
2045                 if (toc_it->depth() == 0)
2046                         list.push_back(toc_it->str());
2047         }
2048 }
2049
2050
2051 void Buffer::updateBibfilesCache(UpdateScope scope) const
2052 {
2053         // FIXME This is probably unnecssary, given where we call this.
2054         // If this is a child document, use the parent's cache instead.
2055         if (parent() && scope != UpdateChildOnly) {
2056                 masterBuffer()->updateBibfilesCache();
2057                 return;
2058         }
2059
2060         d->bibfiles_cache_.clear();
2061         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2062                 if (it->lyxCode() == BIBTEX_CODE) {
2063                         InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
2064                         support::FileNameList const bibfiles = inset.getBibFiles();
2065                         d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2066                                 bibfiles.begin(),
2067                                 bibfiles.end());
2068                 } else if (it->lyxCode() == INCLUDE_CODE) {
2069                         InsetInclude & inset = static_cast<InsetInclude &>(*it);
2070                         Buffer const * const incbuf = inset.getChildBuffer();
2071                         if (!incbuf)
2072                                 continue;
2073                         support::FileNameList const & bibfiles =
2074                                         incbuf->getBibfilesCache(UpdateChildOnly);
2075                         if (!bibfiles.empty()) {
2076                                 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2077                                         bibfiles.begin(),
2078                                         bibfiles.end());
2079                         }
2080                 }
2081         }
2082         d->bibfile_cache_valid_ = true;
2083         d->bibinfo_cache_valid_ = false;
2084         d->cite_labels_valid_ = false;
2085 }
2086
2087
2088 void Buffer::invalidateBibinfoCache() const
2089 {
2090         d->bibinfo_cache_valid_ = false;
2091         d->cite_labels_valid_ = false;
2092         // also invalidate the cache for the parent buffer
2093         Buffer const * const pbuf = d->parent();
2094         if (pbuf)
2095                 pbuf->invalidateBibinfoCache();
2096 }
2097
2098
2099 void Buffer::invalidateBibfileCache() const
2100 {
2101         d->bibfile_cache_valid_ = false;
2102         d->bibinfo_cache_valid_ = false;
2103         d->cite_labels_valid_ = false;
2104         // also invalidate the cache for the parent buffer
2105         Buffer const * const pbuf = d->parent();
2106         if (pbuf)
2107                 pbuf->invalidateBibfileCache();
2108 }
2109
2110
2111 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
2112 {
2113         // FIXME This is probably unnecessary, given where we call this.
2114         // If this is a child document, use the master's cache instead.
2115         Buffer const * const pbuf = masterBuffer();
2116         if (pbuf != this && scope != UpdateChildOnly)
2117                 return pbuf->getBibfilesCache();
2118
2119         if (!d->bibfile_cache_valid_)
2120                 this->updateBibfilesCache(scope);
2121
2122         return d->bibfiles_cache_;
2123 }
2124
2125
2126 BiblioInfo const & Buffer::masterBibInfo() const
2127 {
2128         Buffer const * const tmp = masterBuffer();
2129         if (tmp != this)
2130                 return tmp->masterBibInfo();
2131         return d->bibinfo_;
2132 }
2133
2134
2135 void Buffer::checkIfBibInfoCacheIsValid() const
2136 {
2137         // use the master's cache
2138         Buffer const * const tmp = masterBuffer();
2139         if (tmp != this) {
2140                 tmp->checkIfBibInfoCacheIsValid();
2141                 return;
2142         }
2143
2144         // compare the cached timestamps with the actual ones.
2145         FileNameList const & bibfiles_cache = getBibfilesCache();
2146         FileNameList::const_iterator ei = bibfiles_cache.begin();
2147         FileNameList::const_iterator en = bibfiles_cache.end();
2148         for (; ei != en; ++ ei) {
2149                 time_t lastw = ei->lastModified();
2150                 time_t prevw = d->bibfile_status_[*ei];
2151                 if (lastw != prevw) {
2152                         d->bibinfo_cache_valid_ = false;
2153                         d->cite_labels_valid_ = false;
2154                         d->bibfile_status_[*ei] = lastw;
2155                 }
2156         }
2157 }
2158
2159
2160 void Buffer::reloadBibInfoCache() const
2161 {
2162         // use the master's cache
2163         Buffer const * const tmp = masterBuffer();
2164         if (tmp != this) {
2165                 tmp->reloadBibInfoCache();
2166                 return;
2167         }
2168
2169         checkIfBibInfoCacheIsValid();
2170         if (d->bibinfo_cache_valid_)
2171                 return;
2172
2173         d->bibinfo_.clear();
2174         collectBibKeys();
2175         d->bibinfo_cache_valid_ = true;
2176 }
2177
2178
2179 void Buffer::collectBibKeys() const
2180 {
2181         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2182                 it->collectBibKeys(it);
2183 }
2184
2185
2186 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
2187 {
2188         Buffer const * tmp = masterBuffer();
2189         BiblioInfo & masterbi = (tmp == this) ?
2190                 d->bibinfo_ : tmp->d->bibinfo_;
2191         masterbi.mergeBiblioInfo(bi);
2192 }
2193
2194
2195 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
2196 {
2197         Buffer const * tmp = masterBuffer();
2198         BiblioInfo & masterbi = (tmp == this) ?
2199                 d->bibinfo_ : tmp->d->bibinfo_;
2200         masterbi[key] = bi;
2201 }
2202
2203
2204 void Buffer::makeCitationLabels() const
2205 {
2206         Buffer const * const master = masterBuffer();
2207         return d->bibinfo_.makeCitationLabels(*master);
2208 }
2209
2210
2211 bool Buffer::citeLabelsValid() const
2212 {
2213         return masterBuffer()->d->cite_labels_valid_;
2214 }
2215
2216
2217 void Buffer::removeBiblioTempFiles() const
2218 {
2219         // We remove files that contain LaTeX commands specific to the
2220         // particular bibliographic style being used, in order to avoid
2221         // LaTeX errors when we switch style.
2222         FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2223         FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2224         LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2225         aux_file.removeFile();
2226         LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2227         bbl_file.removeFile();
2228         // Also for the parent buffer
2229         Buffer const * const pbuf = parent();
2230         if (pbuf)
2231                 pbuf->removeBiblioTempFiles();
2232 }
2233
2234
2235 bool Buffer::isDepClean(string const & name) const
2236 {
2237         DepClean::const_iterator const it = d->dep_clean.find(name);
2238         if (it == d->dep_clean.end())
2239                 return true;
2240         return it->second;
2241 }
2242
2243
2244 void Buffer::markDepClean(string const & name)
2245 {
2246         d->dep_clean[name] = true;
2247 }
2248
2249
2250 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2251 {
2252         if (isInternal()) {
2253                 // FIXME? if there is an Buffer LFUN that can be dispatched even
2254                 // if internal, put a switch '(cmd.action)' here.
2255                 return false;
2256         }
2257
2258         bool enable = true;
2259
2260         switch (cmd.action()) {
2261
2262         case LFUN_BUFFER_TOGGLE_READ_ONLY:
2263                 flag.setOnOff(isReadonly());
2264                 break;
2265
2266                 // FIXME: There is need for a command-line import.
2267                 //case LFUN_BUFFER_IMPORT:
2268
2269         case LFUN_BUFFER_AUTO_SAVE:
2270                 break;
2271
2272         case LFUN_BUFFER_EXPORT_CUSTOM:
2273                 // FIXME: Nothing to check here?
2274                 break;
2275
2276         case LFUN_BUFFER_EXPORT: {
2277                 docstring const arg = cmd.argument();
2278                 if (arg == "custom") {
2279                         enable = true;
2280                         break;
2281                 }
2282                 string format = to_utf8(arg);
2283                 size_t pos = format.find(' ');
2284                 if (pos != string::npos)
2285                         format = format.substr(0, pos);
2286                 enable = params().isExportable(format);
2287                 if (!enable)
2288                         flag.message(bformat(
2289                                              _("Don't know how to export to format: %1$s"), arg));
2290                 break;
2291         }
2292
2293         case LFUN_BUFFER_CHKTEX:
2294                 enable = params().isLatex() && !lyxrc.chktex_command.empty();
2295                 break;
2296
2297         case LFUN_BUILD_PROGRAM:
2298                 enable = params().isExportable("program");
2299                 break;
2300
2301         case LFUN_BRANCH_ACTIVATE:
2302         case LFUN_BRANCH_DEACTIVATE:
2303         case LFUN_BRANCH_MASTER_ACTIVATE:
2304         case LFUN_BRANCH_MASTER_DEACTIVATE: {
2305                 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2306                                      || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2307                 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2308                         : params().branchlist();
2309                 docstring const branchName = cmd.argument();
2310                 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2311                 break;
2312         }
2313
2314         case LFUN_BRANCH_ADD:
2315         case LFUN_BRANCHES_RENAME:
2316         case LFUN_BUFFER_PRINT:
2317                 // if no Buffer is present, then of course we won't be called!
2318                 break;
2319
2320         case LFUN_BUFFER_LANGUAGE:
2321                 enable = !isReadonly();
2322                 break;
2323
2324         default:
2325                 return false;
2326         }
2327         flag.setEnabled(enable);
2328         return true;
2329 }
2330
2331
2332 void Buffer::dispatch(string const & command, DispatchResult & result)
2333 {
2334         return dispatch(lyxaction.lookupFunc(command), result);
2335 }
2336
2337
2338 // NOTE We can end up here even if we have no GUI, because we are called
2339 // by LyX::exec to handled command-line requests. So we may need to check
2340 // whether we have a GUI or not. The boolean use_gui holds this information.
2341 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2342 {
2343         if (isInternal()) {
2344                 // FIXME? if there is an Buffer LFUN that can be dispatched even
2345                 // if internal, put a switch '(cmd.action())' here.
2346                 dr.dispatched(false);
2347                 return;
2348         }
2349         string const argument = to_utf8(func.argument());
2350         // We'll set this back to false if need be.
2351         bool dispatched = true;
2352         undo().beginUndoGroup();
2353
2354         switch (func.action()) {
2355         case LFUN_BUFFER_TOGGLE_READ_ONLY:
2356                 if (lyxvc().inUse()) {
2357                         string log = lyxvc().toggleReadOnly();
2358                         if (!log.empty())
2359                                 dr.setMessage(log);
2360                 }
2361                 else
2362                         setReadonly(!isReadonly());
2363                 break;
2364
2365         case LFUN_BUFFER_EXPORT: {
2366                 ExportStatus const status = doExport(argument, false);
2367                 dr.setError(status != ExportSuccess);
2368                 if (status != ExportSuccess)
2369                         dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2370                                               func.argument()));
2371                 break;
2372         }
2373
2374         case LFUN_BUILD_PROGRAM: {
2375                 ExportStatus const status = doExport("program", true);
2376                 dr.setError(status != ExportSuccess);
2377                 if (status != ExportSuccess)
2378                         dr.setMessage(_("Error generating literate programming code."));
2379                 break;
2380         }
2381
2382         case LFUN_BUFFER_CHKTEX:
2383                 runChktex();
2384                 break;
2385
2386         case LFUN_BUFFER_EXPORT_CUSTOM: {
2387                 string format_name;
2388                 string command = split(argument, format_name, ' ');
2389                 Format const * format = formats.getFormat(format_name);
2390                 if (!format) {
2391                         lyxerr << "Format \"" << format_name
2392                                 << "\" not recognized!"
2393                                 << endl;
2394                         break;
2395                 }
2396
2397                 // The name of the file created by the conversion process
2398                 string filename;
2399
2400                 // Output to filename
2401                 if (format->name() == "lyx") {
2402                         string const latexname = latexName(false);
2403                         filename = changeExtension(latexname,
2404                                 format->extension());
2405                         filename = addName(temppath(), filename);
2406
2407                         if (!writeFile(FileName(filename)))
2408                                 break;
2409
2410                 } else {
2411                         doExport(format_name, true, filename);
2412                 }
2413
2414                 // Substitute $$FName for filename
2415                 if (!contains(command, "$$FName"))
2416                         command = "( " + command + " ) < $$FName";
2417                 command = subst(command, "$$FName", filename);
2418
2419                 // Execute the command in the background
2420                 Systemcall call;
2421                 call.startscript(Systemcall::DontWait, command, filePath());
2422                 break;
2423         }
2424
2425         // FIXME: There is need for a command-line import.
2426         /*
2427         case LFUN_BUFFER_IMPORT:
2428                 doImport(argument);
2429                 break;
2430         */
2431
2432         case LFUN_BUFFER_AUTO_SAVE:
2433                 autoSave();
2434                 resetAutosaveTimers();
2435                 break;
2436
2437         case LFUN_BRANCH_ACTIVATE:
2438         case LFUN_BRANCH_DEACTIVATE:
2439         case LFUN_BRANCH_MASTER_ACTIVATE:
2440         case LFUN_BRANCH_MASTER_DEACTIVATE: {
2441                 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2442                                      || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2443                 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2444                                       : this;
2445
2446                 docstring const branch_name = func.argument();
2447                 // the case without a branch name is handled elsewhere
2448                 if (branch_name.empty()) {
2449                         dispatched = false;
2450                         break;
2451                 }
2452                 Branch * branch = buf->params().branchlist().find(branch_name);
2453                 if (!branch) {
2454                         LYXERR0("Branch " << branch_name << " does not exist.");
2455                         dr.setError(true);
2456                         docstring const msg =
2457                                 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2458                         dr.setMessage(msg);
2459                         break;
2460                 }
2461                 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2462                                        || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2463                 if (branch->isSelected() != activate) {
2464                         buf->undo().recordUndoFullDocument(CursorData());
2465                         branch->setSelected(activate);
2466                         dr.setError(false);
2467                         dr.screenUpdate(Update::Force);
2468                         dr.forceBufferUpdate();
2469                 }
2470                 break;
2471         }
2472
2473         case LFUN_BRANCH_ADD: {
2474                 docstring branch_name = func.argument();
2475                 if (branch_name.empty()) {
2476                         dispatched = false;
2477                         break;
2478                 }
2479                 BranchList & branch_list = params().branchlist();
2480                 vector<docstring> const branches =
2481                         getVectorFromString(branch_name, branch_list.separator());
2482                 docstring msg;
2483                 for (vector<docstring>::const_iterator it = branches.begin();
2484                      it != branches.end(); ++it) {
2485                         branch_name = *it;
2486                         Branch * branch = branch_list.find(branch_name);
2487                         if (branch) {
2488                                 LYXERR0("Branch " << branch_name << " already exists.");
2489                                 dr.setError(true);
2490                                 if (!msg.empty())
2491                                         msg += ("\n");
2492                                 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2493                         } else {
2494                                 branch_list.add(branch_name);
2495                                 branch = branch_list.find(branch_name);
2496                                 string const x11hexname = X11hexname(branch->color());
2497                                 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2498                                 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2499                                 dr.setError(false);
2500                                 dr.screenUpdate(Update::Force);
2501                         }
2502                 }
2503                 if (!msg.empty())
2504                         dr.setMessage(msg);
2505                 break;
2506         }
2507
2508         case LFUN_BRANCHES_RENAME: {
2509                 if (func.argument().empty())
2510                         break;
2511
2512                 docstring const oldname = from_utf8(func.getArg(0));
2513                 docstring const newname = from_utf8(func.getArg(1));
2514                 InsetIterator it  = inset_iterator_begin(inset());
2515                 InsetIterator const end = inset_iterator_end(inset());
2516                 bool success = false;
2517                 for (; it != end; ++it) {
2518                         if (it->lyxCode() == BRANCH_CODE) {
2519                                 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2520                                 if (ins.branch() == oldname) {
2521                                         undo().recordUndo(CursorData(it));
2522                                         ins.rename(newname);
2523                                         success = true;
2524                                         continue;
2525                                 }
2526                         }
2527                         if (it->lyxCode() == INCLUDE_CODE) {
2528                                 // get buffer of external file
2529                                 InsetInclude const & ins =
2530                                         static_cast<InsetInclude const &>(*it);
2531                                 Buffer * child = ins.getChildBuffer();
2532                                 if (!child)
2533                                         continue;
2534                                 child->dispatch(func, dr);
2535                         }
2536                 }
2537
2538                 if (success) {
2539                         dr.screenUpdate(Update::Force);
2540                         dr.forceBufferUpdate();
2541                 }
2542                 break;
2543         }
2544
2545         case LFUN_BUFFER_PRINT: {
2546                 // we'll assume there's a problem until we succeed
2547                 dr.setError(true);
2548                 string target = func.getArg(0);
2549                 string target_name = func.getArg(1);
2550                 string command = func.getArg(2);
2551
2552                 if (target.empty()
2553                     || target_name.empty()
2554                     || command.empty()) {
2555                         LYXERR0("Unable to parse " << func.argument());
2556                         docstring const msg =
2557                                 bformat(_("Unable to parse \"%1$s\""), func.argument());
2558                         dr.setMessage(msg);
2559                         break;
2560                 }
2561                 if (target != "printer" && target != "file") {
2562                         LYXERR0("Unrecognized target \"" << target << '"');
2563                         docstring const msg =
2564                                 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2565                         dr.setMessage(msg);
2566                         break;
2567                 }
2568
2569                 if (doExport("dvi", true) != ExportSuccess) {
2570                         showPrintError(absFileName());
2571                         dr.setMessage(_("Error exporting to DVI."));
2572                         break;
2573                 }
2574
2575                 // Push directory path.
2576                 string const path = temppath();
2577                 // Prevent the compiler from optimizing away p
2578                 FileName pp(path);
2579                 PathChanger p(pp);
2580
2581                 // there are three cases here:
2582                 // 1. we print to a file
2583                 // 2. we print directly to a printer
2584                 // 3. we print using a spool command (print to file first)
2585                 Systemcall one;
2586                 int res = 0;
2587                 string const dviname = changeExtension(latexName(true), "dvi");
2588
2589                 if (target == "printer") {
2590                         if (!lyxrc.print_spool_command.empty()) {
2591                                 // case 3: print using a spool
2592                                 string const psname = changeExtension(dviname,".ps");
2593                                 command += ' ' + lyxrc.print_to_file
2594                                         + quoteName(psname)
2595                                         + ' '
2596                                         + quoteName(dviname);
2597
2598                                 string command2 = lyxrc.print_spool_command + ' ';
2599                                 if (target_name != "default") {
2600                                         command2 += lyxrc.print_spool_printerprefix
2601                                                 + target_name
2602                                                 + ' ';
2603                                 }
2604                                 command2 += quoteName(psname);
2605                                 // First run dvips.
2606                                 // If successful, then spool command
2607                                 res = one.startscript(Systemcall::Wait, command,
2608                                                       filePath());
2609
2610                                 if (res == 0) {
2611                                         // If there's no GUI, we have to wait on this command. Otherwise,
2612                                         // LyX deletes the temporary directory, and with it the spooled
2613                                         // file, before it can be printed!!
2614                                         Systemcall::Starttype stype = use_gui ?
2615                                                 Systemcall::DontWait : Systemcall::Wait;
2616                                         res = one.startscript(stype, command2,
2617                                                               filePath());
2618                                 }
2619                         } else {
2620                                 // case 2: print directly to a printer
2621                                 if (target_name != "default")
2622                                         command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2623                                 // as above....
2624                                 Systemcall::Starttype stype = use_gui ?
2625                                         Systemcall::DontWait : Systemcall::Wait;
2626                                 res = one.startscript(stype, command +
2627                                                 quoteName(dviname), filePath());
2628                         }
2629
2630                 } else {
2631                         // case 1: print to a file
2632                         FileName const filename(makeAbsPath(target_name, filePath()));
2633                         FileName const dvifile(makeAbsPath(dviname, path));
2634                         if (filename.exists()) {
2635                                 docstring text = bformat(
2636                                         _("The file %1$s already exists.\n\n"
2637                                           "Do you want to overwrite that file?"),
2638                                         makeDisplayPath(filename.absFileName()));
2639                                 if (Alert::prompt(_("Overwrite file?"),
2640                                                   text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2641                                         break;
2642                         }
2643                         command += ' ' + lyxrc.print_to_file
2644                                 + quoteName(filename.toFilesystemEncoding())
2645                                 + ' '
2646                                 + quoteName(dvifile.toFilesystemEncoding());
2647                         // as above....
2648                         Systemcall::Starttype stype = use_gui ?
2649                                 Systemcall::DontWait : Systemcall::Wait;
2650                         res = one.startscript(stype, command, filePath());
2651                 }
2652
2653                 if (res == 0)
2654                         dr.setError(false);
2655                 else {
2656                         dr.setMessage(_("Error running external commands."));
2657                         showPrintError(absFileName());
2658                 }
2659                 break;
2660         }
2661
2662         default:
2663                 dispatched = false;
2664                 break;
2665         }
2666         dr.dispatched(dispatched);
2667         undo().endUndoGroup();
2668 }
2669
2670
2671 void Buffer::changeLanguage(Language const * from, Language const * to)
2672 {
2673         LASSERT(from, return);
2674         LASSERT(to, return);
2675
2676         for_each(par_iterator_begin(),
2677                  par_iterator_end(),
2678                  bind(&Paragraph::changeLanguage, _1, params(), from, to));
2679 }
2680
2681
2682 bool Buffer::isMultiLingual() const
2683 {
2684         ParConstIterator end = par_iterator_end();
2685         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2686                 if (it->isMultiLingual(params()))
2687                         return true;
2688
2689         return false;
2690 }
2691
2692
2693 std::set<Language const *> Buffer::getLanguages() const
2694 {
2695         std::set<Language const *> languages;
2696         getLanguages(languages);
2697         return languages;
2698 }
2699
2700
2701 void Buffer::getLanguages(std::set<Language const *> & languages) const
2702 {
2703         ParConstIterator end = par_iterator_end();
2704         // add the buffer language, even if it's not actively used
2705         languages.insert(language());
2706         // iterate over the paragraphs
2707         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2708                 it->getLanguages(languages);
2709         // also children
2710         ListOfBuffers clist = getDescendents();
2711         ListOfBuffers::const_iterator cit = clist.begin();
2712         ListOfBuffers::const_iterator const cen = clist.end();
2713         for (; cit != cen; ++cit)
2714                 (*cit)->getLanguages(languages);
2715 }
2716
2717
2718 DocIterator Buffer::getParFromID(int const id) const
2719 {
2720         Buffer * buf = const_cast<Buffer *>(this);
2721         if (id < 0) {
2722                 // John says this is called with id == -1 from undo
2723                 lyxerr << "getParFromID(), id: " << id << endl;
2724                 return doc_iterator_end(buf);
2725         }
2726
2727         for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2728                 if (it.paragraph().id() == id)
2729                         return it;
2730
2731         return doc_iterator_end(buf);
2732 }
2733
2734
2735 bool Buffer::hasParWithID(int const id) const
2736 {
2737         return !getParFromID(id).atEnd();
2738 }
2739
2740
2741 ParIterator Buffer::par_iterator_begin()
2742 {
2743         return ParIterator(doc_iterator_begin(this));
2744 }
2745
2746
2747 ParIterator Buffer::par_iterator_end()
2748 {
2749         return ParIterator(doc_iterator_end(this));
2750 }
2751
2752
2753 ParConstIterator Buffer::par_iterator_begin() const
2754 {
2755         return ParConstIterator(doc_iterator_begin(this));
2756 }
2757
2758
2759 ParConstIterator Buffer::par_iterator_end() const
2760 {
2761         return ParConstIterator(doc_iterator_end(this));
2762 }
2763
2764
2765 Language const * Buffer::language() const
2766 {
2767         return params().language;
2768 }
2769
2770
2771 docstring const Buffer::B_(string const & l10n) const
2772 {
2773         return params().B_(l10n);
2774 }
2775
2776
2777 bool Buffer::isClean() const
2778 {
2779         return d->lyx_clean;
2780 }
2781
2782
2783 bool Buffer::isExternallyModified(CheckMethod method) const
2784 {
2785         LASSERT(d->filename.exists(), return false);
2786         // if method == timestamp, check timestamp before checksum
2787         return (method == checksum_method
2788                 || d->timestamp_ != d->filename.lastModified())
2789                 && d->checksum_ != d->filename.checksum();
2790 }
2791
2792
2793 void Buffer::saveCheckSum() const
2794 {
2795         FileName const & file = d->filename;
2796
2797         file.refresh();
2798         if (file.exists()) {
2799                 d->timestamp_ = file.lastModified();
2800                 d->checksum_ = file.checksum();
2801         } else {
2802                 // in the case of save to a new file.
2803                 d->timestamp_ = 0;
2804                 d->checksum_ = 0;
2805         }
2806 }
2807
2808
2809 void Buffer::markClean() const
2810 {
2811         if (!d->lyx_clean) {
2812                 d->lyx_clean = true;
2813                 updateTitles();
2814         }
2815         // if the .lyx file has been saved, we don't need an
2816         // autosave
2817         d->bak_clean = true;
2818         d->undo_.markDirty();
2819 }
2820
2821
2822 void Buffer::setUnnamed(bool flag)
2823 {
2824         d->unnamed = flag;
2825 }
2826
2827
2828 bool Buffer::isUnnamed() const
2829 {
2830         return d->unnamed;
2831 }
2832
2833
2834 /// \note
2835 /// Don't check unnamed, here: isInternal() is used in
2836 /// newBuffer(), where the unnamed flag has not been set by anyone
2837 /// yet. Also, for an internal buffer, there should be no need for
2838 /// retrieving fileName() nor for checking if it is unnamed or not.
2839 bool Buffer::isInternal() const
2840 {
2841         return d->internal_buffer;
2842 }
2843
2844
2845 void Buffer::setInternal(bool flag)
2846 {
2847         d->internal_buffer = flag;
2848 }
2849
2850
2851 void Buffer::markDirty()
2852 {
2853         if (d->lyx_clean) {
2854                 d->lyx_clean = false;
2855                 updateTitles();
2856         }
2857         d->bak_clean = false;
2858
2859         DepClean::iterator it = d->dep_clean.begin();
2860         DepClean::const_iterator const end = d->dep_clean.end();
2861
2862         for (; it != end; ++it)
2863                 it->second = false;
2864 }
2865
2866
2867 FileName Buffer::fileName() const
2868 {
2869         return d->filename;
2870 }
2871
2872
2873 string Buffer::absFileName() const
2874 {
2875         return d->filename.absFileName();
2876 }
2877
2878
2879 string Buffer::filePath() const
2880 {
2881         string const abs = d->filename.onlyPath().absFileName();
2882         if (abs.empty())
2883                 return abs;
2884         int last = abs.length() - 1;
2885
2886         return abs[last] == '/' ? abs : abs + '/';
2887 }
2888
2889
2890 bool Buffer::isReadonly() const
2891 {
2892         return d->read_only;
2893 }
2894
2895
2896 void Buffer::setParent(Buffer const * buffer)
2897 {
2898         // Avoids recursive include.
2899         d->setParent(buffer == this ? 0 : buffer);
2900         updateMacros();
2901 }
2902
2903
2904 Buffer const * Buffer::parent() const
2905 {
2906         return d->parent();
2907 }
2908
2909
2910 ListOfBuffers Buffer::allRelatives() const
2911 {
2912         ListOfBuffers lb = masterBuffer()->getDescendents();
2913         lb.push_front(const_cast<Buffer *>(masterBuffer()));
2914         return lb;
2915 }
2916
2917
2918 Buffer const * Buffer::masterBuffer() const
2919 {
2920         // FIXME Should be make sure we are not in some kind
2921         // of recursive include? A -> B -> A will crash this.
2922         Buffer const * const pbuf = d->parent();
2923         if (!pbuf)
2924                 return this;
2925
2926         return pbuf->masterBuffer();
2927 }
2928
2929
2930 bool Buffer::isChild(Buffer * child) const
2931 {
2932         return d->children_positions.find(child) != d->children_positions.end();
2933 }
2934
2935
2936 DocIterator Buffer::firstChildPosition(Buffer const * child)
2937 {
2938         Impl::BufferPositionMap::iterator it;
2939         it = d->children_positions.find(child);
2940         if (it == d->children_positions.end())
2941                 return DocIterator(this);
2942         return it->second;
2943 }
2944
2945
2946 bool Buffer::hasChildren() const
2947 {
2948         return !d->children_positions.empty();
2949 }
2950
2951
2952 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
2953 {
2954         // loop over children
2955         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2956         Impl::BufferPositionMap::iterator end = d->children_positions.end();
2957         for (; it != end; ++it) {
2958                 Buffer * child = const_cast<Buffer *>(it->first);
2959                 // No duplicates
2960                 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
2961                 if (bit != clist.end())
2962                         continue;
2963                 clist.push_back(child);
2964                 if (grand_children)
2965                         // there might be grandchildren
2966                         child->collectChildren(clist, true);
2967         }
2968 }
2969
2970
2971 ListOfBuffers Buffer::getChildren() const
2972 {
2973         ListOfBuffers v;
2974         collectChildren(v, false);
2975         // Make sure we have not included ourselves.
2976         ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
2977         if (bit != v.end()) {
2978                 LYXERR0("Recursive include detected in `" << fileName() << "'.");
2979                 v.erase(bit);
2980         }
2981         return v;
2982 }
2983
2984
2985 ListOfBuffers Buffer::getDescendents() const
2986 {
2987         ListOfBuffers v;
2988         collectChildren(v, true);
2989         // Make sure we have not included ourselves.
2990         ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
2991         if (bit != v.end()) {
2992                 LYXERR0("Recursive include detected in `" << fileName() << "'.");
2993                 v.erase(bit);
2994         }
2995         return v;
2996 }
2997
2998
2999 template<typename M>
3000 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3001 {
3002         if (m.empty())
3003                 return m.end();
3004
3005         typename M::const_iterator it = m.lower_bound(x);
3006         if (it == m.begin())
3007                 return m.end();
3008
3009         it--;
3010         return it;
3011 }
3012
3013
3014 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3015                                          DocIterator const & pos) const
3016 {
3017         LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3018
3019         // if paragraphs have no macro context set, pos will be empty
3020         if (pos.empty())
3021                 return 0;
3022
3023         // we haven't found anything yet
3024         DocIterator bestPos = owner_->par_iterator_begin();
3025         MacroData const * bestData = 0;
3026
3027         // find macro definitions for name
3028         NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3029         if (nameIt != macros.end()) {
3030                 // find last definition in front of pos or at pos itself
3031                 PositionScopeMacroMap::const_iterator it
3032                         = greatest_below(nameIt->second, pos);
3033                 if (it != nameIt->second.end()) {
3034                         while (true) {
3035                                 // scope ends behind pos?
3036                                 if (pos < it->second.first) {
3037                                         // Looks good, remember this. If there
3038                                         // is no external macro behind this,
3039                                         // we found the right one already.
3040                                         bestPos = it->first;
3041                                         bestData = &it->second.second;
3042                                         break;
3043                                 }
3044
3045                                 // try previous macro if there is one
3046                                 if (it == nameIt->second.begin())
3047                                         break;
3048                                 --it;
3049                         }
3050                 }
3051         }
3052
3053         // find macros in included files
3054         PositionScopeBufferMap::const_iterator it
3055                 = greatest_below(position_to_children, pos);
3056         if (it == position_to_children.end())
3057                 // no children before
3058                 return bestData;
3059
3060         while (true) {
3061                 // do we know something better (i.e. later) already?
3062                 if (it->first < bestPos )
3063                         break;
3064
3065                 // scope ends behind pos?
3066                 if (pos < it->second.first
3067                         && (cloned_buffer_ ||
3068                             theBufferList().isLoaded(it->second.second))) {
3069                         // look for macro in external file
3070                         macro_lock = true;
3071                         MacroData const * data
3072                                 = it->second.second->getMacro(name, false);
3073                         macro_lock = false;
3074                         if (data) {
3075                                 bestPos = it->first;
3076                                 bestData = data;
3077                                 break;
3078                         }
3079                 }
3080
3081                 // try previous file if there is one
3082                 if (it == position_to_children.begin())
3083                         break;
3084                 --it;
3085         }
3086
3087         // return the best macro we have found
3088         return bestData;
3089 }
3090
3091
3092 MacroData const * Buffer::getMacro(docstring const & name,
3093         DocIterator const & pos, bool global) const
3094 {
3095         if (d->macro_lock)
3096                 return 0;
3097
3098         // query buffer macros
3099         MacroData const * data = d->getBufferMacro(name, pos);
3100         if (data != 0)
3101                 return data;
3102
3103         // If there is a master buffer, query that
3104         Buffer const * const pbuf = d->parent();
3105         if (pbuf) {
3106                 d->macro_lock = true;
3107                 MacroData const * macro = pbuf->getMacro(
3108                         name, *this, false);
3109                 d->macro_lock = false;
3110                 if (macro)
3111                         return macro;
3112         }
3113
3114         if (global) {
3115                 data = MacroTable::globalMacros().get(name);
3116                 if (data != 0)
3117                         return data;
3118         }
3119
3120         return 0;
3121 }
3122
3123
3124 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3125 {
3126         // set scope end behind the last paragraph
3127         DocIterator scope = par_iterator_begin();
3128         scope.pit() = scope.lastpit() + 1;
3129
3130         return getMacro(name, scope, global);
3131 }
3132
3133
3134 MacroData const * Buffer::getMacro(docstring const & name,
3135         Buffer const & child, bool global) const
3136 {
3137         // look where the child buffer is included first
3138         Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3139         if (it == d->children_positions.end())
3140                 return 0;
3141
3142         // check for macros at the inclusion position
3143         return getMacro(name, it->second, global);
3144 }
3145
3146
3147 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3148 {
3149         pit_type const lastpit = it.lastpit();
3150
3151         // look for macros in each paragraph
3152         while (it.pit() <= lastpit) {
3153                 Paragraph & par = it.paragraph();
3154
3155                 // iterate over the insets of the current paragraph
3156                 InsetList const & insets = par.insetList();
3157                 InsetList::const_iterator iit = insets.begin();
3158                 InsetList::const_iterator end = insets.end();
3159                 for (; iit != end; ++iit) {
3160                         it.pos() = iit->pos;
3161
3162                         // is it a nested text inset?
3163                         if (iit->inset->asInsetText()) {
3164                                 // Inset needs its own scope?
3165                                 InsetText const * itext = iit->inset->asInsetText();
3166                                 bool newScope = itext->isMacroScope();
3167
3168                                 // scope which ends just behind the inset
3169                                 DocIterator insetScope = it;
3170                                 ++insetScope.pos();
3171
3172                                 // collect macros in inset
3173                                 it.push_back(CursorSlice(*iit->inset));
3174                                 updateMacros(it, newScope ? insetScope : scope);
3175                                 it.pop_back();
3176                                 continue;
3177                         }
3178
3179                         if (iit->inset->asInsetTabular()) {
3180                                 CursorSlice slice(*iit->inset);
3181                                 size_t const numcells = slice.nargs();
3182                                 for (; slice.idx() < numcells; slice.forwardIdx()) {
3183                                         it.push_back(slice);
3184                                         updateMacros(it, scope);
3185                                         it.pop_back();
3186                                 }
3187                                 continue;
3188                         }
3189
3190                         // is it an external file?
3191                         if (iit->inset->lyxCode() == INCLUDE_CODE) {
3192                                 // get buffer of external file
3193                                 InsetInclude const & inset =
3194                                         static_cast<InsetInclude const &>(*iit->inset);
3195                                 macro_lock = true;
3196                                 Buffer * child = inset.getChildBuffer();
3197                                 macro_lock = false;
3198                                 if (!child)
3199                                         continue;
3200
3201                                 // register its position, but only when it is
3202                                 // included first in the buffer
3203                                 if (children_positions.find(child) ==
3204                                         children_positions.end())
3205                                                 children_positions[child] = it;
3206
3207                                 // register child with its scope
3208                                 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3209                                 continue;
3210                         }
3211
3212                         InsetMath * im = iit->inset->asInsetMath();
3213                         if (doing_export && im)  {
3214                                 InsetMathHull * hull = im->asHullInset();
3215                                 if (hull)
3216                                         hull->recordLocation(it);
3217                         }
3218
3219                         if (iit->inset->lyxCode() != MATHMACRO_CODE)
3220                                 continue;
3221
3222                         // get macro data
3223                         MathMacroTemplate & macroTemplate =
3224                                 *iit->inset->asInsetMath()->asMacroTemplate();
3225                         MacroContext mc(owner_, it);
3226                         macroTemplate.updateToContext(mc);
3227
3228                         // valid?
3229                         bool valid = macroTemplate.validMacro();
3230                         // FIXME: Should be fixNameAndCheckIfValid() in fact,
3231                         // then the BufferView's cursor will be invalid in
3232                         // some cases which leads to crashes.
3233                         if (!valid)
3234                                 continue;
3235
3236                         // register macro
3237                         // FIXME (Abdel), I don't understandt why we pass 'it' here
3238                         // instead of 'macroTemplate' defined above... is this correct?
3239                         macros[macroTemplate.name()][it] =
3240                                 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3241                 }
3242
3243                 // next paragraph
3244                 it.pit()++;
3245                 it.pos() = 0;
3246         }
3247 }
3248
3249
3250 void Buffer::updateMacros() const
3251 {
3252         if (d->macro_lock)
3253                 return;
3254
3255         LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3256
3257         // start with empty table
3258         d->macros.clear();
3259         d->children_positions.clear();
3260         d->position_to_children.clear();
3261
3262         // Iterate over buffer, starting with first paragraph
3263         // The scope must be bigger than any lookup DocIterator
3264         // later. For the global lookup, lastpit+1 is used, hence
3265         // we use lastpit+2 here.
3266         DocIterator it = par_iterator_begin();
3267         DocIterator outerScope = it;
3268         outerScope.pit() = outerScope.lastpit() + 2;
3269         d->updateMacros(it, outerScope);
3270 }
3271
3272
3273 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3274 {
3275         InsetIterator it  = inset_iterator_begin(inset());
3276         InsetIterator const end = inset_iterator_end(inset());
3277         for (; it != end; ++it) {
3278                 if (it->lyxCode() == BRANCH_CODE) {
3279                         InsetBranch & br = static_cast<InsetBranch &>(*it);
3280                         docstring const name = br.branch();
3281                         if (!from_master && !params().branchlist().find(name))
3282                                 result.push_back(name);
3283                         else if (from_master && !masterBuffer()->params().branchlist().find(name))
3284                                 result.push_back(name);
3285                         continue;
3286                 }
3287                 if (it->lyxCode() == INCLUDE_CODE) {
3288                         // get buffer of external file
3289                         InsetInclude const & ins =
3290                                 static_cast<InsetInclude const &>(*it);
3291                         Buffer * child = ins.getChildBuffer();
3292                         if (!child)
3293                                 continue;
3294                         child->getUsedBranches(result, true);
3295                 }
3296         }
3297         // remove duplicates
3298         result.unique();
3299 }
3300
3301
3302 void Buffer::updateMacroInstances(UpdateType utype) const
3303 {
3304         LYXERR(Debug::MACROS, "updateMacroInstances for "
3305                 << d->filename.onlyFileName());
3306         DocIterator it = doc_iterator_begin(this);
3307         it.forwardInset();
3308         DocIterator const end = doc_iterator_end(this);
3309         for (; it != end; it.forwardInset()) {
3310                 // look for MathData cells in InsetMathNest insets
3311                 InsetMath * minset = it.nextInset()->asInsetMath();
3312                 if (!minset)
3313                         continue;
3314
3315                 // update macro in all cells of the InsetMathNest
3316                 DocIterator::idx_type n = minset->nargs();
3317                 MacroContext mc = MacroContext(this, it);
3318                 for (DocIterator::idx_type i = 0; i < n; ++i) {
3319                         MathData & data = minset->cell(i);
3320                         data.updateMacros(0, mc, utype);
3321                 }
3322         }
3323 }
3324
3325
3326 void Buffer::listMacroNames(MacroNameSet & macros) const
3327 {
3328         if (d->macro_lock)
3329                 return;
3330
3331         d->macro_lock = true;
3332
3333         // loop over macro names
3334         Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3335         Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3336         for (; nameIt != nameEnd; ++nameIt)
3337                 macros.insert(nameIt->first);
3338
3339         // loop over children
3340         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3341         Impl::BufferPositionMap::iterator end = d->children_positions.end();
3342         for (; it != end; ++it)
3343                 it->first->listMacroNames(macros);
3344
3345         // call parent
3346         Buffer const * const pbuf = d->parent();
3347         if (pbuf)
3348                 pbuf->listMacroNames(macros);
3349
3350         d->macro_lock = false;
3351 }
3352
3353
3354 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3355 {
3356         Buffer const * const pbuf = d->parent();
3357         if (!pbuf)
3358                 return;
3359
3360         MacroNameSet names;
3361         pbuf->listMacroNames(names);
3362
3363         // resolve macros
3364         MacroNameSet::iterator it = names.begin();
3365         MacroNameSet::iterator end = names.end();
3366         for (; it != end; ++it) {
3367                 // defined?
3368                 MacroData const * data =
3369                 pbuf->getMacro(*it, *this, false);
3370                 if (data) {
3371                         macros.insert(data);
3372
3373                         // we cannot access the original MathMacroTemplate anymore
3374                         // here to calls validate method. So we do its work here manually.
3375                         // FIXME: somehow make the template accessible here.
3376                         if (data->optionals() > 0)
3377                                 features.require("xargs");
3378                 }
3379         }
3380 }
3381
3382
3383 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3384 {
3385         if (d->parent())
3386                 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3387
3388         RefCache::iterator it = d->ref_cache_.find(label);
3389         if (it != d->ref_cache_.end())
3390                 return it->second.second;
3391
3392         static InsetLabel const * dummy_il = 0;
3393         static References const dummy_refs;
3394         it = d->ref_cache_.insert(
3395                 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3396         return it->second.second;
3397 }
3398
3399
3400 Buffer::References const & Buffer::references(docstring const & label) const
3401 {
3402         return const_cast<Buffer *>(this)->getReferenceCache(label);
3403 }
3404
3405
3406 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3407 {
3408         References & refs = getReferenceCache(label);
3409         refs.push_back(make_pair(inset, it));
3410 }
3411
3412
3413 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3414 {
3415         masterBuffer()->d->ref_cache_[label].first = il;
3416 }
3417
3418
3419 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3420 {
3421         return masterBuffer()->d->ref_cache_[label].first;
3422 }
3423
3424
3425 void Buffer::clearReferenceCache() const
3426 {
3427         if (!d->parent())
3428                 d->ref_cache_.clear();
3429 }
3430
3431
3432 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
3433 {
3434         //FIXME: This does not work for child documents yet.
3435         reloadBibInfoCache();
3436
3437         // Check if the label 'from' appears more than once
3438         BiblioInfo const & keys = masterBibInfo();
3439         BiblioInfo::const_iterator bit  = keys.begin();
3440         BiblioInfo::const_iterator bend = keys.end();
3441         vector<docstring> labels;
3442
3443         for (; bit != bend; ++bit)
3444                 // FIXME UNICODE
3445                 labels.push_back(bit->first);
3446
3447         if (count(labels.begin(), labels.end(), from) > 1)
3448                 return;
3449
3450         string const paramName = "key";
3451         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3452                 if (it->lyxCode() != CITE_CODE)
3453                         continue;
3454                 InsetCommand * inset = it->asInsetCommand();
3455                 docstring const oldValue = inset->getParam(paramName);
3456                 if (oldValue == from)
3457                         inset->setParam(paramName, to);
3458         }
3459 }
3460
3461
3462 void Buffer::getSourceCode(odocstream & os, string const format,
3463                            pit_type par_begin, pit_type par_end,
3464                            OutputWhat output, bool master) const
3465 {
3466         OutputParams runparams(&params().encoding());
3467         runparams.nice = true;
3468         runparams.flavor = params().getOutputFlavor(format);
3469         runparams.linelen = lyxrc.plaintext_linelen;
3470         // No side effect of file copying and image conversion
3471         runparams.dryrun = true;
3472
3473         if (output == CurrentParagraph) {
3474                 runparams.par_begin = par_begin;
3475                 runparams.par_end = par_end;
3476                 if (par_begin + 1 == par_end) {
3477                         os << "% "
3478                            << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3479                            << "\n\n";
3480                 } else {
3481                         os << "% "
3482                            << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3483                                         convert<docstring>(par_begin),
3484                                         convert<docstring>(par_end - 1))
3485                            << "\n\n";
3486                 }
3487                 // output paragraphs
3488                 if (runparams.flavor == OutputParams::LYX) {
3489                         Paragraph const & par = text().paragraphs()[par_begin];
3490                         ostringstream ods;
3491                         depth_type dt = par.getDepth();
3492                         par.write(ods, params(), dt);
3493                         os << from_utf8(ods.str());
3494                 } else if (runparams.flavor == OutputParams::HTML) {
3495                         XHTMLStream xs(os);
3496                         setMathFlavor(runparams);
3497                         xhtmlParagraphs(text(), *this, xs, runparams);
3498                 } else if (runparams.flavor == OutputParams::TEXT) {
3499                         bool dummy;
3500                         // FIXME Handles only one paragraph, unlike the others.
3501                         // Probably should have some routine with a signature like them.
3502                         writePlaintextParagraph(*this,
3503                                 text().paragraphs()[par_begin], os, runparams, dummy);
3504                 } else if (params().isDocBook()) {
3505                         docbookParagraphs(text(), *this, os, runparams);
3506                 } else {
3507                         // If we are previewing a paragraph, even if this is the
3508                         // child of some other buffer, let's cut the link here,
3509                         // so that no concurring settings from the master
3510                         // (e.g. branch state) interfere (see #8101).
3511                         if (!master)
3512                                 d->ignore_parent = true;
3513                         // We need to validate the Buffer params' features here
3514                         // in order to know if we should output polyglossia
3515                         // macros (instead of babel macros)
3516                         LaTeXFeatures features(*this, params(), runparams);
3517                         params().validate(features);
3518                         runparams.use_polyglossia = features.usePolyglossia();
3519                         TexRow texrow;
3520                         texrow.reset();
3521                         texrow.newline();
3522                         texrow.newline();
3523                         // latex or literate
3524                         otexstream ots(os, texrow);
3525
3526                         // the real stuff
3527                         latexParagraphs(*this, text(), ots, runparams);
3528
3529                         // Restore the parenthood
3530                         if (!master)
3531                                 d->ignore_parent = false;
3532                 }
3533         } else {
3534                 os << "% ";
3535                 if (output == FullSource)
3536                         os << _("Preview source code");
3537                 else if (output == OnlyPreamble)
3538                         os << _("Preview preamble");
3539                 else if (output == OnlyBody)
3540                         os << _("Preview body");
3541                 os << "\n\n";
3542                 if (runparams.flavor == OutputParams::LYX) {
3543                         ostringstream ods;
3544                         if (output == FullSource)
3545                                 write(ods);
3546                         else if (output == OnlyPreamble)
3547                                 params().writeFile(ods);
3548                         else if (output == OnlyBody)
3549                                 text().write(ods);
3550                         os << from_utf8(ods.str());
3551                 } else if (runparams.flavor == OutputParams::HTML) {
3552                         writeLyXHTMLSource(os, runparams, output);
3553                 } else if (runparams.flavor == OutputParams::TEXT) {
3554                         if (output == OnlyPreamble) {
3555                                 os << "% "<< _("Plain text does not have a preamble.");
3556                         } else
3557                                 writePlaintextFile(*this, os, runparams);
3558                 } else if (params().isDocBook()) {
3559                                 writeDocBookSource(os, absFileName(), runparams, output);
3560                 } else {
3561                         // latex or literate
3562                         d->texrow.reset();
3563                         d->texrow.newline();
3564                         d->texrow.newline();
3565                         otexstream ots(os, d->texrow);
3566                         if (master)
3567                                 runparams.is_child = true;
3568                         writeLaTeXSource(ots, string(), runparams, output);
3569                 }
3570         }
3571 }
3572
3573
3574 ErrorList & Buffer::errorList(string const & type) const
3575 {
3576         return d->errorLists[type];
3577 }
3578
3579
3580 void Buffer::updateTocItem(std::string const & type,
3581         DocIterator const & dit) const
3582 {
3583         if (d->gui_)
3584                 d->gui_->updateTocItem(type, dit);
3585 }
3586
3587
3588 void Buffer::structureChanged() const
3589 {
3590         if (d->gui_)
3591                 d->gui_->structureChanged();
3592 }
3593
3594
3595 void Buffer::errors(string const & err, bool from_master) const
3596 {
3597         if (d->gui_)
3598                 d->gui_->errors(err, from_master);
3599 }
3600
3601
3602 void Buffer::message(docstring const & msg) const
3603 {
3604         if (d->gui_)
3605                 d->gui_->message(msg);
3606 }
3607
3608
3609 void Buffer::setBusy(bool on) const
3610 {
3611         if (d->gui_)
3612                 d->gui_->setBusy(on);
3613 }
3614
3615
3616 void Buffer::updateTitles() const
3617 {
3618         if (d->wa_)
3619                 d->wa_->updateTitles();
3620 }
3621
3622
3623 void Buffer::resetAutosaveTimers() const
3624 {
3625         if (d->gui_)
3626                 d->gui_->resetAutosaveTimers();
3627 }
3628
3629
3630 bool Buffer::hasGuiDelegate() const
3631 {
3632         return d->gui_;
3633 }
3634
3635
3636 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3637 {
3638         d->gui_ = gui;
3639 }
3640
3641
3642
3643 namespace {
3644
3645 class AutoSaveBuffer : public ForkedProcess {
3646 public:
3647         ///
3648         AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3649                 : buffer_(buffer), fname_(fname) {}
3650         ///
3651         virtual shared_ptr<ForkedProcess> clone() const
3652         {
3653                 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3654         }
3655         ///
3656         int start()
3657         {
3658                 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3659                                                  from_utf8(fname_.absFileName())));
3660                 return run(DontWait);
3661         }
3662 private:
3663         ///
3664         virtual int generateChild();
3665         ///
3666         Buffer const & buffer_;
3667         FileName fname_;
3668 };
3669
3670
3671 int AutoSaveBuffer::generateChild()
3672 {
3673 #if defined(__APPLE__)
3674         /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3675          *   We should use something else like threads.
3676          *
3677          * Since I do not know how to determine at run time what is the OS X
3678          * version, I just disable forking altogether for now (JMarc)
3679          */
3680         pid_t const pid = -1;
3681 #else
3682         // tmp_ret will be located (usually) in /tmp
3683         // will that be a problem?
3684         // Note that this calls ForkedCalls::fork(), so it's
3685         // ok cross-platform.
3686         pid_t const pid = fork();
3687         // If you want to debug the autosave
3688         // you should set pid to -1, and comment out the fork.
3689         if (pid != 0 && pid != -1)
3690                 return pid;
3691 #endif
3692
3693         // pid = -1 signifies that lyx was unable
3694         // to fork. But we will do the save
3695         // anyway.
3696         bool failed = false;
3697         FileName const tmp_ret = FileName::tempName("lyxauto");
3698         if (!tmp_ret.empty()) {
3699                 buffer_.writeFile(tmp_ret);
3700                 // assume successful write of tmp_ret
3701                 if (!tmp_ret.moveTo(fname_))
3702                         failed = true;
3703         } else
3704                 failed = true;
3705
3706         if (failed) {
3707                 // failed to write/rename tmp_ret so try writing direct
3708                 if (!buffer_.writeFile(fname_)) {
3709                         // It is dangerous to do this in the child,
3710                         // but safe in the parent, so...
3711                         if (pid == -1) // emit message signal.
3712                                 buffer_.message(_("Autosave failed!"));
3713                 }
3714         }
3715
3716         if (pid == 0) // we are the child so...
3717                 _exit(0);
3718
3719         return pid;
3720 }
3721
3722 } // namespace anon
3723
3724
3725 FileName Buffer::getEmergencyFileName() const
3726 {
3727         return FileName(d->filename.absFileName() + ".emergency");
3728 }
3729
3730
3731 FileName Buffer::getAutosaveFileName() const
3732 {
3733         // if the document is unnamed try to save in the backup dir, else
3734         // in the default document path, and as a last try in the filePath,
3735         // which will most often be the temporary directory
3736         string fpath;
3737         if (isUnnamed())
3738                 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3739                         : lyxrc.backupdir_path;
3740         if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3741                 fpath = filePath();
3742
3743         string const fname = "#" + d->filename.onlyFileName() + "#";
3744
3745         return makeAbsPath(fname, fpath);
3746 }
3747
3748
3749 void Buffer::removeAutosaveFile() const
3750 {
3751         FileName const f = getAutosaveFileName();
3752         if (f.exists())
3753                 f.removeFile();
3754 }
3755
3756
3757 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3758 {
3759         FileName const newauto = getAutosaveFileName();
3760         oldauto.refresh();
3761         if (newauto != oldauto && oldauto.exists())
3762                 if (!oldauto.moveTo(newauto))
3763                         LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3764 }
3765
3766
3767 bool Buffer::autoSave() const
3768 {
3769         Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3770         if (buf->d->bak_clean || isReadonly())
3771                 return true;
3772
3773         message(_("Autosaving current document..."));
3774         buf->d->bak_clean = true;
3775
3776         FileName const fname = getAutosaveFileName();
3777         LASSERT(d->cloned_buffer_, return false);
3778
3779         // If this buffer is cloned, we assume that
3780         // we are running in a separate thread already.
3781         FileName const tmp_ret = FileName::tempName("lyxauto");
3782         if (!tmp_ret.empty()) {
3783                 writeFile(tmp_ret);
3784                 // assume successful write of tmp_ret
3785                 if (tmp_ret.moveTo(fname))
3786                         return true;
3787         }
3788         // failed to write/rename tmp_ret so try writing direct
3789         return writeFile(fname);
3790 }
3791
3792
3793 void Buffer::setExportStatus(bool e) const
3794 {
3795         d->doing_export = e;
3796         ListOfBuffers clist = getDescendents();
3797         ListOfBuffers::const_iterator cit = clist.begin();
3798         ListOfBuffers::const_iterator const cen = clist.end();
3799         for (; cit != cen; ++cit)
3800                 (*cit)->d->doing_export = e;
3801 }
3802
3803
3804 bool Buffer::isExporting() const
3805 {
3806         return d->doing_export;
3807 }
3808
3809
3810 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
3811         const
3812 {
3813         string result_file;
3814         return doExport(target, put_in_tempdir, result_file);
3815 }
3816
3817 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3818         string & result_file) const
3819 {
3820         bool const update_unincluded =
3821                         params().maintain_unincluded_children
3822                         && !params().getIncludedChildren().empty();
3823
3824         // (1) export with all included children (omit \includeonly)
3825         if (update_unincluded) {
3826                 ExportStatus const status =
3827                         doExport(target, put_in_tempdir, true, result_file);
3828                 if (status != ExportSuccess)
3829                         return status;
3830         }
3831         // (2) export with included children only
3832         return doExport(target, put_in_tempdir, false, result_file);
3833 }
3834
3835
3836 void Buffer::setMathFlavor(OutputParams & op) const
3837 {
3838         switch (params().html_math_output) {
3839         case BufferParams::MathML:
3840                 op.math_flavor = OutputParams::MathAsMathML;
3841                 break;
3842         case BufferParams::HTML:
3843                 op.math_flavor = OutputParams::MathAsHTML;
3844                 break;
3845         case BufferParams::Images:
3846                 op.math_flavor = OutputParams::MathAsImages;
3847                 break;
3848         case BufferParams::LaTeX:
3849                 op.math_flavor = OutputParams::MathAsLaTeX;
3850                 break;
3851         }
3852 }
3853
3854
3855 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3856         bool includeall, string & result_file) const
3857 {
3858         LYXERR(Debug::FILES, "target=" << target);
3859         OutputParams runparams(&params().encoding());
3860         string format = target;
3861         string dest_filename;
3862         size_t pos = target.find(' ');
3863         if (pos != string::npos) {
3864                 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
3865                 format = target.substr(0, pos);
3866                 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
3867                 FileName(dest_filename).onlyPath().createPath();
3868                 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
3869         }
3870         MarkAsExporting exporting(this);
3871         string backend_format;
3872         runparams.flavor = OutputParams::LATEX;
3873         runparams.linelen = lyxrc.plaintext_linelen;
3874         runparams.includeall = includeall;
3875         vector<string> backs = params().backends();
3876         Converters converters = theConverters();
3877         bool need_nice_file = false;
3878         if (find(backs.begin(), backs.end(), format) == backs.end()) {
3879                 // Get shortest path to format
3880                 converters.buildGraph();
3881                 Graph::EdgePath path;
3882                 for (vector<string>::const_iterator it = backs.begin();
3883                      it != backs.end(); ++it) {
3884                         Graph::EdgePath p = converters.getPath(*it, format);
3885                         if (!p.empty() && (path.empty() || p.size() < path.size())) {
3886                                 backend_format = *it;
3887                                 path = p;
3888                         }
3889                 }
3890                 if (path.empty()) {
3891                         if (!put_in_tempdir) {
3892                                 // Only show this alert if this is an export to a non-temporary
3893                                 // file (not for previewing).
3894                                 Alert::error(_("Couldn't export file"), bformat(
3895                                         _("No information for exporting the format %1$s."),
3896                                         formats.prettyName(format)));
3897                         }
3898                         return ExportNoPathToFormat;
3899                 }
3900                 runparams.flavor = converters.getFlavor(path, this);
3901                 Graph::EdgePath::const_iterator it = path.begin();
3902                 Graph::EdgePath::const_iterator en = path.end();
3903                 for (; it != en; ++it)
3904                         if (theConverters().get(*it).nice) {
3905                                 need_nice_file = true;
3906                                 break;
3907                         }
3908
3909         } else {
3910                 backend_format = format;
3911                 LYXERR(Debug::FILES, "backend_format=" << backend_format);
3912                 // FIXME: Don't hardcode format names here, but use a flag
3913                 if (backend_format == "pdflatex")
3914                         runparams.flavor = OutputParams::PDFLATEX;
3915                 else if (backend_format == "luatex")
3916                         runparams.flavor = OutputParams::LUATEX;
3917                 else if (backend_format == "dviluatex")
3918                         runparams.flavor = OutputParams::DVILUATEX;
3919                 else if (backend_format == "xetex")
3920                         runparams.flavor = OutputParams::XETEX;
3921         }
3922
3923         string filename = latexName(false);
3924         filename = addName(temppath(), filename);
3925         filename = changeExtension(filename,
3926                                    formats.extension(backend_format));
3927         LYXERR(Debug::FILES, "filename=" << filename);
3928
3929         // Plain text backend
3930         if (backend_format == "text") {
3931                 runparams.flavor = OutputParams::TEXT;
3932                 writePlaintextFile(*this, FileName(filename), runparams);
3933         }
3934         // HTML backend
3935         else if (backend_format == "xhtml") {
3936                 runparams.flavor = OutputParams::HTML;
3937                 setMathFlavor(runparams);
3938                 makeLyXHTMLFile(FileName(filename), runparams);
3939         } else if (backend_format == "lyx")
3940                 writeFile(FileName(filename));
3941         // Docbook backend
3942         else if (params().isDocBook()) {
3943                 runparams.nice = !put_in_tempdir;
3944                 makeDocBookFile(FileName(filename), runparams);
3945         }
3946         // LaTeX backend
3947         else if (backend_format == format || need_nice_file) {
3948                 runparams.nice = true;
3949                 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
3950                 if (d->cloned_buffer_)
3951                         d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
3952                 if (!success)
3953                         return ExportError;
3954         } else if (!lyxrc.tex_allows_spaces
3955                    && contains(filePath(), ' ')) {
3956                 Alert::error(_("File name error"),
3957                            _("The directory path to the document cannot contain spaces."));
3958                 return ExportTexPathHasSpaces;
3959         } else {
3960                 runparams.nice = false;
3961                 bool const success = makeLaTeXFile(
3962                         FileName(filename), filePath(), runparams);
3963                 if (d->cloned_buffer_)
3964                         d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
3965                 if (!success)
3966                         return ExportError;
3967         }
3968
3969         string const error_type = (format == "program")
3970                 ? "Build" : params().bufferFormat();
3971         ErrorList & error_list = d->errorLists[error_type];
3972         string const ext = formats.extension(format);
3973         FileName const tmp_result_file(changeExtension(filename, ext));
3974         bool const success = converters.convert(this, FileName(filename),
3975                 tmp_result_file, FileName(absFileName()), backend_format, format,
3976                 error_list);
3977
3978         // Emit the signal to show the error list or copy it back to the
3979         // cloned Buffer so that it can be emitted afterwards.
3980         if (format != backend_format) {
3981                 if (runparams.silent)
3982                         error_list.clear();
3983                 else if (d->cloned_buffer_)
3984                         d->cloned_buffer_->d->errorLists[error_type] =
3985                                 d->errorLists[error_type];
3986                 else
3987                         errors(error_type);
3988                 // also to the children, in case of master-buffer-view
3989                 ListOfBuffers clist = getDescendents();
3990                 ListOfBuffers::const_iterator cit = clist.begin();
3991                 ListOfBuffers::const_iterator const cen = clist.end();
3992                 for (; cit != cen; ++cit) {
3993                         if (runparams.silent)
3994                                 (*cit)->d->errorLists[error_type].clear();
3995                         else if (d->cloned_buffer_) {
3996                                 // Enable reverse search by copying back the
3997                                 // texrow object to the cloned buffer.
3998                                 // FIXME: this is not thread safe.
3999                                 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
4000                                 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
4001                                         (*cit)->d->errorLists[error_type];
4002                         } else
4003                                 (*cit)->errors(error_type, true);
4004                 }
4005         }
4006
4007         if (d->cloned_buffer_) {
4008                 // Enable reverse dvi or pdf to work by copying back the texrow
4009                 // object to the cloned buffer.
4010                 // FIXME: There is a possibility of concurrent access to texrow
4011                 // here from the main GUI thread that should be securized.
4012                 d->cloned_buffer_->d->texrow = d->texrow;
4013                 string const error_type = params().bufferFormat();
4014                 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
4015         }
4016
4017         if (!success)
4018                 return ExportConverterError;
4019
4020         if (put_in_tempdir) {
4021                 result_file = tmp_result_file.absFileName();
4022                 return ExportSuccess;
4023         }
4024
4025         if (dest_filename.empty())
4026                 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4027         else
4028                 result_file = dest_filename;
4029         // We need to copy referenced files (e. g. included graphics
4030         // if format == "dvi") to the result dir.
4031         vector<ExportedFile> const files =
4032                 runparams.exportdata->externalFiles(format);
4033         string const dest = runparams.export_folder.empty() ?
4034                 onlyPath(result_file) : runparams.export_folder;
4035         bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4036                                  : force_overwrite == ALL_FILES;
4037         CopyStatus status = use_force ? FORCE : SUCCESS;
4038
4039         vector<ExportedFile>::const_iterator it = files.begin();
4040         vector<ExportedFile>::const_iterator const en = files.end();
4041         for (; it != en && status != CANCEL; ++it) {
4042                 string const fmt = formats.getFormatFromFile(it->sourceName);
4043                 string fixedName = it->exportName;
4044                 if (!runparams.export_folder.empty()) {
4045                         // Relative pathnames starting with ../ will be sanitized
4046                         // if exporting to a different folder
4047                         while (fixedName.substr(0, 3) == "../")
4048                                 fixedName = fixedName.substr(3, fixedName.length() - 3);
4049                 }
4050                 FileName fixedFileName = makeAbsPath(fixedName, dest);
4051                 fixedFileName.onlyPath().createPath();
4052                 status = copyFile(fmt, it->sourceName,
4053                         fixedFileName,
4054                         it->exportName, status == FORCE,
4055                         runparams.export_folder.empty());
4056         }
4057
4058         if (status == CANCEL) {
4059                 message(_("Document export cancelled."));
4060                 return ExportCancel;
4061         }
4062
4063         if (tmp_result_file.exists()) {
4064                 // Finally copy the main file
4065                 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4066                                     : force_overwrite != NO_FILES;
4067                 if (status == SUCCESS && use_force)
4068                         status = FORCE;
4069                 status = copyFile(format, tmp_result_file,
4070                         FileName(result_file), result_file,
4071                         status == FORCE);
4072                 if (status == CANCEL) {
4073                         message(_("Document export cancelled."));
4074                         return ExportCancel;
4075                 } else {
4076                         message(bformat(_("Document exported as %1$s "
4077                                 "to file `%2$s'"),
4078                                 formats.prettyName(format),
4079                                 makeDisplayPath(result_file)));
4080                 }
4081         } else {
4082                 // This must be a dummy converter like fax (bug 1888)
4083                 message(bformat(_("Document exported as %1$s"),
4084                         formats.prettyName(format)));
4085         }
4086
4087         return ExportSuccess;
4088 }
4089
4090
4091 Buffer::ExportStatus Buffer::preview(string const & format) const
4092 {
4093         bool const update_unincluded =
4094                         params().maintain_unincluded_children
4095                         && !params().getIncludedChildren().empty();
4096         return preview(format, update_unincluded);
4097 }
4098
4099 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4100 {
4101         MarkAsExporting exporting(this);
4102         string result_file;
4103         // (1) export with all included children (omit \includeonly)
4104         if (includeall) {
4105                 ExportStatus const status = doExport(format, true, true, result_file);
4106                 if (status != ExportSuccess)
4107                         return status;
4108         }
4109         // (2) export with included children only
4110         ExportStatus const status = doExport(format, true, false, result_file);
4111         if (status != ExportSuccess)
4112                 return status;
4113         if (!formats.view(*this, FileName(result_file), format))
4114                 return PreviewError;
4115         return PreviewSuccess;
4116 }
4117
4118
4119 Buffer::ReadStatus Buffer::extractFromVC()
4120 {
4121         bool const found = LyXVC::file_not_found_hook(d->filename);
4122         if (!found)
4123                 return ReadFileNotFound;
4124         if (!d->filename.isReadableFile())
4125                 return ReadVCError;
4126         return ReadSuccess;
4127 }
4128
4129
4130 Buffer::ReadStatus Buffer::loadEmergency()
4131 {
4132         FileName const emergencyFile = getEmergencyFileName();
4133         if (!emergencyFile.exists()
4134                   || emergencyFile.lastModified() <= d->filename.lastModified())
4135                 return ReadFileNotFound;
4136
4137         docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4138         docstring const text = bformat(_("An emergency save of the document "
4139                 "%1$s exists.\n\nRecover emergency save?"), file);
4140
4141         int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4142                 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4143
4144         switch (load_emerg)
4145         {
4146         case 0: {
4147                 docstring str;
4148                 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4149                 bool const success = (ret_llf == ReadSuccess);
4150                 if (success) {
4151                         if (isReadonly()) {
4152                                 Alert::warning(_("File is read-only"),
4153                                         bformat(_("An emergency file is successfully loaded, "
4154                                         "but the original file %1$s is marked read-only. "
4155                                         "Please make sure to save the document as a different "
4156                                         "file."), from_utf8(d->filename.absFileName())));
4157                         }
4158                         markDirty();
4159                         lyxvc().file_found_hook(d->filename);
4160                         str = _("Document was successfully recovered.");
4161                 } else
4162                         str = _("Document was NOT successfully recovered.");
4163                 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4164                         makeDisplayPath(emergencyFile.absFileName()));
4165
4166                 int const del_emerg =
4167                         Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4168                                 _("&Remove"), _("&Keep"));
4169                 if (del_emerg == 0) {
4170                         emergencyFile.removeFile();
4171                         if (success)
4172                                 Alert::warning(_("Emergency file deleted"),
4173                                         _("Do not forget to save your file now!"), true);
4174                         }
4175                 return success ? ReadSuccess : ReadEmergencyFailure;
4176         }
4177         case 1: {
4178                 int const del_emerg =
4179                         Alert::prompt(_("Delete emergency file?"),
4180                                 _("Remove emergency file now?"), 1, 1,
4181                                 _("&Remove"), _("&Keep"));
4182                 if (del_emerg == 0)
4183                         emergencyFile.removeFile();
4184                 return ReadOriginal;
4185         }
4186
4187         default:
4188                 break;
4189         }
4190         return ReadCancel;
4191 }
4192
4193
4194 Buffer::ReadStatus Buffer::loadAutosave()
4195 {
4196         // Now check if autosave file is newer.
4197         FileName const autosaveFile = getAutosaveFileName();
4198         if (!autosaveFile.exists()
4199                   || autosaveFile.lastModified() <= d->filename.lastModified())
4200                 return ReadFileNotFound;
4201
4202         docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4203         docstring const text = bformat(_("The backup of the document %1$s "
4204                 "is newer.\n\nLoad the backup instead?"), file);
4205         int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4206                 _("&Load backup"), _("Load &original"), _("&Cancel"));
4207
4208         switch (ret)
4209         {
4210         case 0: {
4211                 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4212                 // the file is not saved if we load the autosave file.
4213                 if (ret_llf == ReadSuccess) {
4214                         if (isReadonly()) {
4215                                 Alert::warning(_("File is read-only"),
4216                                         bformat(_("A backup file is successfully loaded, "
4217                                         "but the original file %1$s is marked read-only. "
4218                                         "Please make sure to save the document as a "
4219                                         "different file."),
4220                                         from_utf8(d->filename.absFileName())));
4221                         }
4222                         markDirty();
4223                         lyxvc().file_found_hook(d->filename);
4224                         return ReadSuccess;
4225                 }
4226                 return ReadAutosaveFailure;
4227         }
4228         case 1:
4229                 // Here we delete the autosave
4230                 autosaveFile.removeFile();
4231                 return ReadOriginal;
4232         default:
4233                 break;
4234         }
4235         return ReadCancel;
4236 }
4237
4238
4239 Buffer::ReadStatus Buffer::loadLyXFile()
4240 {
4241         if (!d->filename.isReadableFile()) {
4242                 ReadStatus const ret_rvc = extractFromVC();
4243                 if (ret_rvc != ReadSuccess)
4244                         return ret_rvc;
4245         }
4246
4247         ReadStatus const ret_re = loadEmergency();
4248         if (ret_re == ReadSuccess || ret_re == ReadCancel)
4249                 return ret_re;
4250
4251         ReadStatus const ret_ra = loadAutosave();
4252         if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4253                 return ret_ra;
4254
4255         return loadThisLyXFile(d->filename);
4256 }
4257
4258
4259 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4260 {
4261         return readFile(fn);
4262 }
4263
4264
4265 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4266 {
4267         TeXErrors::Errors::const_iterator it = terr.begin();
4268         TeXErrors::Errors::const_iterator end = terr.end();
4269         ListOfBuffers clist = getDescendents();
4270         ListOfBuffers::const_iterator cen = clist.end();
4271
4272         for (; it != end; ++it) {
4273                 int id_start = -1;
4274                 int pos_start = -1;
4275                 int errorRow = it->error_in_line;
4276                 Buffer const * buf = 0;
4277                 Impl const * p = d;
4278                 if (it->child_name.empty())
4279                     p->texrow.getIdFromRow(errorRow, id_start, pos_start);
4280                 else {
4281                         // The error occurred in a child
4282                         ListOfBuffers::const_iterator cit = clist.begin();
4283                         for (; cit != cen; ++cit) {
4284                                 string const child_name =
4285                                         DocFileName(changeExtension(
4286                                                 (*cit)->absFileName(), "tex")).
4287                                                         mangledFileName();
4288                                 if (it->child_name != child_name)
4289                                         continue;
4290                                 (*cit)->d->texrow.getIdFromRow(errorRow,
4291                                                         id_start, pos_start);
4292                                 if (id_start != -1) {
4293                                         buf = d->cloned_buffer_
4294                                                 ? (*cit)->d->cloned_buffer_->d->owner_
4295                                                 : (*cit)->d->owner_;
4296                                         p = (*cit)->d;
4297                                         break;
4298                                 }
4299                         }
4300                 }
4301                 int id_end = -1;
4302                 int pos_end = -1;
4303                 bool found;
4304                 do {
4305                         ++errorRow;
4306                         found = p->texrow.getIdFromRow(errorRow, id_end, pos_end);
4307                 } while (found && id_start == id_end && pos_start == pos_end);
4308
4309                 if (id_start != id_end) {
4310                         // Next registered position is outside the inset where
4311                         // the error occurred, so signal end-of-paragraph
4312                         pos_end = 0;
4313                 }
4314
4315                 errorList.push_back(ErrorItem(it->error_desc,
4316                         it->error_text, id_start, pos_start, pos_end, buf));
4317         }
4318 }
4319
4320
4321 void Buffer::setBuffersForInsets() const
4322 {
4323         inset().setBuffer(const_cast<Buffer &>(*this));
4324 }
4325
4326
4327 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4328 {
4329         LBUFERR(!text().paragraphs().empty());
4330
4331         // Use the master text class also for child documents
4332         Buffer const * const master = masterBuffer();
4333         DocumentClass const & textclass = master->params().documentClass();
4334
4335         // do this only if we are the top-level Buffer
4336         if (master == this) {
4337                 textclass.counters().reset(from_ascii("bibitem"));
4338                 reloadBibInfoCache();
4339         }
4340
4341         // keep the buffers to be children in this set. If the call from the
4342         // master comes back we can see which of them were actually seen (i.e.
4343         // via an InsetInclude). The remaining ones in the set need still be updated.
4344         static std::set<Buffer const *> bufToUpdate;
4345         if (scope == UpdateMaster) {
4346                 // If this is a child document start with the master
4347                 if (master != this) {
4348                         bufToUpdate.insert(this);
4349                         master->updateBuffer(UpdateMaster, utype);
4350                         // Do this here in case the master has no gui associated with it. Then,
4351                         // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
4352                         if (!master->d->gui_)
4353                                 structureChanged();
4354
4355                         // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4356                         if (bufToUpdate.find(this) == bufToUpdate.end())
4357                                 return;
4358                 }
4359
4360                 // start over the counters in the master
4361                 textclass.counters().reset();
4362         }
4363
4364         // update will be done below for this buffer
4365         bufToUpdate.erase(this);
4366
4367         // update all caches
4368         clearReferenceCache();
4369         updateMacros();
4370
4371         Buffer & cbuf = const_cast<Buffer &>(*this);
4372
4373         // do the real work
4374         ParIterator parit = cbuf.par_iterator_begin();
4375         updateBuffer(parit, utype);
4376
4377         if (master != this)
4378                 // TocBackend update will be done later.
4379                 return;
4380
4381         d->bibinfo_cache_valid_ = true;
4382         d->cite_labels_valid_ = true;
4383         cbuf.tocBackend().update(utype == OutputUpdate);
4384         if (scope == UpdateMaster)
4385                 cbuf.structureChanged();
4386 }
4387
4388
4389 static depth_type getDepth(DocIterator const & it)
4390 {
4391         depth_type depth = 0;
4392         for (size_t i = 0 ; i < it.depth() ; ++i)
4393                 if (!it[i].inset().inMathed())
4394                         depth += it[i].paragraph().getDepth() + 1;
4395         // remove 1 since the outer inset does not count
4396         return depth - 1;
4397 }
4398
4399 static depth_type getItemDepth(ParIterator const & it)
4400 {
4401         Paragraph const & par = *it;
4402         LabelType const labeltype = par.layout().labeltype;
4403
4404         if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4405                 return 0;
4406
4407         // this will hold the lowest depth encountered up to now.
4408         depth_type min_depth = getDepth(it);
4409         ParIterator prev_it = it;
4410         while (true) {
4411                 if (prev_it.pit())
4412                         --prev_it.top().pit();
4413                 else {
4414                         // start of nested inset: go to outer par
4415                         prev_it.pop_back();
4416                         if (prev_it.empty()) {
4417                                 // start of document: nothing to do
4418                                 return 0;
4419                         }
4420                 }
4421
4422                 // We search for the first paragraph with same label
4423                 // that is not more deeply nested.
4424                 Paragraph & prev_par = *prev_it;
4425                 depth_type const prev_depth = getDepth(prev_it);
4426                 if (labeltype == prev_par.layout().labeltype) {
4427                         if (prev_depth < min_depth)
4428                                 return prev_par.itemdepth + 1;
4429                         if (prev_depth == min_depth)
4430                                 return prev_par.itemdepth;
4431                 }
4432                 min_depth = min(min_depth, prev_depth);
4433                 // small optimization: if we are at depth 0, we won't
4434                 // find anything else
4435                 if (prev_depth == 0)
4436                         return 0;
4437         }
4438 }
4439
4440
4441 static bool needEnumCounterReset(ParIterator const & it)
4442 {
4443         Paragraph const & par = *it;
4444         LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
4445         depth_type const cur_depth = par.getDepth();
4446         ParIterator prev_it = it;
4447         while (prev_it.pit()) {
4448                 --prev_it.top().pit();
4449                 Paragraph const & prev_par = *prev_it;
4450                 if (prev_par.getDepth() <= cur_depth)
4451                         return  prev_par.layout().labeltype != LABEL_ENUMERATE;
4452         }
4453         // start of nested inset: reset
4454         return true;
4455 }
4456
4457
4458 // set the label of a paragraph. This includes the counters.
4459 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4460 {
4461         BufferParams const & bp = owner_->masterBuffer()->params();
4462         DocumentClass const & textclass = bp.documentClass();
4463         Paragraph & par = it.paragraph();
4464         Layout const & layout = par.layout();
4465         Counters & counters = textclass.counters();
4466
4467         if (par.params().startOfAppendix()) {
4468                 // We want to reset the counter corresponding to toplevel sectioning
4469                 Layout const & lay = textclass.getTOCLayout();
4470                 docstring const cnt = lay.counter;
4471                 if (!cnt.empty())
4472                         counters.reset(cnt);
4473                 counters.appendix(true);
4474         }
4475         par.params().appendix(counters.appendix());
4476
4477         // Compute the item depth of the paragraph
4478         par.itemdepth = getItemDepth(it);
4479
4480         if (layout.margintype == MARGIN_MANUAL) {
4481                 if (par.params().labelWidthString().empty())
4482                         par.params().labelWidthString(par.expandLabel(layout, bp));
4483         } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4484                 // we do not need to do anything here, since the empty case is
4485                 // handled during export.
4486         } else {
4487                 par.params().labelWidthString(docstring());
4488         }
4489
4490         switch(layout.labeltype) {
4491         case LABEL_ITEMIZE: {
4492                 // At some point of time we should do something more
4493                 // clever here, like:
4494                 //   par.params().labelString(
4495                 //    bp.user_defined_bullet(par.itemdepth).getText());
4496                 // for now, use a simple hardcoded label
4497                 docstring itemlabel;
4498                 switch (par.itemdepth) {
4499                 case 0:
4500                         itemlabel = char_type(0x2022);
4501                         break;
4502                 case 1:
4503                         itemlabel = char_type(0x2013);
4504                         break;
4505                 case 2:
4506                         itemlabel = char_type(0x2217);
4507                         break;
4508                 case 3:
4509                         itemlabel = char_type(0x2219); // or 0x00b7
4510                         break;
4511                 }
4512                 par.params().labelString(itemlabel);
4513                 break;
4514         }
4515
4516         case LABEL_ENUMERATE: {
4517                 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4518
4519                 switch (par.itemdepth) {
4520                 case 2:
4521                         enumcounter += 'i';
4522                 case 1:
4523                         enumcounter += 'i';
4524                 case 0:
4525                         enumcounter += 'i';
4526                         break;
4527                 case 3:
4528                         enumcounter += "iv";
4529                         break;
4530                 default:
4531                         // not a valid enumdepth...
4532                         break;
4533                 }
4534
4535                 // Maybe we have to reset the enumeration counter.
4536                 if (needEnumCounterReset(it))
4537                         counters.reset(enumcounter);
4538                 counters.step(enumcounter, utype);
4539
4540                 string const & lang = par.getParLanguage(bp)->code();
4541                 par.params().labelString(counters.theCounter(enumcounter, lang));
4542
4543                 break;
4544         }
4545
4546         case LABEL_SENSITIVE: {
4547                 string const & type = counters.current_float();
4548                 docstring full_label;
4549                 if (type.empty())
4550                         full_label = owner_->B_("Senseless!!! ");
4551                 else {
4552                         docstring name = owner_->B_(textclass.floats().getType(type).name());
4553                         if (counters.hasCounter(from_utf8(type))) {
4554                                 string const & lang = par.getParLanguage(bp)->code();
4555                                 counters.step(from_utf8(type), utype);
4556                                 full_label = bformat(from_ascii("%1$s %2$s:"),
4557                                                      name,
4558                                                      counters.theCounter(from_utf8(type), lang));
4559                         } else
4560                                 full_label = bformat(from_ascii("%1$s #:"), name);
4561                 }
4562                 par.params().labelString(full_label);
4563                 break;
4564         }
4565
4566         case LABEL_NO_LABEL:
4567                 par.params().labelString(docstring());
4568                 break;
4569
4570         case LABEL_ABOVE:
4571         case LABEL_CENTERED:
4572         case LABEL_STATIC: {
4573                 docstring const & lcounter = layout.counter;
4574                 if (!lcounter.empty()) {
4575                         if (layout.toclevel <= bp.secnumdepth
4576                                                 && (layout.latextype != LATEX_ENVIRONMENT
4577                                         || it.text()->isFirstInSequence(it.pit()))) {
4578                                 if (counters.hasCounter(lcounter))
4579                                         counters.step(lcounter, utype);
4580                                 par.params().labelString(par.expandLabel(layout, bp));
4581                         } else
4582                                 par.params().labelString(docstring());
4583                 } else
4584                         par.params().labelString(par.expandLabel(layout, bp));
4585                 break;
4586         }
4587
4588         case LABEL_MANUAL:
4589         case LABEL_BIBLIO:
4590                 par.params().labelString(par.expandLabel(layout, bp));
4591         }
4592 }
4593
4594
4595 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4596 {
4597         // LASSERT: Is it safe to continue here, or should we just return?
4598         LASSERT(parit.pit() == 0, /**/);
4599
4600         // Set the position of the text in the buffer to be able
4601         // to resolve macros in it.
4602         parit.text()->setMacrocontextPosition(parit);
4603
4604         depth_type maxdepth = 0;
4605         pit_type const lastpit = parit.lastpit();
4606         for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4607                 // reduce depth if necessary
4608                 if (parit->params().depth() > maxdepth) {
4609                         /** FIXME: this function is const, but
4610                          * nevertheless it modifies the buffer. To be
4611                          * cleaner, one should modify the buffer in
4612                          * another function, which is actually
4613                          * non-const. This would however be costly in
4614                          * terms of code duplication.
4615                          */
4616                         const_cast<Buffer *>(this)->undo().recordUndo(CursorData(parit));
4617                         parit->params().depth(maxdepth);
4618                 }
4619                 maxdepth = parit->getMaxDepthAfter();
4620
4621                 if (utype == OutputUpdate) {
4622                         // track the active counters
4623                         // we have to do this for the master buffer, since the local
4624                         // buffer isn't tracking anything.
4625                         masterBuffer()->params().documentClass().counters().
4626                                         setActiveLayout(parit->layout());
4627                 }
4628
4629                 // set the counter for this paragraph
4630                 d->setLabel(parit, utype);
4631
4632                 // now the insets
4633                 InsetList::const_iterator iit = parit->insetList().begin();
4634                 InsetList::const_iterator end = parit->insetList().end();
4635                 for (; iit != end; ++iit) {
4636                         parit.pos() = iit->pos;
4637                         iit->inset->updateBuffer(parit, utype);
4638                 }
4639         }
4640 }
4641
4642
4643 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4644         WordLangTuple & word_lang, docstring_list & suggestions) const
4645 {
4646         int progress = 0;
4647         WordLangTuple wl;
4648         suggestions.clear();
4649         word_lang = WordLangTuple();
4650         bool const to_end = to.empty();
4651         DocIterator const end = to_end ? doc_iterator_end(this) : to;
4652         // OK, we start from here.
4653         for (; from != end; from.forwardPos()) {
4654                 // We are only interested in text so remove the math CursorSlice.
4655                 while (from.inMathed()) {
4656                         from.pop_back();
4657                         from.pos()++;
4658                 }
4659                 // If from is at the end of the document (which is possible
4660                 // when leaving the mathed) LyX will crash later otherwise.
4661                 if (from.atEnd() || (!to_end && from >= end))
4662                         break;
4663                 to = from;
4664                 from.paragraph().spellCheck();
4665                 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4666                 if (SpellChecker::misspelled(res)) {
4667                         word_lang = wl;
4668                         break;
4669                 }
4670
4671                 // Do not increase progress when from == to, otherwise the word
4672                 // count will be wrong.
4673                 if (from != to) {
4674                         from = to;
4675                         ++progress;
4676                 }
4677         }
4678         return progress;
4679 }
4680
4681
4682 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
4683 {
4684         bool inword = false;
4685         word_count_ = 0;
4686         char_count_ = 0;
4687         blank_count_ = 0;
4688
4689         for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
4690                 if (!dit.inTexted()) {
4691                         dit.forwardPos();
4692                         continue;
4693                 }
4694
4695                 Paragraph const & par = dit.paragraph();
4696                 pos_type const pos = dit.pos();
4697
4698                 // Copied and adapted from isWordSeparator() in Paragraph
4699                 if (pos == dit.lastpos()) {
4700                         inword = false;
4701                 } else {
4702                         Inset const * ins = par.getInset(pos);
4703                         if (ins && skipNoOutput && !ins->producesOutput()) {
4704                                 // skip this inset
4705                                 ++dit.top().pos();
4706                                 // stop if end of range was skipped
4707                                 if (!to.atEnd() && dit >= to)
4708                                         break;
4709                                 continue;
4710                         } else if (!par.isDeleted(pos)) {
4711                                 if (par.isWordSeparator(pos))
4712                                         inword = false;
4713                                 else if (!inword) {
4714                                         ++word_count_;
4715                                         inword = true;
4716                                 }
4717                                 if (ins && ins->isLetter())
4718                                         ++char_count_;
4719                                 else if (ins && ins->isSpace())
4720                                         ++blank_count_;
4721                                 else {
4722                                         char_type const c = par.getChar(pos);
4723                                         if (isPrintableNonspace(c))
4724                                                 ++char_count_;
4725                                         else if (isSpace(c))
4726                                                 ++blank_count_;
4727                                 }
4728                         }
4729                 }
4730                 dit.forwardPos();
4731         }
4732 }
4733
4734
4735 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
4736 {
4737         d->updateStatistics(from, to, skipNoOutput);
4738 }
4739
4740
4741 int Buffer::wordCount() const
4742 {
4743         return d->wordCount();
4744 }
4745
4746
4747 int Buffer::charCount(bool with_blanks) const
4748 {
4749         return d->charCount(with_blanks);
4750 }
4751
4752
4753 Buffer::ReadStatus Buffer::reload()
4754 {
4755         setBusy(true);
4756         // c.f. bug http://www.lyx.org/trac/ticket/6587
4757         removeAutosaveFile();
4758         // e.g., read-only status could have changed due to version control
4759         d->filename.refresh();
4760         docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4761
4762         // clear parent. this will get reset if need be.
4763         d->setParent(0);
4764         ReadStatus const status = loadLyXFile();
4765         if (status == ReadSuccess) {
4766                 updateBuffer();
4767                 changed(true);
4768                 updateTitles();
4769                 markClean();
4770                 message(bformat(_("Document %1$s reloaded."), disp_fn));
4771                 d->undo_.clear();
4772         } else {
4773                 message(bformat(_("Could not reload document %1$s."), disp_fn));
4774         }
4775         setBusy(false);
4776         removePreviews();
4777         updatePreviews();
4778         errors("Parse");
4779         return status;
4780 }
4781
4782
4783 bool Buffer::saveAs(FileName const & fn)
4784 {
4785         FileName const old_name = fileName();
4786         FileName const old_auto = getAutosaveFileName();
4787         bool const old_unnamed = isUnnamed();
4788
4789         setFileName(fn);
4790         markDirty();
4791         setUnnamed(false);
4792
4793         if (save()) {
4794                 // bring the autosave file with us, just in case.
4795                 moveAutosaveFile(old_auto);
4796                 // validate version control data and
4797                 // correct buffer title
4798                 lyxvc().file_found_hook(fileName());
4799                 updateTitles();
4800                 // the file has now been saved to the new location.
4801                 // we need to check that the locations of child buffers
4802                 // are still valid.
4803                 checkChildBuffers();
4804                 checkMasterBuffer();
4805                 return true;
4806         } else {
4807                 // save failed
4808                 // reset the old filename and unnamed state
4809                 setFileName(old_name);
4810                 setUnnamed(old_unnamed);
4811                 return false;
4812         }
4813 }
4814
4815
4816 // FIXME We could do better here, but it is complicated. What would be
4817 // nice is to offer either (a) to save the child buffer to an appropriate
4818 // location, so that it would "move with the master", or else (b) to update
4819 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4820 // complicated, because the code for this lives in GuiView.
4821 void Buffer::checkChildBuffers()
4822 {
4823         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4824         Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4825         for (; it != en; ++it) {
4826                 DocIterator dit = it->second;
4827                 Buffer * cbuf = const_cast<Buffer *>(it->first);
4828                 if (!cbuf || !theBufferList().isLoaded(cbuf))
4829                         continue;
4830                 Inset * inset = dit.nextInset();
4831                 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4832                 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4833                 docstring const & incfile = inset_inc->getParam("filename");
4834                 string oldloc = cbuf->absFileName();
4835                 string newloc = makeAbsPath(to_utf8(incfile),
4836                                 onlyPath(absFileName())).absFileName();
4837                 if (oldloc == newloc)
4838                         continue;
4839                 // the location of the child file is incorrect.
4840                 Alert::warning(_("Included File Invalid"),
4841                                 bformat(_("Saving this document to a new location has made the file:\n"
4842                                 "  %1$s\n"
4843                                 "inaccessible. You will need to update the included filename."),
4844                                 from_utf8(oldloc)));
4845                 cbuf->setParent(0);
4846                 inset_inc->setChildBuffer(0);
4847         }
4848         // invalidate cache of children
4849         d->children_positions.clear();
4850         d->position_to_children.clear();
4851 }
4852
4853
4854 // If a child has been saved under a different name/path, it might have been
4855 // orphaned. Therefore the master needs to be reset (bug 8161).
4856 void Buffer::checkMasterBuffer()
4857 {
4858         Buffer const * const master = masterBuffer();
4859         if (master == this)
4860                 return;
4861
4862         // necessary to re-register the child (bug 5873)
4863         // FIXME: clean up updateMacros (here, only
4864         // child registering is needed).
4865         master->updateMacros();
4866         // (re)set master as master buffer, but only
4867         // if we are a real child
4868         if (master->isChild(this))
4869                 setParent(master);
4870         else
4871                 setParent(0);
4872 }
4873
4874 } // namespace lyx