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