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