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