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