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