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