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