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