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