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