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