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