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