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