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