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