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