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