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