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