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