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