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