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