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