]> git.lyx.org Git - lyx.git/blob - src/Buffer.cpp
Expand comment
[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 label 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, stop here.
2501         // This is important in the case when the bibliography
2502         // environment (rather than Bib[la]TeX) is used.
2503         // In that case, the timestamp check below gives no
2504         // sensible result. Rather than that, the cache will
2505         // be invalidated explicitly via invalidateBibInfoCache()
2506         // by the Bibitem inset.
2507         // Same applies for bib encoding changes, which trigger
2508         // invalidateBibInfoCache() by InsetBibtex.
2509         if (!d->bibinfo_cache_valid_)
2510                 return;
2511
2512         // we'll assume it's ok and change this if it's not
2513         d->bibinfo_cache_valid_ = true;
2514         d->cite_labels_valid_ = true;
2515
2516         // compare the cached timestamps with the actual ones.
2517         docstring_list const & bibfiles_cache = getBibfiles();
2518         for (auto const & bf : bibfiles_cache) {
2519                 FileName const fn = getBibfilePath(bf);
2520                 time_t lastw = fn.lastModified();
2521                 time_t prevw = d->bibfile_status_[fn];
2522                 if (lastw != prevw) {
2523                         d->bibinfo_cache_valid_ = false;
2524                         d->cite_labels_valid_ = false;
2525                         d->bibfile_status_[fn] = lastw;
2526                 }
2527         }
2528 }
2529
2530
2531 void Buffer::clearBibFileCache() const
2532 {
2533         bibfileCache.clear();
2534 }
2535
2536
2537 void Buffer::reloadBibInfoCache(bool const force) const
2538 {
2539         // we should not need to do this for internal buffers
2540         if (isInternal())
2541                 return;
2542
2543         // use the master's cache
2544         Buffer const * const tmp = masterBuffer();
2545         if (tmp != this) {
2546                 tmp->reloadBibInfoCache(force);
2547                 return;
2548         }
2549
2550         if (!force) {
2551                 checkIfBibInfoCacheIsValid();
2552                 if (d->bibinfo_cache_valid_)
2553                         return;
2554         }
2555
2556         LYXERR(Debug::FILES, "Bibinfo cache was invalid.");
2557         // re-read file locations when this info changes
2558         // FIXME Is this sufficient? Or should we also force that
2559         // in some other cases? If so, then it is easy enough to
2560         // add the following line in some other places.
2561         clearBibFileCache();
2562         d->bibinfo_.clear();
2563         FileNameList checkedFiles;
2564         collectBibKeys(checkedFiles);
2565         d->bibinfo_cache_valid_ = true;
2566 }
2567
2568
2569 void Buffer::collectBibKeys(FileNameList & checkedFiles) const
2570 {
2571         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2572                 it->collectBibKeys(it, checkedFiles);
2573 }
2574
2575
2576 void Buffer::addBiblioInfo(BiblioInfo const & bin) const
2577 {
2578         // We add the biblio info to the master buffer,
2579         // if there is one, but also to every single buffer,
2580         // in case a child is compiled alone.
2581         BiblioInfo & bi = d->bibinfo_;
2582         bi.mergeBiblioInfo(bin);
2583
2584         if (parent() != 0) {
2585                 BiblioInfo & masterbi = parent()->d->bibinfo_;
2586                 masterbi.mergeBiblioInfo(bin);
2587         }
2588 }
2589
2590
2591 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bin) const
2592 {
2593         // We add the bibtex info to the master buffer,
2594         // if there is one, but also to every single buffer,
2595         // in case a child is compiled alone.
2596         BiblioInfo & bi = d->bibinfo_;
2597         bi[key] = bin;
2598
2599         if (parent() != 0) {
2600                 BiblioInfo & masterbi = masterBuffer()->d->bibinfo_;
2601                 masterbi[key] = bin;
2602         }
2603 }
2604
2605
2606 void Buffer::makeCitationLabels() const
2607 {
2608         Buffer const * const master = masterBuffer();
2609         return d->bibinfo_.makeCitationLabels(*master);
2610 }
2611
2612
2613 void Buffer::invalidateCiteLabels() const
2614 {
2615         masterBuffer()->d->cite_labels_valid_ = false;
2616 }
2617
2618 bool Buffer::citeLabelsValid() const
2619 {
2620         return masterBuffer()->d->cite_labels_valid_;
2621 }
2622
2623
2624 void Buffer::removeBiblioTempFiles() const
2625 {
2626         // We remove files that contain LaTeX commands specific to the
2627         // particular bibliographic style being used, in order to avoid
2628         // LaTeX errors when we switch style.
2629         FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2630         FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2631         LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2632         aux_file.removeFile();
2633         LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2634         bbl_file.removeFile();
2635         // Also for the parent buffer
2636         Buffer const * const pbuf = parent();
2637         if (pbuf)
2638                 pbuf->removeBiblioTempFiles();
2639 }
2640
2641
2642 bool Buffer::isDepClean(string const & name) const
2643 {
2644         DepClean::const_iterator const it = d->dep_clean.find(name);
2645         if (it == d->dep_clean.end())
2646                 return true;
2647         return it->second;
2648 }
2649
2650
2651 void Buffer::markDepClean(string const & name)
2652 {
2653         d->dep_clean[name] = true;
2654 }
2655
2656
2657 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2658 {
2659         if (isInternal()) {
2660                 // FIXME? if there is an Buffer LFUN that can be dispatched even
2661                 // if internal, put a switch '(cmd.action)' here.
2662                 return false;
2663         }
2664
2665         bool enable = true;
2666
2667         switch (cmd.action()) {
2668
2669         case LFUN_BUFFER_TOGGLE_READ_ONLY:
2670                 flag.setOnOff(hasReadonlyFlag());
2671                 break;
2672
2673                 // FIXME: There is need for a command-line import.
2674                 //case LFUN_BUFFER_IMPORT:
2675
2676         case LFUN_BUFFER_AUTO_SAVE:
2677                 break;
2678
2679         case LFUN_BUFFER_EXPORT_CUSTOM:
2680                 // FIXME: Nothing to check here?
2681                 break;
2682
2683         case LFUN_BUFFER_EXPORT: {
2684                 docstring const arg = cmd.argument();
2685                 if (arg == "custom") {
2686                         enable = true;
2687                         break;
2688                 }
2689                 string format = (arg.empty() || arg == "default") ?
2690                         params().getDefaultOutputFormat() : to_utf8(arg);
2691                 size_t pos = format.find(' ');
2692                 if (pos != string::npos)
2693                         format = format.substr(0, pos);
2694                 enable = params().isExportable(format, false);
2695                 if (!enable)
2696                         flag.message(bformat(
2697                                              _("Don't know how to export to format: %1$s"), arg));
2698                 break;
2699         }
2700
2701         case LFUN_BUILD_PROGRAM:
2702                 enable = params().isExportable("program", false);
2703                 break;
2704
2705         case LFUN_BRANCH_ACTIVATE:
2706         case LFUN_BRANCH_DEACTIVATE:
2707         case LFUN_BRANCH_MASTER_ACTIVATE:
2708         case LFUN_BRANCH_MASTER_DEACTIVATE: {
2709                 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2710                                      || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2711                 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2712                         : params().branchlist();
2713                 docstring const branchName = cmd.argument();
2714                 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2715                 break;
2716         }
2717
2718         case LFUN_BRANCH_ADD:
2719         case LFUN_BRANCHES_RENAME:
2720                 // if no Buffer is present, then of course we won't be called!
2721                 break;
2722
2723         case LFUN_BUFFER_LANGUAGE:
2724                 enable = !isReadonly();
2725                 break;
2726
2727         case LFUN_BUFFER_VIEW_CACHE:
2728                 (d->preview_file_).refresh();
2729                 enable = (d->preview_file_).exists() && !(d->preview_file_).isFileEmpty();
2730                 break;
2731
2732         case LFUN_CHANGES_TRACK:
2733                 flag.setEnabled(true);
2734                 flag.setOnOff(params().track_changes);
2735                 break;
2736
2737         case LFUN_CHANGES_OUTPUT:
2738                 flag.setEnabled(true);
2739                 flag.setOnOff(params().output_changes);
2740                 break;
2741
2742         case LFUN_BUFFER_TOGGLE_COMPRESSION:
2743                 flag.setOnOff(params().compressed);
2744                 break;
2745
2746         case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
2747                 flag.setOnOff(params().output_sync);
2748                 break;
2749
2750         case LFUN_BUFFER_ANONYMIZE:
2751                 break;
2752
2753         default:
2754                 return false;
2755         }
2756         flag.setEnabled(enable);
2757         return true;
2758 }
2759
2760
2761 void Buffer::dispatch(string const & command, DispatchResult & result)
2762 {
2763         return dispatch(lyxaction.lookupFunc(command), result);
2764 }
2765
2766
2767 // NOTE We can end up here even if we have no GUI, because we are called
2768 // by LyX::exec to handled command-line requests. So we may need to check
2769 // whether we have a GUI or not. The boolean use_gui holds this information.
2770 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2771 {
2772         if (isInternal()) {
2773                 // FIXME? if there is an Buffer LFUN that can be dispatched even
2774                 // if internal, put a switch '(cmd.action())' here.
2775                 dr.dispatched(false);
2776                 return;
2777         }
2778         string const argument = to_utf8(func.argument());
2779         // We'll set this back to false if need be.
2780         bool dispatched = true;
2781         // This handles undo groups automagically
2782         UndoGroupHelper ugh(this);
2783
2784         switch (func.action()) {
2785         case LFUN_BUFFER_TOGGLE_READ_ONLY:
2786                 if (lyxvc().inUse()) {
2787                         string log = lyxvc().toggleReadOnly();
2788                         if (!log.empty())
2789                                 dr.setMessage(log);
2790                 }
2791                 else
2792                         setReadonly(!hasReadonlyFlag());
2793                 break;
2794
2795         case LFUN_BUFFER_EXPORT: {
2796                 string const format = (argument.empty() || argument == "default") ?
2797                         params().getDefaultOutputFormat() : argument;
2798                 ExportStatus const status = doExport(format, false);
2799                 dr.setError(status != ExportSuccess);
2800                 if (status != ExportSuccess)
2801                         dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2802                                               from_utf8(format)));
2803                 break;
2804         }
2805
2806         case LFUN_BUILD_PROGRAM: {
2807                 ExportStatus const status = doExport("program", true);
2808                 dr.setError(status != ExportSuccess);
2809                 if (status != ExportSuccess)
2810                         dr.setMessage(_("Error generating literate programming code."));
2811                 break;
2812         }
2813
2814         case LFUN_BUFFER_EXPORT_CUSTOM: {
2815                 string format_name;
2816                 string command = split(argument, format_name, ' ');
2817                 Format const * format = theFormats().getFormat(format_name);
2818                 if (!format) {
2819                         lyxerr << "Format \"" << format_name
2820                                 << "\" not recognized!"
2821                                 << endl;
2822                         break;
2823                 }
2824
2825                 // The name of the file created by the conversion process
2826                 string filename;
2827
2828                 // Output to filename
2829                 if (format->name() == "lyx") {
2830                         string const latexname = latexName(false);
2831                         filename = changeExtension(latexname,
2832                                 format->extension());
2833                         filename = addName(temppath(), filename);
2834
2835                         if (!writeFile(FileName(filename)))
2836                                 break;
2837
2838                 } else {
2839                         doExport(format_name, true, filename);
2840                 }
2841
2842                 // Substitute $$FName for filename
2843                 if (!contains(command, "$$FName"))
2844                         command = "( " + command + " ) < $$FName";
2845                 command = subst(command, "$$FName", filename);
2846
2847                 // Execute the command in the background
2848                 Systemcall call;
2849                 call.startscript(Systemcall::DontWait, command,
2850                                  filePath(), layoutPos());
2851                 break;
2852         }
2853
2854         // FIXME: There is need for a command-line import.
2855         /*
2856         case LFUN_BUFFER_IMPORT:
2857                 doImport(argument);
2858                 break;
2859         */
2860
2861         case LFUN_BUFFER_AUTO_SAVE:
2862                 autoSave();
2863                 resetAutosaveTimers();
2864                 break;
2865
2866         case LFUN_BRANCH_ACTIVATE:
2867         case LFUN_BRANCH_DEACTIVATE:
2868         case LFUN_BRANCH_MASTER_ACTIVATE:
2869         case LFUN_BRANCH_MASTER_DEACTIVATE: {
2870                 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2871                                      || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2872                 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2873                                       : this;
2874
2875                 docstring const branch_name = func.argument();
2876                 // the case without a branch name is handled elsewhere
2877                 if (branch_name.empty()) {
2878                         dispatched = false;
2879                         break;
2880                 }
2881                 Branch * branch = buf->params().branchlist().find(branch_name);
2882                 if (!branch) {
2883                         LYXERR0("Branch " << branch_name << " does not exist.");
2884                         dr.setError(true);
2885                         docstring const msg =
2886                                 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2887                         dr.setMessage(msg);
2888                         break;
2889                 }
2890                 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2891                                        || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2892                 if (branch->isSelected() != activate) {
2893                         buf->undo().recordUndoBufferParams(CursorData());
2894                         branch->setSelected(activate);
2895                         dr.setError(false);
2896                         dr.screenUpdate(Update::Force);
2897                         dr.forceBufferUpdate();
2898                 }
2899                 break;
2900         }
2901
2902         case LFUN_BRANCH_ADD: {
2903                 docstring branchnames = func.argument();
2904                 if (branchnames.empty()) {
2905                         dispatched = false;
2906                         break;
2907                 }
2908                 BranchList & branch_list = params().branchlist();
2909                 vector<docstring> const branches =
2910                         getVectorFromString(branchnames, branch_list.separator());
2911                 docstring msg;
2912                 for (docstring const & branch_name : branches) {
2913                         Branch * branch = branch_list.find(branch_name);
2914                         if (branch) {
2915                                 LYXERR0("Branch " << branch_name << " already exists.");
2916                                 dr.setError(true);
2917                                 if (!msg.empty())
2918                                         msg += ("\n");
2919                                 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2920                         } else {
2921                                 undo().recordUndoBufferParams(CursorData());
2922                                 branch_list.add(branch_name);
2923                                 branch = branch_list.find(branch_name);
2924                                 string const x11hexname = X11hexname(branch->color());
2925                                 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2926                                 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2927                                 dr.setError(false);
2928                                 dr.screenUpdate(Update::Force);
2929                         }
2930                 }
2931                 if (!msg.empty())
2932                         dr.setMessage(msg);
2933                 break;
2934         }
2935
2936         case LFUN_BRANCHES_RENAME: {
2937                 if (func.argument().empty())
2938                         break;
2939
2940                 docstring const oldname = from_utf8(func.getArg(0));
2941                 docstring const newname = from_utf8(func.getArg(1));
2942                 InsetIterator it  = inset_iterator_begin(inset());
2943                 InsetIterator const end = inset_iterator_end(inset());
2944                 bool success = false;
2945                 for (; it != end; ++it) {
2946                         if (it->lyxCode() == BRANCH_CODE) {
2947                                 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2948                                 if (ins.branch() == oldname) {
2949                                         undo().recordUndo(CursorData(it));
2950                                         ins.rename(newname);
2951                                         success = true;
2952                                         continue;
2953                                 }
2954                         }
2955                         if (it->lyxCode() == INCLUDE_CODE) {
2956                                 // get buffer of external file
2957                                 InsetInclude const & ins =
2958                                         static_cast<InsetInclude const &>(*it);
2959                                 Buffer * child = ins.getChildBuffer();
2960                                 if (!child)
2961                                         continue;
2962                                 child->dispatch(func, dr);
2963                         }
2964                 }
2965
2966                 if (success) {
2967                         dr.screenUpdate(Update::Force);
2968                         dr.forceBufferUpdate();
2969                 }
2970                 break;
2971         }
2972
2973         case LFUN_BUFFER_VIEW_CACHE:
2974                 if (!theFormats().view(*this, d->preview_file_,
2975                                   d->preview_format_))
2976                         dr.setMessage(_("Error viewing the output file."));
2977                 break;
2978
2979         case LFUN_CHANGES_TRACK:
2980                 if (params().save_transient_properties)
2981                         undo().recordUndoBufferParams(CursorData());
2982                 params().track_changes = !params().track_changes;
2983                 if (!params().track_changes)
2984                         dr.forceChangesUpdate();
2985                 break;
2986
2987         case LFUN_CHANGES_OUTPUT:
2988                 if (params().save_transient_properties)
2989                         undo().recordUndoBufferParams(CursorData());
2990                 params().output_changes = !params().output_changes;
2991                 if (params().output_changes) {
2992                         bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
2993                         bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
2994                                           LaTeXFeatures::isAvailable("xcolor");
2995
2996                         if (!dvipost && !xcolorulem) {
2997                                 Alert::warning(_("Changes not shown in LaTeX output"),
2998                                                _("Changes will not be highlighted in LaTeX output, "
2999                                                  "because neither dvipost nor xcolor/ulem are installed.\n"
3000                                                  "Please install these packages or redefine "
3001                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
3002                         } else if (!xcolorulem) {
3003                                 Alert::warning(_("Changes not shown in LaTeX output"),
3004                                                _("Changes will not be highlighted in LaTeX output "
3005                                                  "when using pdflatex, because xcolor and ulem are not installed.\n"
3006                                                  "Please install both packages or redefine "
3007                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
3008                         }
3009                 }
3010                 break;
3011
3012         case LFUN_BUFFER_TOGGLE_COMPRESSION:
3013                 // turn compression on/off
3014                 undo().recordUndoBufferParams(CursorData());
3015                 params().compressed = !params().compressed;
3016                 break;
3017
3018         case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
3019                 undo().recordUndoBufferParams(CursorData());
3020                 params().output_sync = !params().output_sync;
3021                 break;
3022
3023         case LFUN_BUFFER_ANONYMIZE: {
3024                 undo().recordUndoFullBuffer(CursorData());
3025                 CursorData cur(doc_iterator_begin(this));
3026                 for ( ; cur ; cur.forwardPar())
3027                         cur.paragraph().anonymize();
3028                 dr.forceBufferUpdate();
3029                 dr.screenUpdate(Update::Force);
3030                 break;
3031         }
3032
3033         default:
3034                 dispatched = false;
3035                 break;
3036         }
3037         dr.dispatched(dispatched);
3038 }
3039
3040
3041 void Buffer::changeLanguage(Language const * from, Language const * to)
3042 {
3043         LASSERT(from, return);
3044         LASSERT(to, return);
3045
3046         for_each(par_iterator_begin(),
3047                  par_iterator_end(),
3048                  bind(&Paragraph::changeLanguage, _1, params(), from, to));
3049 }
3050
3051
3052 bool Buffer::isMultiLingual() const
3053 {
3054         ParConstIterator end = par_iterator_end();
3055         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
3056                 if (it->isMultiLingual(params()))
3057                         return true;
3058
3059         return false;
3060 }
3061
3062
3063 std::set<Language const *> Buffer::getLanguages() const
3064 {
3065         std::set<Language const *> langs;
3066         getLanguages(langs);
3067         return langs;
3068 }
3069
3070
3071 void Buffer::getLanguages(std::set<Language const *> & langs) const
3072 {
3073         ParConstIterator end = par_iterator_end();
3074         // add the buffer language, even if it's not actively used
3075         langs.insert(language());
3076         // iterate over the paragraphs
3077         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
3078                 it->getLanguages(langs);
3079         // also children
3080         ListOfBuffers clist = getDescendents();
3081         for (auto const & cit : clist)
3082                 cit->getLanguages(langs);
3083 }
3084
3085
3086 DocIterator Buffer::getParFromID(int const id) const
3087 {
3088         Buffer * buf = const_cast<Buffer *>(this);
3089         if (id < 0)
3090                 // This means non-existent
3091                 return doc_iterator_end(buf);
3092
3093         for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
3094                 if (it.paragraph().id() == id)
3095                         return it;
3096
3097         return doc_iterator_end(buf);
3098 }
3099
3100
3101 bool Buffer::hasParWithID(int const id) const
3102 {
3103         return !getParFromID(id).atEnd();
3104 }
3105
3106
3107 ParIterator Buffer::par_iterator_begin()
3108 {
3109         return ParIterator(doc_iterator_begin(this));
3110 }
3111
3112
3113 ParIterator Buffer::par_iterator_end()
3114 {
3115         return ParIterator(doc_iterator_end(this));
3116 }
3117
3118
3119 ParConstIterator Buffer::par_iterator_begin() const
3120 {
3121         return ParConstIterator(doc_iterator_begin(this));
3122 }
3123
3124
3125 ParConstIterator Buffer::par_iterator_end() const
3126 {
3127         return ParConstIterator(doc_iterator_end(this));
3128 }
3129
3130
3131 Language const * Buffer::language() const
3132 {
3133         return params().language;
3134 }
3135
3136
3137 docstring const Buffer::B_(string const & l10n) const
3138 {
3139         return params().B_(l10n);
3140 }
3141
3142
3143 bool Buffer::isClean() const
3144 {
3145         return d->lyx_clean;
3146 }
3147
3148
3149 bool Buffer::isChecksumModified() const
3150 {
3151         LASSERT(d->filename.exists(), return false);
3152         return d->checksum_ != d->filename.checksum();
3153 }
3154
3155
3156 void Buffer::saveCheckSum() const
3157 {
3158         FileName const & file = d->filename;
3159         file.refresh();
3160         d->checksum_ = file.exists() ? file.checksum()
3161                 : 0; // in the case of save to a new file.
3162 }
3163
3164
3165 void Buffer::markClean() const
3166 {
3167         if (!d->lyx_clean) {
3168                 d->lyx_clean = true;
3169                 updateTitles();
3170         }
3171         // if the .lyx file has been saved, we don't need an
3172         // autosave
3173         d->bak_clean = true;
3174         d->undo_.markDirty();
3175         clearExternalModification();
3176 }
3177
3178
3179 void Buffer::setUnnamed(bool flag)
3180 {
3181         d->unnamed = flag;
3182 }
3183
3184
3185 bool Buffer::isUnnamed() const
3186 {
3187         return d->unnamed;
3188 }
3189
3190
3191 /// \note
3192 /// Don't check unnamed, here: isInternal() is used in
3193 /// newBuffer(), where the unnamed flag has not been set by anyone
3194 /// yet. Also, for an internal buffer, there should be no need for
3195 /// retrieving fileName() nor for checking if it is unnamed or not.
3196 bool Buffer::isInternal() const
3197 {
3198         return d->internal_buffer;
3199 }
3200
3201
3202 void Buffer::setInternal(bool flag)
3203 {
3204         d->internal_buffer = flag;
3205 }
3206
3207
3208 void Buffer::markDirty()
3209 {
3210         if (d->lyx_clean) {
3211                 d->lyx_clean = false;
3212                 updateTitles();
3213         }
3214         d->bak_clean = false;
3215
3216         for (auto & depit : d->dep_clean)
3217                 depit.second = false;
3218 }
3219
3220
3221 FileName Buffer::fileName() const
3222 {
3223         return d->filename;
3224 }
3225
3226
3227 string Buffer::absFileName() const
3228 {
3229         return d->filename.absFileName();
3230 }
3231
3232
3233 string Buffer::filePath() const
3234 {
3235         string const abs = d->filename.onlyPath().absFileName();
3236         if (abs.empty())
3237                 return abs;
3238         int last = abs.length() - 1;
3239
3240         return abs[last] == '/' ? abs : abs + '/';
3241 }
3242
3243
3244 DocFileName Buffer::getReferencedFileName(string const & fn) const
3245 {
3246         DocFileName result;
3247         if (FileName::isAbsolute(fn) || !FileName::isAbsolute(params().origin))
3248                 result.set(fn, filePath());
3249         else {
3250                 // filePath() ends with a path separator
3251                 FileName const test(filePath() + fn);
3252                 if (test.exists())
3253                         result.set(fn, filePath());
3254                 else
3255                         result.set(fn, params().origin);
3256         }
3257
3258         return result;
3259 }
3260
3261
3262 string const Buffer::prepareFileNameForLaTeX(string const & name,
3263                                              string const & ext, bool nice) const
3264 {
3265         string const fname = makeAbsPath(name, filePath()).absFileName();
3266         if (FileName::isAbsolute(name) || !FileName(fname + ext).isReadableFile())
3267                 return name;
3268         if (!nice)
3269                 return fname;
3270
3271         // FIXME UNICODE
3272         return to_utf8(makeRelPath(from_utf8(fname),
3273                 from_utf8(masterBuffer()->filePath())));
3274 }
3275
3276
3277 vector<docstring> const Buffer::prepareBibFilePaths(OutputParams const & runparams,
3278                                                 docstring_list const & bibfilelist,
3279                                                 bool const add_extension) const
3280 {
3281         // If we are processing the LaTeX file in a temp directory then
3282         // copy the .bib databases to this temp directory, mangling their
3283         // names in the process. Store this mangled name in the list of
3284         // all databases.
3285         // (We need to do all this because BibTeX *really*, *really*
3286         // can't handle "files with spaces" and Windows users tend to
3287         // use such filenames.)
3288         // Otherwise, store the (maybe absolute) path to the original,
3289         // unmangled database name.
3290
3291         vector<docstring> res;
3292
3293         // determine the export format
3294         string const tex_format = flavor2format(runparams.flavor);
3295
3296         // check for spaces in paths
3297         bool found_space = false;
3298
3299         for (auto const & bit : bibfilelist) {
3300                 string utf8input = to_utf8(bit);
3301                 string database =
3302                         prepareFileNameForLaTeX(utf8input, ".bib", runparams.nice);
3303                 FileName try_in_file =
3304                         makeAbsPath(database + ".bib", filePath());
3305                 bool not_from_texmf = try_in_file.isReadableFile();
3306                 // If the file has not been found, try with the real file name
3307                 // (it might come from a child in a sub-directory)
3308                 if (!not_from_texmf) {
3309                         try_in_file = getBibfilePath(bit);
3310                         if (try_in_file.isReadableFile()) {
3311                                 // Check if the file is in texmf
3312                                 FileName kpsefile(findtexfile(changeExtension(utf8input, "bib"), "bib", true));
3313                                 not_from_texmf = kpsefile.empty()
3314                                                 || kpsefile.absFileName() != try_in_file.absFileName();
3315                                 if (not_from_texmf)
3316                                         // If this exists, make path relative to the master
3317                                         // FIXME Unicode
3318                                         database =
3319                                                 removeExtension(prepareFileNameForLaTeX(
3320                                                                                         to_utf8(makeRelPath(from_utf8(try_in_file.absFileName()),
3321                                                                                                                                 from_utf8(filePath()))),
3322                                                                                         ".bib", runparams.nice));
3323                         }
3324                 }
3325
3326                 if (!runparams.inComment && !runparams.dryrun && !runparams.nice &&
3327                     not_from_texmf) {
3328                         // mangledFileName() needs the extension
3329                         DocFileName const in_file = DocFileName(try_in_file);
3330                         database = removeExtension(in_file.mangledFileName());
3331                         FileName const out_file = makeAbsPath(database + ".bib",
3332                                         masterBuffer()->temppath());
3333                         bool const success = in_file.copyTo(out_file);
3334                         if (!success) {
3335                                 LYXERR0("Failed to copy '" << in_file
3336                                        << "' to '" << out_file << "'");
3337                         }
3338                 } else if (!runparams.inComment && runparams.nice && not_from_texmf) {
3339                         runparams.exportdata->addExternalFile(tex_format, try_in_file, database + ".bib");
3340                         if (!isValidLaTeXFileName(database)) {
3341                                 frontend::Alert::warning(_("Invalid filename"),
3342                                          _("The following filename will cause troubles "
3343                                                "when running the exported file through LaTeX: ") +
3344                                              from_utf8(database));
3345                         }
3346                         if (!isValidDVIFileName(database)) {
3347                                 frontend::Alert::warning(_("Problematic filename for DVI"),
3348                                          _("The following filename can cause troubles "
3349                                                "when running the exported file through LaTeX "
3350                                                    "and opening the resulting DVI: ") +
3351                                              from_utf8(database), true);
3352                         }
3353                 }
3354
3355                 if (add_extension)
3356                         database += ".bib";
3357
3358                 // FIXME UNICODE
3359                 docstring const path = from_utf8(latex_path(database));
3360
3361                 if (contains(path, ' '))
3362                         found_space = true;
3363
3364                 if (find(res.begin(), res.end(), path) == res.end())
3365                         res.push_back(path);
3366         }
3367
3368         // Check if there are spaces in the path and warn BibTeX users, if so.
3369         // (biber can cope with such paths)
3370         if (!prefixIs(runparams.bibtex_command, "biber")) {
3371                 // Post this warning only once.
3372                 static bool warned_about_spaces = false;
3373                 if (!warned_about_spaces &&
3374                     runparams.nice && found_space) {
3375                         warned_about_spaces = true;
3376                         Alert::warning(_("Export Warning!"),
3377                                        _("There are spaces in the paths to your BibTeX databases.\n"
3378                                                       "BibTeX will be unable to find them."));
3379                 }
3380         }
3381
3382         return res;
3383 }
3384
3385
3386
3387 string Buffer::layoutPos() const
3388 {
3389         return d->layout_position;
3390 }
3391
3392
3393 void Buffer::setLayoutPos(string const & path)
3394 {
3395         if (path.empty()) {
3396                 d->layout_position.clear();
3397                 return;
3398         }
3399
3400         LATTEST(FileName::isAbsolute(path));
3401
3402         d->layout_position =
3403                 to_utf8(makeRelPath(from_utf8(path), from_utf8(filePath())));
3404
3405         if (d->layout_position.empty())
3406                 d->layout_position = ".";
3407 }
3408
3409
3410 bool Buffer::hasReadonlyFlag() const
3411 {
3412         return d->read_only;
3413 }
3414
3415
3416 bool Buffer::isReadonly() const
3417 {
3418         return hasReadonlyFlag() || notifiesExternalModification();
3419 }
3420
3421
3422 void Buffer::setParent(Buffer const * buffer)
3423 {
3424         // Avoids recursive include.
3425         d->setParent(buffer == this ? 0 : buffer);
3426         updateMacros();
3427 }
3428
3429
3430 Buffer const * Buffer::parent() const
3431 {
3432         return d->parent();
3433 }
3434
3435
3436 ListOfBuffers Buffer::allRelatives() const
3437 {
3438         ListOfBuffers lb = masterBuffer()->getDescendents();
3439         lb.push_front(const_cast<Buffer *>(masterBuffer()));
3440         return lb;
3441 }
3442
3443
3444 Buffer const * Buffer::masterBuffer() const
3445 {
3446         // FIXME Should be make sure we are not in some kind
3447         // of recursive include? A -> B -> A will crash this.
3448         Buffer const * const pbuf = d->parent();
3449         if (!pbuf)
3450                 return this;
3451
3452         return pbuf->masterBuffer();
3453 }
3454
3455
3456 bool Buffer::isChild(Buffer * child) const
3457 {
3458         return d->children_positions.find(child) != d->children_positions.end();
3459 }
3460
3461
3462 DocIterator Buffer::firstChildPosition(Buffer const * child)
3463 {
3464         Impl::BufferPositionMap::iterator it;
3465         it = d->children_positions.find(child);
3466         if (it == d->children_positions.end())
3467                 return DocIterator(this);
3468         return it->second;
3469 }
3470
3471
3472 bool Buffer::hasChildren() const
3473 {
3474         return !d->children_positions.empty();
3475 }
3476
3477
3478 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
3479 {
3480         // loop over children
3481         for (auto const & p : d->children_positions) {
3482                 Buffer * child = const_cast<Buffer *>(p.first);
3483                 // No duplicates
3484                 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
3485                 if (bit != clist.end())
3486                         continue;
3487                 clist.push_back(child);
3488                 if (grand_children)
3489                         // there might be grandchildren
3490                         child->collectChildren(clist, true);
3491         }
3492 }
3493
3494
3495 ListOfBuffers Buffer::getChildren() const
3496 {
3497         ListOfBuffers v;
3498         collectChildren(v, false);
3499         // Make sure we have not included ourselves.
3500         ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3501         if (bit != v.end()) {
3502                 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3503                 v.erase(bit);
3504         }
3505         return v;
3506 }
3507
3508
3509 ListOfBuffers Buffer::getDescendents() const
3510 {
3511         ListOfBuffers v;
3512         collectChildren(v, true);
3513         // Make sure we have not included ourselves.
3514         ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3515         if (bit != v.end()) {
3516                 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3517                 v.erase(bit);
3518         }
3519         return v;
3520 }
3521
3522
3523 template<typename M>
3524 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3525 {
3526         if (m.empty())
3527                 return m.end();
3528
3529         typename M::const_iterator it = m.lower_bound(x);
3530         if (it == m.begin())
3531                 return m.end();
3532
3533         it--;
3534         return it;
3535 }
3536
3537
3538 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3539                                          DocIterator const & pos) const
3540 {
3541         LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3542
3543         // if paragraphs have no macro context set, pos will be empty
3544         if (pos.empty())
3545                 return 0;
3546
3547         // we haven't found anything yet
3548         DocIterator bestPos = owner_->par_iterator_begin();
3549         MacroData const * bestData = 0;
3550
3551         // find macro definitions for name
3552         NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3553         if (nameIt != macros.end()) {
3554                 // find last definition in front of pos or at pos itself
3555                 PositionScopeMacroMap::const_iterator it
3556                         = greatest_below(nameIt->second, pos);
3557                 if (it != nameIt->second.end()) {
3558                         while (true) {
3559                                 // scope ends behind pos?
3560                                 if (pos < it->second.scope) {
3561                                         // Looks good, remember this. If there
3562                                         // is no external macro behind this,
3563                                         // we found the right one already.
3564                                         bestPos = it->first;
3565                                         bestData = &it->second.macro;
3566                                         break;
3567                                 }
3568
3569                                 // try previous macro if there is one
3570                                 if (it == nameIt->second.begin())
3571                                         break;
3572                                 --it;
3573                         }
3574                 }
3575         }
3576
3577         // find macros in included files
3578         PositionScopeBufferMap::const_iterator it
3579                 = greatest_below(position_to_children, pos);
3580         if (it == position_to_children.end())
3581                 // no children before
3582                 return bestData;
3583
3584         while (true) {
3585                 // do we know something better (i.e. later) already?
3586                 if (it->first < bestPos )
3587                         break;
3588
3589                 // scope ends behind pos?
3590                 if (pos < it->second.scope
3591                         && (cloned_buffer_ ||
3592                             theBufferList().isLoaded(it->second.buffer))) {
3593                         // look for macro in external file
3594                         macro_lock = true;
3595                         MacroData const * data
3596                                 = it->second.buffer->getMacro(name, false);
3597                         macro_lock = false;
3598                         if (data) {
3599                                 bestPos = it->first;
3600                                 bestData = data;
3601                                 break;
3602                         }
3603                 }
3604
3605                 // try previous file if there is one
3606                 if (it == position_to_children.begin())
3607                         break;
3608                 --it;
3609         }
3610
3611         // return the best macro we have found
3612         return bestData;
3613 }
3614
3615
3616 MacroData const * Buffer::getMacro(docstring const & name,
3617         DocIterator const & pos, bool global) const
3618 {
3619         if (d->macro_lock)
3620                 return 0;
3621
3622         // query buffer macros
3623         MacroData const * data = d->getBufferMacro(name, pos);
3624         if (data != 0)
3625                 return data;
3626
3627         // If there is a master buffer, query that
3628         Buffer const * const pbuf = d->parent();
3629         if (pbuf) {
3630                 d->macro_lock = true;
3631                 MacroData const * macro = pbuf->getMacro(
3632                         name, *this, false);
3633                 d->macro_lock = false;
3634                 if (macro)
3635                         return macro;
3636         }
3637
3638         if (global) {
3639                 data = MacroTable::globalMacros().get(name);
3640                 if (data != 0)
3641                         return data;
3642         }
3643
3644         return 0;
3645 }
3646
3647
3648 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3649 {
3650         // set scope end behind the last paragraph
3651         DocIterator scope = par_iterator_begin();
3652         scope.pit() = scope.lastpit() + 1;
3653
3654         return getMacro(name, scope, global);
3655 }
3656
3657
3658 MacroData const * Buffer::getMacro(docstring const & name,
3659         Buffer const & child, bool global) const
3660 {
3661         // look where the child buffer is included first
3662         Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3663         if (it == d->children_positions.end())
3664                 return 0;
3665
3666         // check for macros at the inclusion position
3667         return getMacro(name, it->second, global);
3668 }
3669
3670
3671 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3672 {
3673         pit_type const lastpit = it.lastpit();
3674
3675         // look for macros in each paragraph
3676         while (it.pit() <= lastpit) {
3677                 Paragraph & par = it.paragraph();
3678
3679                 // FIXME Can this be done with the new-style iterators?
3680                 // iterate over the insets of the current paragraph
3681                 for (auto const & insit : par.insetList()) {
3682                         it.pos() = insit.pos;
3683
3684                         // is it a nested text inset?
3685                         if (insit.inset->asInsetText()) {
3686                                 // Inset needs its own scope?
3687                                 InsetText const * itext = insit.inset->asInsetText();
3688                                 bool newScope = itext->isMacroScope();
3689
3690                                 // scope which ends just behind the inset
3691                                 DocIterator insetScope = it;
3692                                 ++insetScope.pos();
3693
3694                                 // collect macros in inset
3695                                 it.push_back(CursorSlice(*insit.inset));
3696                                 updateMacros(it, newScope ? insetScope : scope);
3697                                 it.pop_back();
3698                                 continue;
3699                         }
3700
3701                         if (insit.inset->asInsetTabular()) {
3702                                 CursorSlice slice(*insit.inset);
3703                                 size_t const numcells = slice.nargs();
3704                                 for (; slice.idx() < numcells; slice.forwardIdx()) {
3705                                         it.push_back(slice);
3706                                         updateMacros(it, scope);
3707                                         it.pop_back();
3708                                 }
3709                                 continue;
3710                         }
3711
3712                         // is it an external file?
3713                         if (insit.inset->lyxCode() == INCLUDE_CODE) {
3714                                 // get buffer of external file
3715                                 InsetInclude const & incinset =
3716                                         static_cast<InsetInclude const &>(*insit.inset);
3717                                 macro_lock = true;
3718                                 Buffer * child = incinset.getChildBuffer();
3719                                 macro_lock = false;
3720                                 if (!child)
3721                                         continue;
3722
3723                                 // register its position, but only when it is
3724                                 // included first in the buffer
3725                                 if (children_positions.find(child) ==
3726                                         children_positions.end())
3727                                                 children_positions[child] = it;
3728
3729                                 // register child with its scope
3730                                 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3731                                 continue;
3732                         }
3733
3734                         InsetMath * im = insit.inset->asInsetMath();
3735                         if (doing_export && im)  {
3736                                 InsetMathHull * hull = im->asHullInset();
3737                                 if (hull)
3738                                         hull->recordLocation(it);
3739                         }
3740
3741                         if (insit.inset->lyxCode() != MATHMACRO_CODE)
3742                                 continue;
3743
3744                         // get macro data
3745                         InsetMathMacroTemplate & macroTemplate =
3746                                 *insit.inset->asInsetMath()->asMacroTemplate();
3747                         MacroContext mc(owner_, it);
3748                         macroTemplate.updateToContext(mc);
3749
3750                         // valid?
3751                         bool valid = macroTemplate.validMacro();
3752                         // FIXME: Should be fixNameAndCheckIfValid() in fact,
3753                         // then the BufferView's cursor will be invalid in
3754                         // some cases which leads to crashes.
3755                         if (!valid)
3756                                 continue;
3757
3758                         // register macro
3759                         // FIXME (Abdel), I don't understand why we pass 'it' here
3760                         // instead of 'macroTemplate' defined above... is this correct?
3761                         macros[macroTemplate.name()][it] =
3762                                 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3763                 }
3764
3765                 // next paragraph
3766                 it.pit()++;
3767                 it.pos() = 0;
3768         }
3769 }
3770
3771
3772 void Buffer::updateMacros() const
3773 {
3774         if (d->macro_lock)
3775                 return;
3776
3777         LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3778
3779         // start with empty table
3780         d->macros.clear();
3781         d->children_positions.clear();
3782         d->position_to_children.clear();
3783
3784         // Iterate over buffer, starting with first paragraph
3785         // The scope must be bigger than any lookup DocIterator
3786         // later. For the global lookup, lastpit+1 is used, hence
3787         // we use lastpit+2 here.
3788         DocIterator it = par_iterator_begin();
3789         DocIterator outerScope = it;
3790         outerScope.pit() = outerScope.lastpit() + 2;
3791         d->updateMacros(it, outerScope);
3792 }
3793
3794
3795 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3796 {
3797         InsetIterator it  = inset_iterator_begin(inset());
3798         InsetIterator const end = inset_iterator_end(inset());
3799         for (; it != end; ++it) {
3800                 if (it->lyxCode() == BRANCH_CODE) {
3801                         InsetBranch & br = static_cast<InsetBranch &>(*it);
3802                         docstring const name = br.branch();
3803                         if (!from_master && !params().branchlist().find(name))
3804                                 result.push_back(name);
3805                         else if (from_master && !masterBuffer()->params().branchlist().find(name))
3806                                 result.push_back(name);
3807                         continue;
3808                 }
3809                 if (it->lyxCode() == INCLUDE_CODE) {
3810                         // get buffer of external file
3811                         InsetInclude const & ins =
3812                                 static_cast<InsetInclude const &>(*it);
3813                         Buffer * child = ins.getChildBuffer();
3814                         if (!child)
3815                                 continue;
3816                         child->getUsedBranches(result, true);
3817                 }
3818         }
3819         // remove duplicates
3820         result.unique();
3821 }
3822
3823
3824 void Buffer::updateMacroInstances(UpdateType utype) const
3825 {
3826         LYXERR(Debug::MACROS, "updateMacroInstances for "
3827                 << d->filename.onlyFileName());
3828         DocIterator it = doc_iterator_begin(this);
3829         it.forwardInset();
3830         DocIterator const end = doc_iterator_end(this);
3831         for (; it != end; it.forwardInset()) {
3832                 // look for MathData cells in InsetMathNest insets
3833                 InsetMath * minset = it.nextInset()->asInsetMath();
3834                 if (!minset)
3835                         continue;
3836
3837                 // update macro in all cells of the InsetMathNest
3838                 DocIterator::idx_type n = minset->nargs();
3839                 MacroContext mc = MacroContext(this, it);
3840                 for (DocIterator::idx_type i = 0; i < n; ++i) {
3841                         MathData & data = minset->cell(i);
3842                         data.updateMacros(0, mc, utype, 0);
3843                 }
3844         }
3845 }
3846
3847
3848 void Buffer::listMacroNames(MacroNameSet & macros) const
3849 {
3850         if (d->macro_lock)
3851                 return;
3852
3853         d->macro_lock = true;
3854
3855         // loop over macro names
3856         for (auto const & nameit : d->macros)
3857                 macros.insert(nameit.first);
3858
3859         // loop over children
3860         for (auto const & p : d->children_positions) {
3861                 Buffer * child = const_cast<Buffer *>(p.first);
3862                 // The buffer might have been closed (see #10766).
3863                 if (theBufferList().isLoaded(child))
3864                         child->listMacroNames(macros);
3865         }
3866
3867         // call parent
3868         Buffer const * const pbuf = d->parent();
3869         if (pbuf)
3870                 pbuf->listMacroNames(macros);
3871
3872         d->macro_lock = false;
3873 }
3874
3875
3876 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3877 {
3878         Buffer const * const pbuf = d->parent();
3879         if (!pbuf)
3880                 return;
3881
3882         MacroNameSet names;
3883         pbuf->listMacroNames(names);
3884
3885         // resolve macros
3886         for (auto const & mit : names) {
3887                 // defined?
3888                 MacroData const * data = pbuf->getMacro(mit, *this, false);
3889                 if (data) {
3890                         macros.insert(data);
3891
3892                         // we cannot access the original InsetMathMacroTemplate anymore
3893                         // here to calls validate method. So we do its work here manually.
3894                         // FIXME: somehow make the template accessible here.
3895                         if (data->optionals() > 0)
3896                                 features.require("xargs");
3897                 }
3898         }
3899 }
3900
3901
3902 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3903 {
3904         if (d->parent())
3905                 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3906
3907         // In what follows, we look whether we find an active label
3908         // with the given string in the cache. If so, return its
3909         // references cache. If we only find an inactive one, return
3910         // that (the last we find, coincidentally). If we find nothing,
3911         // return an empty references cache.
3912         static LabelInfo linfo;
3913         linfo.inset = nullptr;
3914         linfo.references = References();
3915         linfo.active = false;
3916         bool have_inactive = false;
3917         for (auto & rc : d->ref_cache_) {
3918                 if (rc.label == label) {
3919                         if (rc.active)
3920                                 return rc.references;
3921                         else {
3922                                 linfo = rc;
3923                                 have_inactive = true;
3924                         }
3925                 }
3926         }
3927
3928         if (!have_inactive)
3929                 // We found nothing, so insert the empty one to the cache
3930                 // for further processing
3931                 d->ref_cache_.push_back(linfo);
3932
3933         return linfo.references;
3934 }
3935
3936
3937 Buffer::References const & Buffer::references(docstring const & label) const
3938 {
3939         return const_cast<Buffer *>(this)->getReferenceCache(label);
3940 }
3941
3942
3943 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3944 {
3945         References & refs = getReferenceCache(label);
3946         refs.push_back(make_pair(inset, it));
3947 }
3948
3949
3950 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il,
3951                            bool const active)
3952 {
3953         LabelInfo linfo;
3954         linfo.label = label;
3955         linfo.inset = il;
3956         linfo.active = active;
3957         masterBuffer()->d->ref_cache_.push_back(linfo);
3958 }
3959
3960
3961 InsetLabel const * Buffer::insetLabel(docstring const & label,
3962                                       bool const active) const
3963 {
3964         for (auto & rc : masterBuffer()->d->ref_cache_) {
3965                 if (rc.label == label && (rc.active || !active))
3966                         return rc.inset;
3967         }
3968         return nullptr;
3969 }
3970
3971
3972 bool Buffer::activeLabel(docstring const & label) const
3973 {
3974         if (!insetLabel(label, true))
3975                 return false;
3976
3977         return true;
3978 }
3979
3980
3981 void Buffer::clearReferenceCache() const
3982 {
3983         if (!d->parent())
3984                 d->ref_cache_.clear();
3985 }
3986
3987
3988 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
3989 {
3990         //FIXME: This does not work for child documents yet.
3991         reloadBibInfoCache();
3992
3993         // Check if the label 'from' appears more than once
3994         vector<docstring> labels;
3995         for (auto const & bibit : masterBibInfo())
3996                 labels.push_back(bibit.first);
3997
3998         if (count(labels.begin(), labels.end(), from) > 1)
3999                 return;
4000
4001         string const paramName = "key";
4002         InsetIterator it = inset_iterator_begin(inset());
4003         for (; it; ++it) {
4004                 if (it->lyxCode() != CITE_CODE)
4005                         continue;
4006                 InsetCommand * inset = it->asInsetCommand();
4007                 docstring const oldValue = inset->getParam(paramName);
4008                 if (oldValue == from)
4009                         inset->setParam(paramName, to);
4010         }
4011 }
4012
4013 // returns NULL if id-to-row conversion is unsupported
4014 unique_ptr<TexRow> Buffer::getSourceCode(odocstream & os, string const & format,
4015                                          pit_type par_begin, pit_type par_end,
4016                                          OutputWhat output, bool master) const
4017 {
4018         unique_ptr<TexRow> texrow;
4019         OutputParams runparams(&params().encoding());
4020         runparams.nice = true;
4021         runparams.flavor = params().getOutputFlavor(format);
4022         runparams.linelen = lyxrc.plaintext_linelen;
4023         // No side effect of file copying and image conversion
4024         runparams.dryrun = true;
4025
4026         // Some macros rely on font encoding
4027         runparams.main_fontenc = params().main_font_encoding();
4028
4029         if (output == CurrentParagraph) {
4030                 runparams.par_begin = par_begin;
4031                 runparams.par_end = par_end;
4032                 if (par_begin + 1 == par_end) {
4033                         os << "% "
4034                            << bformat(_("Preview source code for paragraph %1$d"), par_begin)
4035                            << "\n\n";
4036                 } else {
4037                         os << "% "
4038                            << bformat(_("Preview source code from paragraph %1$s to %2$s"),
4039                                         convert<docstring>(par_begin),
4040                                         convert<docstring>(par_end - 1))
4041                            << "\n\n";
4042                 }
4043                 // output paragraphs
4044                 if (runparams.flavor == OutputParams::LYX) {
4045                         Paragraph const & par = text().paragraphs()[par_begin];
4046                         ostringstream ods;
4047                         depth_type dt = par.getDepth();
4048                         par.write(ods, params(), dt);
4049                         os << from_utf8(ods.str());
4050                 } else if (runparams.flavor == OutputParams::HTML) {
4051                         XHTMLStream xs(os);
4052                         setMathFlavor(runparams);
4053                         xhtmlParagraphs(text(), *this, xs, runparams);
4054                 } else if (runparams.flavor == OutputParams::TEXT) {
4055                         bool dummy = false;
4056                         // FIXME Handles only one paragraph, unlike the others.
4057                         // Probably should have some routine with a signature like them.
4058                         writePlaintextParagraph(*this,
4059                                 text().paragraphs()[par_begin], os, runparams, dummy);
4060                 } else if (params().isDocBook()) {
4061                         docbookParagraphs(text(), *this, os, runparams);
4062                 } else {
4063                         // If we are previewing a paragraph, even if this is the
4064                         // child of some other buffer, let's cut the link here,
4065                         // so that no concurring settings from the master
4066                         // (e.g. branch state) interfere (see #8101).
4067                         if (!master)
4068                                 d->ignore_parent = true;
4069                         // We need to validate the Buffer params' features here
4070                         // in order to know if we should output polyglossia
4071                         // macros (instead of babel macros)
4072                         LaTeXFeatures features(*this, params(), runparams);
4073                         validate(features);
4074                         runparams.use_polyglossia = features.usePolyglossia();
4075                         // latex or literate
4076                         otexstream ots(os);
4077                         // output above
4078                         ots.texrow().newlines(2);
4079                         // the real stuff
4080                         latexParagraphs(*this, text(), ots, runparams);
4081                         texrow = ots.releaseTexRow();
4082
4083                         // Restore the parenthood
4084                         if (!master)
4085                                 d->ignore_parent = false;
4086                 }
4087         } else {
4088                 os << "% ";
4089                 if (output == FullSource)
4090                         os << _("Preview source code");
4091                 else if (output == OnlyPreamble)
4092                         os << _("Preview preamble");
4093                 else if (output == OnlyBody)
4094                         os << _("Preview body");
4095                 os << "\n\n";
4096                 if (runparams.flavor == OutputParams::LYX) {
4097                         ostringstream ods;
4098                         if (output == FullSource)
4099                                 write(ods);
4100                         else if (output == OnlyPreamble)
4101                                 params().writeFile(ods, this);
4102                         else if (output == OnlyBody)
4103                                 text().write(ods);
4104                         os << from_utf8(ods.str());
4105                 } else if (runparams.flavor == OutputParams::HTML) {
4106                         writeLyXHTMLSource(os, runparams, output);
4107                 } else if (runparams.flavor == OutputParams::TEXT) {
4108                         if (output == OnlyPreamble) {
4109                                 os << "% "<< _("Plain text does not have a preamble.");
4110                         } else
4111                                 writePlaintextFile(*this, os, runparams);
4112                 } else if (params().isDocBook()) {
4113                                 writeDocBookSource(os, absFileName(), runparams, output);
4114                 } else {
4115                         // latex or literate
4116                         otexstream ots(os);
4117                         // output above
4118                         ots.texrow().newlines(2);
4119                         if (master)
4120                                 runparams.is_child = true;
4121                         updateBuffer();
4122                         writeLaTeXSource(ots, string(), runparams, output);
4123                         texrow = ots.releaseTexRow();
4124                 }
4125         }
4126         return texrow;
4127 }
4128
4129
4130 ErrorList & Buffer::errorList(string const & type) const
4131 {
4132         return d->errorLists[type];
4133 }
4134
4135
4136 void Buffer::updateTocItem(std::string const & type,
4137         DocIterator const & dit) const
4138 {
4139         if (d->gui_)
4140                 d->gui_->updateTocItem(type, dit);
4141 }
4142
4143
4144 void Buffer::structureChanged() const
4145 {
4146         if (d->gui_)
4147                 d->gui_->structureChanged();
4148 }
4149
4150
4151 void Buffer::errors(string const & err, bool from_master) const
4152 {
4153         if (d->gui_)
4154                 d->gui_->errors(err, from_master);
4155 }
4156
4157
4158 void Buffer::message(docstring const & msg) const
4159 {
4160         if (d->gui_)
4161                 d->gui_->message(msg);
4162 }
4163
4164
4165 void Buffer::setBusy(bool on) const
4166 {
4167         if (d->gui_)
4168                 d->gui_->setBusy(on);
4169 }
4170
4171
4172 void Buffer::updateTitles() const
4173 {
4174         if (d->wa_)
4175                 d->wa_->updateTitles();
4176 }
4177
4178
4179 void Buffer::resetAutosaveTimers() const
4180 {
4181         if (d->gui_)
4182                 d->gui_->resetAutosaveTimers();
4183 }
4184
4185
4186 bool Buffer::hasGuiDelegate() const
4187 {
4188         return d->gui_;
4189 }
4190
4191
4192 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
4193 {
4194         d->gui_ = gui;
4195 }
4196
4197
4198
4199 namespace {
4200
4201 class AutoSaveBuffer : public ForkedProcess {
4202 public:
4203         ///
4204         AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
4205                 : buffer_(buffer), fname_(fname) {}
4206         ///
4207         virtual shared_ptr<ForkedProcess> clone() const
4208         {
4209                 return make_shared<AutoSaveBuffer>(*this);
4210         }
4211         ///
4212         int start()
4213         {
4214                 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
4215                                                  from_utf8(fname_.absFileName())));
4216                 return run(DontWait);
4217         }
4218 private:
4219         ///
4220         virtual int generateChild();
4221         ///
4222         Buffer const & buffer_;
4223         FileName fname_;
4224 };
4225
4226
4227 int AutoSaveBuffer::generateChild()
4228 {
4229 #if defined(__APPLE__)
4230         /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
4231          *   We should use something else like threads.
4232          *
4233          * Since I do not know how to determine at run time what is the OS X
4234          * version, I just disable forking altogether for now (JMarc)
4235          */
4236         pid_t const pid = -1;
4237 #else
4238         // tmp_ret will be located (usually) in /tmp
4239         // will that be a problem?
4240         // Note that this calls ForkedCalls::fork(), so it's
4241         // ok cross-platform.
4242         pid_t const pid = fork();
4243         // If you want to debug the autosave
4244         // you should set pid to -1, and comment out the fork.
4245         if (pid != 0 && pid != -1)
4246                 return pid;
4247 #endif
4248
4249         // pid = -1 signifies that lyx was unable
4250         // to fork. But we will do the save
4251         // anyway.
4252         bool failed = false;
4253         TempFile tempfile("lyxautoXXXXXX.lyx");
4254         tempfile.setAutoRemove(false);
4255         FileName const tmp_ret = tempfile.name();
4256         if (!tmp_ret.empty()) {
4257                 if (!buffer_.writeFile(tmp_ret))
4258                         failed = true;
4259                 else if (!tmp_ret.moveTo(fname_))
4260                         failed = true;
4261         } else
4262                 failed = true;
4263
4264         if (failed) {
4265                 // failed to write/rename tmp_ret so try writing direct
4266                 if (!buffer_.writeFile(fname_)) {
4267                         // It is dangerous to do this in the child,
4268                         // but safe in the parent, so...
4269                         if (pid == -1) // emit message signal.
4270                                 buffer_.message(_("Autosave failed!"));
4271                 }
4272         }
4273
4274         if (pid == 0) // we are the child so...
4275                 _exit(0);
4276
4277         return pid;
4278 }
4279
4280 } // namespace
4281
4282
4283 FileName Buffer::getEmergencyFileName() const
4284 {
4285         return FileName(d->filename.absFileName() + ".emergency");
4286 }
4287
4288
4289 FileName Buffer::getAutosaveFileName() const
4290 {
4291         // if the document is unnamed try to save in the backup dir, else
4292         // in the default document path, and as a last try in the filePath,
4293         // which will most often be the temporary directory
4294         string fpath;
4295         if (isUnnamed())
4296                 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
4297                         : lyxrc.backupdir_path;
4298         if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
4299                 fpath = filePath();
4300
4301         string const fname = "#" + d->filename.onlyFileName() + "#";
4302
4303         return makeAbsPath(fname, fpath);
4304 }
4305
4306
4307 void Buffer::removeAutosaveFile() const
4308 {
4309         FileName const f = getAutosaveFileName();
4310         if (f.exists())
4311                 f.removeFile();
4312 }
4313
4314
4315 void Buffer::moveAutosaveFile(FileName const & oldauto) const
4316 {
4317         FileName const newauto = getAutosaveFileName();
4318         oldauto.refresh();
4319         if (newauto != oldauto && oldauto.exists())
4320                 if (!oldauto.moveTo(newauto))
4321                         LYXERR0("Unable to move autosave file `" << oldauto << "'!");
4322 }
4323
4324
4325 bool Buffer::autoSave() const
4326 {
4327         Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
4328         if (buf->d->bak_clean || hasReadonlyFlag())
4329                 return true;
4330
4331         message(_("Autosaving current document..."));
4332         buf->d->bak_clean = true;
4333
4334         FileName const fname = getAutosaveFileName();
4335         LASSERT(d->cloned_buffer_, return false);
4336
4337         // If this buffer is cloned, we assume that
4338         // we are running in a separate thread already.
4339         TempFile tempfile("lyxautoXXXXXX.lyx");
4340         tempfile.setAutoRemove(false);
4341         FileName const tmp_ret = tempfile.name();
4342         if (!tmp_ret.empty()) {
4343                 writeFile(tmp_ret);
4344                 // assume successful write of tmp_ret
4345                 if (tmp_ret.moveTo(fname))
4346                         return true;
4347         }
4348         // failed to write/rename tmp_ret so try writing direct
4349         return writeFile(fname);
4350 }
4351
4352
4353 void Buffer::setExportStatus(bool e) const
4354 {
4355         d->doing_export = e;
4356         ListOfBuffers clist = getDescendents();
4357         for (auto const & bit : clist)
4358                 bit->d->doing_export = e;
4359 }
4360
4361
4362 bool Buffer::isExporting() const
4363 {
4364         return d->doing_export;
4365 }
4366
4367
4368 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
4369         const
4370 {
4371         string result_file;
4372         return doExport(target, put_in_tempdir, result_file);
4373 }
4374
4375 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4376         string & result_file) const
4377 {
4378         bool const update_unincluded =
4379                         params().maintain_unincluded_children
4380                         && !params().getIncludedChildren().empty();
4381
4382         // (1) export with all included children (omit \includeonly)
4383         if (update_unincluded) {
4384                 ExportStatus const status =
4385                         doExport(target, put_in_tempdir, true, result_file);
4386                 if (status != ExportSuccess)
4387                         return status;
4388         }
4389         // (2) export with included children only
4390         return doExport(target, put_in_tempdir, false, result_file);
4391 }
4392
4393
4394 void Buffer::setMathFlavor(OutputParams & op) const
4395 {
4396         switch (params().html_math_output) {
4397         case BufferParams::MathML:
4398                 op.math_flavor = OutputParams::MathAsMathML;
4399                 break;
4400         case BufferParams::HTML:
4401                 op.math_flavor = OutputParams::MathAsHTML;
4402                 break;
4403         case BufferParams::Images:
4404                 op.math_flavor = OutputParams::MathAsImages;
4405                 break;
4406         case BufferParams::LaTeX:
4407                 op.math_flavor = OutputParams::MathAsLaTeX;
4408                 break;
4409         }
4410 }
4411
4412
4413 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4414         bool includeall, string & result_file) const
4415 {
4416         LYXERR(Debug::FILES, "target=" << target);
4417         OutputParams runparams(&params().encoding());
4418         string format = target;
4419         string dest_filename;
4420         size_t pos = target.find(' ');
4421         if (pos != string::npos) {
4422                 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
4423                 format = target.substr(0, pos);
4424                 if (format == "default")
4425                         format = params().getDefaultOutputFormat();
4426                 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
4427                 FileName(dest_filename).onlyPath().createPath();
4428                 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
4429         }
4430         MarkAsExporting exporting(this);
4431         string backend_format;
4432         runparams.flavor = OutputParams::LATEX;
4433         runparams.linelen = lyxrc.plaintext_linelen;
4434         runparams.includeall = includeall;
4435         vector<string> backs = params().backends();
4436         Converters converters = theConverters();
4437         bool need_nice_file = false;
4438         if (find(backs.begin(), backs.end(), format) == backs.end()) {
4439                 // Get shortest path to format
4440                 converters.buildGraph();
4441                 Graph::EdgePath path;
4442                 for (string const & sit : backs) {
4443                         Graph::EdgePath p = converters.getPath(sit, format);
4444                         if (!p.empty() && (path.empty() || p.size() < path.size())) {
4445                                 backend_format = sit;
4446                                 path = p;
4447                         }
4448                 }
4449                 if (path.empty()) {
4450                         if (!put_in_tempdir) {
4451                                 // Only show this alert if this is an export to a non-temporary
4452                                 // file (not for previewing).
4453                                 Alert::error(_("Couldn't export file"), bformat(
4454                                         _("No information for exporting the format %1$s."),
4455                                         theFormats().prettyName(format)));
4456                         }
4457                         return ExportNoPathToFormat;
4458                 }
4459                 runparams.flavor = converters.getFlavor(path, this);
4460                 runparams.hyperref_driver = converters.getHyperrefDriver(path);
4461                 for (auto const & edge : path)
4462                         if (theConverters().get(edge).nice()) {
4463                                 need_nice_file = true;
4464                                 break;
4465                         }
4466
4467         } else {
4468                 backend_format = format;
4469                 LYXERR(Debug::FILES, "backend_format=" << backend_format);
4470                 // FIXME: Don't hardcode format names here, but use a flag
4471                 if (backend_format == "pdflatex")
4472                         runparams.flavor = OutputParams::PDFLATEX;
4473                 else if (backend_format == "luatex")
4474                         runparams.flavor = OutputParams::LUATEX;
4475                 else if (backend_format == "dviluatex")
4476                         runparams.flavor = OutputParams::DVILUATEX;
4477                 else if (backend_format == "xetex")
4478                         runparams.flavor = OutputParams::XETEX;
4479         }
4480
4481         string filename = latexName(false);
4482         filename = addName(temppath(), filename);
4483         filename = changeExtension(filename,
4484                                    theFormats().extension(backend_format));
4485         LYXERR(Debug::FILES, "filename=" << filename);
4486
4487         // Plain text backend
4488         if (backend_format == "text") {
4489                 runparams.flavor = OutputParams::TEXT;
4490                 try {
4491                         writePlaintextFile(*this, FileName(filename), runparams);
4492                 }
4493                 catch (ConversionException const &) { return ExportCancel; }
4494         }
4495         // HTML backend
4496         else if (backend_format == "xhtml") {
4497                 runparams.flavor = OutputParams::HTML;
4498                 setMathFlavor(runparams);
4499                 if (makeLyXHTMLFile(FileName(filename), runparams) == ExportKilled)
4500                         return ExportKilled;
4501         } else if (backend_format == "lyx")
4502                 writeFile(FileName(filename));
4503         // Docbook backend
4504         else if (params().isDocBook()) {
4505                 runparams.nice = !put_in_tempdir;
4506                 if (makeDocBookFile(FileName(filename), runparams) == ExportKilled)
4507                         return ExportKilled;
4508         }
4509         // LaTeX backend
4510         else if (backend_format == format || need_nice_file) {
4511                 runparams.nice = true;
4512                 ExportStatus const retval =
4513                         makeLaTeXFile(FileName(filename), string(), runparams);
4514                 if (retval == ExportKilled)
4515                         return ExportKilled;
4516                 if (d->cloned_buffer_)
4517                         d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4518                 if (retval != ExportSuccess)
4519                         return retval;
4520         } else if (!lyxrc.tex_allows_spaces
4521                    && contains(filePath(), ' ')) {
4522                 Alert::error(_("File name error"),
4523                         bformat(_("The directory path to the document\n%1$s\n"
4524                             "contains spaces, but your TeX installation does "
4525                             "not allow them. You should save the file to a directory "
4526                                         "whose name does not contain spaces."), from_ascii(filePath())));
4527                 return ExportTexPathHasSpaces;
4528         } else {
4529                 runparams.nice = false;
4530                 ExportStatus const retval =
4531                         makeLaTeXFile(FileName(filename), filePath(), runparams);
4532                 if (retval == ExportKilled)
4533                         return ExportKilled;
4534                 if (d->cloned_buffer_)
4535                         d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4536                 if (retval != ExportSuccess)
4537                         return ExportError;
4538         }
4539
4540         string const error_type = (format == "program")
4541                 ? "Build" : params().bufferFormat();
4542         ErrorList & error_list = d->errorLists[error_type];
4543         string const ext = theFormats().extension(format);
4544         FileName const tmp_result_file(changeExtension(filename, ext));
4545         Converters::RetVal const retval = 
4546                 converters.convert(this, FileName(filename), tmp_result_file, 
4547                 FileName(absFileName()), backend_format, format, error_list);
4548         if (retval == Converters::KILLED)
4549                 return ExportCancel;
4550         bool success = (retval == Converters::SUCCESS);
4551
4552         // Emit the signal to show the error list or copy it back to the
4553         // cloned Buffer so that it can be emitted afterwards.
4554         if (format != backend_format) {
4555                 if (runparams.silent)
4556                         error_list.clear();
4557                 else if (d->cloned_buffer_)
4558                         d->cloned_buffer_->d->errorLists[error_type] =
4559                                 d->errorLists[error_type];
4560                 else
4561                         errors(error_type);
4562                 // also to the children, in case of master-buffer-view
4563                 ListOfBuffers clist = getDescendents();
4564                 for (auto const & bit : clist) {
4565                         if (runparams.silent)
4566                                 bit->d->errorLists[error_type].clear();
4567                         else if (d->cloned_buffer_) {
4568                                 // Enable reverse search by copying back the
4569                                 // texrow object to the cloned buffer.
4570                                 // FIXME: this is not thread safe.
4571                                 bit->d->cloned_buffer_->d->texrow = bit->d->texrow;
4572                                 bit->d->cloned_buffer_->d->errorLists[error_type] =
4573                                         bit->d->errorLists[error_type];
4574                         } else
4575                                 bit->errors(error_type, true);
4576                 }
4577         }
4578
4579         if (d->cloned_buffer_) {
4580                 // Enable reverse dvi or pdf to work by copying back the texrow
4581                 // object to the cloned buffer.
4582                 // FIXME: There is a possibility of concurrent access to texrow
4583                 // here from the main GUI thread that should be securized.
4584                 d->cloned_buffer_->d->texrow = d->texrow;
4585                 string const err_type = params().bufferFormat();
4586                 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[err_type];
4587         }
4588
4589
4590         if (put_in_tempdir) {
4591                 result_file = tmp_result_file.absFileName();
4592                 return success ? ExportSuccess : ExportConverterError;
4593         }
4594
4595         if (dest_filename.empty())
4596                 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4597         else
4598                 result_file = dest_filename;
4599         // We need to copy referenced files (e. g. included graphics
4600         // if format == "dvi") to the result dir.
4601         vector<ExportedFile> const files =
4602                 runparams.exportdata->externalFiles(format);
4603         string const dest = runparams.export_folder.empty() ?
4604                 onlyPath(result_file) : runparams.export_folder;
4605         bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4606                                  : force_overwrite == ALL_FILES;
4607         CopyStatus status = use_force ? FORCE : SUCCESS;
4608
4609         for (ExportedFile const & exp : files) {
4610                 if (status == CANCEL) {
4611                         message(_("Document export cancelled."));
4612                         return ExportCancel;
4613                 }
4614                 string const fmt = theFormats().getFormatFromFile(exp.sourceName);
4615                 string fixedName = exp.exportName;
4616                 if (!runparams.export_folder.empty()) {
4617                         // Relative pathnames starting with ../ will be sanitized
4618                         // if exporting to a different folder
4619                         while (fixedName.substr(0, 3) == "../")
4620                                 fixedName = fixedName.substr(3, fixedName.length() - 3);
4621                 }
4622                 FileName fixedFileName = makeAbsPath(fixedName, dest);
4623                 fixedFileName.onlyPath().createPath();
4624                 status = copyFile(fmt, exp.sourceName,
4625                         fixedFileName,
4626                         exp.exportName, status == FORCE,
4627                         runparams.export_folder.empty());
4628         }
4629
4630
4631         if (tmp_result_file.exists()) {
4632                 // Finally copy the main file
4633                 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4634                                     : force_overwrite != NO_FILES;
4635                 if (status == SUCCESS && use_force)
4636                         status = FORCE;
4637                 status = copyFile(format, tmp_result_file,
4638                         FileName(result_file), result_file,
4639                         status == FORCE);
4640                 if (status == CANCEL) {
4641                         message(_("Document export cancelled."));
4642                         return ExportCancel;
4643                 } else {
4644                         message(bformat(_("Document exported as %1$s "
4645                                 "to file `%2$s'"),
4646                                 theFormats().prettyName(format),
4647                                 makeDisplayPath(result_file)));
4648                 }
4649         } else {
4650                 // This must be a dummy converter like fax (bug 1888)
4651                 message(bformat(_("Document exported as %1$s"),
4652                         theFormats().prettyName(format)));
4653         }
4654
4655         return success ? ExportSuccess : ExportConverterError;
4656 }
4657
4658
4659 Buffer::ExportStatus Buffer::preview(string const & format) const
4660 {
4661         bool const update_unincluded =
4662                         params().maintain_unincluded_children
4663                         && !params().getIncludedChildren().empty();
4664         return preview(format, update_unincluded);
4665 }
4666
4667
4668 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4669 {
4670         MarkAsExporting exporting(this);
4671         string result_file;
4672         // (1) export with all included children (omit \includeonly)
4673         if (includeall) {
4674                 ExportStatus const status = doExport(format, true, true, result_file);
4675                 if (status != ExportSuccess)
4676                         return status;
4677         }
4678         // (2) export with included children only
4679         ExportStatus const status = doExport(format, true, false, result_file);
4680         FileName const previewFile(result_file);
4681
4682         Impl * theimpl = isClone() ? d->cloned_buffer_->d : d;
4683         theimpl->preview_file_ = previewFile;
4684         theimpl->preview_format_ = format;
4685         theimpl->preview_error_ = (status != ExportSuccess);
4686
4687         if (status != ExportSuccess)
4688                 return status;
4689
4690         if (previewFile.exists())
4691                 return theFormats().view(*this, previewFile, format) ?
4692                         PreviewSuccess : PreviewError;
4693
4694         // Successful export but no output file?
4695         // Probably a bug in error detection.
4696         LATTEST(status != ExportSuccess);
4697         return status;
4698 }
4699
4700
4701 Buffer::ReadStatus Buffer::extractFromVC()
4702 {
4703         bool const found = LyXVC::file_not_found_hook(d->filename);
4704         if (!found)
4705                 return ReadFileNotFound;
4706         if (!d->filename.isReadableFile())
4707                 return ReadVCError;
4708         return ReadSuccess;
4709 }
4710
4711
4712 Buffer::ReadStatus Buffer::loadEmergency()
4713 {
4714         FileName const emergencyFile = getEmergencyFileName();
4715         if (!emergencyFile.exists()
4716                   || emergencyFile.lastModified() <= d->filename.lastModified())
4717                 return ReadFileNotFound;
4718
4719         docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4720         docstring const text = bformat(_("An emergency save of the document "
4721                 "%1$s exists.\n\nRecover emergency save?"), file);
4722
4723         int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4724                 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4725
4726         switch (load_emerg)
4727         {
4728         case 0: {
4729                 docstring str;
4730                 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4731                 bool const success = (ret_llf == ReadSuccess);
4732                 if (success) {
4733                         if (hasReadonlyFlag()) {
4734                                 Alert::warning(_("File is read-only"),
4735                                         bformat(_("An emergency file is successfully loaded, "
4736                                         "but the original file %1$s is marked read-only. "
4737                                         "Please make sure to save the document as a different "
4738                                         "file."), from_utf8(d->filename.absFileName())));
4739                         }
4740                         markDirty();
4741                         lyxvc().file_found_hook(d->filename);
4742                         str = _("Document was successfully recovered.");
4743                 } else
4744                         str = _("Document was NOT successfully recovered.");
4745                 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4746                         makeDisplayPath(emergencyFile.absFileName()));
4747
4748                 int const del_emerg =
4749                         Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4750                                 _("&Remove"), _("&Keep"));
4751                 if (del_emerg == 0) {
4752                         emergencyFile.removeFile();
4753                         if (success)
4754                                 Alert::warning(_("Emergency file deleted"),
4755                                         _("Do not forget to save your file now!"), true);
4756                         }
4757                 return success ? ReadSuccess : ReadEmergencyFailure;
4758         }
4759         case 1: {
4760                 int const del_emerg =
4761                         Alert::prompt(_("Delete emergency file?"),
4762                                 _("Remove emergency file now?"), 1, 1,
4763                                 _("&Remove"), _("&Keep"));
4764                 if (del_emerg == 0)
4765                         emergencyFile.removeFile();
4766                 return ReadOriginal;
4767         }
4768
4769         default:
4770                 break;
4771         }
4772         return ReadCancel;
4773 }
4774
4775
4776 Buffer::ReadStatus Buffer::loadAutosave()
4777 {
4778         // Now check if autosave file is newer.
4779         FileName const autosaveFile = getAutosaveFileName();
4780         if (!autosaveFile.exists()
4781                   || autosaveFile.lastModified() <= d->filename.lastModified())
4782                 return ReadFileNotFound;
4783
4784         docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4785         docstring const text = bformat(_("The backup of the document %1$s "
4786                 "is newer.\n\nLoad the backup instead?"), file);
4787         int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4788                 _("&Load backup"), _("Load &original"), _("&Cancel"));
4789
4790         switch (ret)
4791         {
4792         case 0: {
4793                 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4794                 // the file is not saved if we load the autosave file.
4795                 if (ret_llf == ReadSuccess) {
4796                         if (hasReadonlyFlag()) {
4797                                 Alert::warning(_("File is read-only"),
4798                                         bformat(_("A backup file is successfully loaded, "
4799                                         "but the original file %1$s is marked read-only. "
4800                                         "Please make sure to save the document as a "
4801                                         "different file."),
4802                                         from_utf8(d->filename.absFileName())));
4803                         }
4804                         markDirty();
4805                         lyxvc().file_found_hook(d->filename);
4806                         return ReadSuccess;
4807                 }
4808                 return ReadAutosaveFailure;
4809         }
4810         case 1:
4811                 // Here we delete the autosave
4812                 autosaveFile.removeFile();
4813                 return ReadOriginal;
4814         default:
4815                 break;
4816         }
4817         return ReadCancel;
4818 }
4819
4820
4821 Buffer::ReadStatus Buffer::loadLyXFile()
4822 {
4823         if (!d->filename.isReadableFile()) {
4824                 ReadStatus const ret_rvc = extractFromVC();
4825                 if (ret_rvc != ReadSuccess)
4826                         return ret_rvc;
4827         }
4828
4829         ReadStatus const ret_re = loadEmergency();
4830         if (ret_re == ReadSuccess || ret_re == ReadCancel)
4831                 return ret_re;
4832
4833         ReadStatus const ret_ra = loadAutosave();
4834         if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4835                 return ret_ra;
4836
4837         return loadThisLyXFile(d->filename);
4838 }
4839
4840
4841 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4842 {
4843         return readFile(fn);
4844 }
4845
4846
4847 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4848 {
4849         for (auto const & err : terr) {
4850                 TexRow::TextEntry start = TexRow::text_none, end = TexRow::text_none;
4851                 int errorRow = err.error_in_line;
4852                 Buffer const * buf = 0;
4853                 Impl const * p = d;
4854                 if (err.child_name.empty())
4855                         tie(start, end) = p->texrow.getEntriesFromRow(errorRow);
4856                 else {
4857                         // The error occurred in a child
4858                         for (Buffer const * child : getDescendents()) {
4859                                 string const child_name =
4860                                         DocFileName(changeExtension(child->absFileName(), "tex")).
4861                                         mangledFileName();
4862                                 if (err.child_name != child_name)
4863                                         continue;
4864                                 tie(start, end) = child->d->texrow.getEntriesFromRow(errorRow);
4865                                 if (!TexRow::isNone(start)) {
4866                                         buf = d->cloned_buffer_
4867                                                 ? child->d->cloned_buffer_->d->owner_
4868                                                 : child->d->owner_;
4869                                         p = child->d;
4870                                         break;
4871                                 }
4872                         }
4873                 }
4874                 errorList.push_back(ErrorItem(err.error_desc, err.error_text,
4875                                               start, end, buf));
4876         }
4877 }
4878
4879
4880 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4881 {
4882         LBUFERR(!text().paragraphs().empty());
4883
4884         // Use the master text class also for child documents
4885         Buffer const * const master = masterBuffer();
4886         DocumentClass const & textclass = master->params().documentClass();
4887
4888         docstring_list old_bibfiles;
4889         // Do this only if we are the top-level Buffer. We also need to account
4890         // for the case of a previewed child with ignored parent here.
4891         if (master == this && !d->ignore_parent) {
4892                 textclass.counters().reset(from_ascii("bibitem"));
4893                 reloadBibInfoCache();
4894                 // we will re-read this cache as we go through, but we need
4895                 // to know whether it's changed to know whether we need to
4896                 // update the bibinfo cache.
4897                 old_bibfiles = d->bibfiles_cache_;
4898                 d->bibfiles_cache_.clear();
4899         }
4900
4901         // keep the buffers to be children in this set. If the call from the
4902         // master comes back we can see which of them were actually seen (i.e.
4903         // via an InsetInclude). The remaining ones in the set need still be updated.
4904         static std::set<Buffer const *> bufToUpdate;
4905         if (scope == UpdateMaster) {
4906                 // If this is a child document start with the master
4907                 if (master != this) {
4908                         bufToUpdate.insert(this);
4909                         master->updateBuffer(UpdateMaster, utype);
4910                         // If the master buffer has no gui associated with it, then the TocModel is
4911                         // not updated during the updateBuffer call and TocModel::toc_ is invalid
4912                         // (bug 5699). The same happens if the master buffer is open in a different
4913                         // window. This test catches both possibilities.
4914                         // See: https://marc.info/?l=lyx-devel&m=138590578911716&w=2
4915                         // There remains a problem here: If there is another child open in yet a third
4916                         // window, that TOC is not updated. So some more general solution is needed at
4917                         // some point.
4918                         if (master->d->gui_ != d->gui_)
4919                                 structureChanged();
4920
4921                         // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4922                         if (bufToUpdate.find(this) == bufToUpdate.end())
4923                                 return;
4924                 }
4925
4926                 // start over the counters in the master
4927                 textclass.counters().reset();
4928         }
4929
4930         // update will be done below for this buffer
4931         bufToUpdate.erase(this);
4932
4933         // update all caches
4934         clearReferenceCache();
4935         updateMacros();
4936         setChangesPresent(false);
4937
4938         Buffer & cbuf = const_cast<Buffer &>(*this);
4939
4940         // do the real work
4941         ParIterator parit = cbuf.par_iterator_begin();
4942         updateBuffer(parit, utype);
4943
4944         // If this document has siblings, then update the TocBackend later. The
4945         // reason is to ensure that later siblings are up to date when e.g. the
4946         // broken or not status of references is computed. The update is called
4947         // in InsetInclude::addToToc.
4948         if (master != this)
4949                 return;
4950
4951         // if the bibfiles changed, the cache of bibinfo is invalid
4952         docstring_list new_bibfiles = d->bibfiles_cache_;
4953         // this is a trick to determine whether the two vectors have
4954         // the same elements.
4955         sort(new_bibfiles.begin(), new_bibfiles.end());
4956         sort(old_bibfiles.begin(), old_bibfiles.end());
4957         if (old_bibfiles != new_bibfiles) {
4958                 LYXERR(Debug::FILES, "Reloading bibinfo cache.");
4959                 invalidateBibinfoCache();
4960                 reloadBibInfoCache();
4961                 // We relied upon the bibinfo cache when recalculating labels. But that
4962                 // cache was invalid, although we didn't find that out until now. So we
4963                 // have to do it all again.
4964                 // That said, the only thing we really need to do is update the citation
4965                 // labels. Nothing else will have changed. So we could create a new 
4966                 // UpdateType that would signal that fact, if we needed to do so.
4967                 parit = cbuf.par_iterator_begin();
4968                 // we will be re-doing the counters and references and such.
4969                 textclass.counters().reset();
4970                 clearReferenceCache();
4971                 // we should not need to do this again?
4972                 // updateMacros();
4973                 setChangesPresent(false);
4974                 updateBuffer(parit, utype);
4975                 // this will already have been done by reloadBibInfoCache();
4976                 // d->bibinfo_cache_valid_ = true;
4977         }
4978         else {
4979                 LYXERR(Debug::FILES, "Bibfiles unchanged.");
4980                 // this is also set to true on the other path, by reloadBibInfoCache.
4981                 d->bibinfo_cache_valid_ = true;
4982         }
4983         d->cite_labels_valid_ = true;
4984         /// FIXME: Perf
4985         cbuf.tocBackend().update(true, utype);
4986         if (scope == UpdateMaster)
4987                 cbuf.structureChanged();
4988 }
4989
4990
4991 static depth_type getDepth(DocIterator const & it)
4992 {
4993         depth_type depth = 0;
4994         for (size_t i = 0 ; i < it.depth() ; ++i)
4995                 if (!it[i].inset().inMathed())
4996                         depth += it[i].paragraph().getDepth() + 1;
4997         // remove 1 since the outer inset does not count
4998         // we should have at least one non-math inset, so
4999         // depth should nevery be 0. but maybe it is worth
5000         // marking this, just in case.
5001         LATTEST(depth > 0);
5002         // coverity[INTEGER_OVERFLOW]
5003         return depth - 1;
5004 }
5005
5006 static depth_type getItemDepth(ParIterator const & it)
5007 {
5008         Paragraph const & par = *it;
5009         LabelType const labeltype = par.layout().labeltype;
5010
5011         if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
5012                 return 0;
5013
5014         // this will hold the lowest depth encountered up to now.
5015         depth_type min_depth = getDepth(it);
5016         ParIterator prev_it = it;
5017         while (true) {
5018                 if (prev_it.pit())
5019                         --prev_it.top().pit();
5020                 else {
5021                         // start of nested inset: go to outer par
5022                         prev_it.pop_back();
5023                         if (prev_it.empty()) {
5024                                 // start of document: nothing to do
5025                                 return 0;
5026                         }
5027                 }
5028
5029                 // We search for the first paragraph with same label
5030                 // that is not more deeply nested.
5031                 Paragraph & prev_par = *prev_it;
5032                 depth_type const prev_depth = getDepth(prev_it);
5033                 if (labeltype == prev_par.layout().labeltype) {
5034                         if (prev_depth < min_depth)
5035                                 return prev_par.itemdepth + 1;
5036                         if (prev_depth == min_depth)
5037                                 return prev_par.itemdepth;
5038                 }
5039                 min_depth = min(min_depth, prev_depth);
5040                 // small optimization: if we are at depth 0, we won't
5041                 // find anything else
5042                 if (prev_depth == 0)
5043                         return 0;
5044         }
5045 }
5046
5047
5048 static bool needEnumCounterReset(ParIterator const & it)
5049 {
5050         Paragraph const & par = *it;
5051         LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
5052         depth_type const cur_depth = par.getDepth();
5053         ParIterator prev_it = it;
5054         while (prev_it.pit()) {
5055                 --prev_it.top().pit();
5056                 Paragraph const & prev_par = *prev_it;
5057                 if (prev_par.getDepth() <= cur_depth)
5058                         return prev_par.layout().name() != par.layout().name();
5059         }
5060         // start of nested inset: reset
5061         return true;
5062 }
5063
5064
5065 // set the label of a paragraph. This includes the counters.
5066 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
5067 {
5068         BufferParams const & bp = owner_->masterBuffer()->params();
5069         DocumentClass const & textclass = bp.documentClass();
5070         Paragraph & par = it.paragraph();
5071         Layout const & layout = par.layout();
5072         Counters & counters = textclass.counters();
5073
5074         if (par.params().startOfAppendix()) {
5075                 // We want to reset the counter corresponding to toplevel sectioning
5076                 Layout const & lay = textclass.getTOCLayout();
5077                 docstring const cnt = lay.counter;
5078                 if (!cnt.empty())
5079                         counters.reset(cnt);
5080                 counters.appendix(true);
5081         }
5082         par.params().appendix(counters.appendix());
5083
5084         // Compute the item depth of the paragraph
5085         par.itemdepth = getItemDepth(it);
5086
5087         if (layout.margintype == MARGIN_MANUAL) {
5088                 if (par.params().labelWidthString().empty())
5089                         par.params().labelWidthString(par.expandLabel(layout, bp));
5090         } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
5091                 // we do not need to do anything here, since the empty case is
5092                 // handled during export.
5093         } else {
5094                 par.params().labelWidthString(docstring());
5095         }
5096
5097         switch(layout.labeltype) {
5098         case LABEL_ITEMIZE: {
5099                 // At some point of time we should do something more
5100                 // clever here, like:
5101                 //   par.params().labelString(
5102                 //    bp.user_defined_bullet(par.itemdepth).getText());
5103                 // for now, use a simple hardcoded label
5104                 docstring itemlabel;
5105                 switch (par.itemdepth) {
5106                 case 0:
5107                         itemlabel = char_type(0x2022);
5108                         break;
5109                 case 1:
5110                         itemlabel = char_type(0x2013);
5111                         break;
5112                 case 2:
5113                         itemlabel = char_type(0x2217);
5114                         break;
5115                 case 3:
5116                         itemlabel = char_type(0x2219); // or 0x00b7
5117                         break;
5118                 }
5119                 par.params().labelString(itemlabel);
5120                 break;
5121         }
5122
5123         case LABEL_ENUMERATE: {
5124                 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
5125
5126                 switch (par.itemdepth) {
5127                 case 2:
5128                         enumcounter += 'i';
5129                         // fall through
5130                 case 1:
5131                         enumcounter += 'i';
5132                         // fall through
5133                 case 0:
5134                         enumcounter += 'i';
5135                         break;
5136                 case 3:
5137                         enumcounter += "iv";
5138                         break;
5139                 default:
5140                         // not a valid enumdepth...
5141                         break;
5142                 }
5143
5144                 if (needEnumCounterReset(it)) {
5145                         // Increase the master counter?
5146                         if (layout.stepmastercounter)
5147                                 counters.stepMaster(enumcounter, utype);
5148                         // Maybe we have to reset the enumeration counter.
5149                         if (!layout.resumecounter)
5150                                 counters.reset(enumcounter);
5151                 }
5152                 counters.step(enumcounter, utype);
5153
5154                 string const & lang = par.getParLanguage(bp)->code();
5155                 par.params().labelString(counters.theCounter(enumcounter, lang));
5156
5157                 break;
5158         }
5159
5160         case LABEL_SENSITIVE: {
5161                 string const & type = counters.current_float();
5162                 docstring full_label;
5163                 if (type.empty())
5164                         full_label = owner_->B_("Senseless!!! ");
5165                 else {
5166                         docstring name = owner_->B_(textclass.floats().getType(type).name());
5167                         if (counters.hasCounter(from_utf8(type))) {
5168                                 string const & lang = par.getParLanguage(bp)->code();
5169                                 counters.step(from_utf8(type), utype);
5170                                 full_label = bformat(from_ascii("%1$s %2$s:"),
5171                                                      name,
5172                                                      counters.theCounter(from_utf8(type), lang));
5173                         } else
5174                                 full_label = bformat(from_ascii("%1$s #:"), name);
5175                 }
5176                 par.params().labelString(full_label);
5177                 break;
5178         }
5179
5180         case LABEL_NO_LABEL:
5181                 par.params().labelString(docstring());
5182                 break;
5183
5184         case LABEL_ABOVE:
5185         case LABEL_CENTERED:
5186         case LABEL_STATIC: {
5187                 docstring const & lcounter = layout.counter;
5188                 if (!lcounter.empty()) {
5189                         if (layout.toclevel <= bp.secnumdepth
5190                                                 && (layout.latextype != LATEX_ENVIRONMENT
5191                                         || it.text()->isFirstInSequence(it.pit()))) {
5192                                 if (counters.hasCounter(lcounter))
5193                                         counters.step(lcounter, utype);
5194                                 par.params().labelString(par.expandLabel(layout, bp));
5195                         } else
5196                                 par.params().labelString(docstring());
5197                 } else
5198                         par.params().labelString(par.expandLabel(layout, bp));
5199                 break;
5200         }
5201
5202         case LABEL_MANUAL:
5203         case LABEL_BIBLIO:
5204                 par.params().labelString(par.expandLabel(layout, bp));
5205         }
5206 }
5207
5208
5209 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
5210 {
5211         // LASSERT: Is it safe to continue here, or should we just return?
5212         LASSERT(parit.pit() == 0, /**/);
5213
5214         // Set the position of the text in the buffer to be able
5215         // to resolve macros in it.
5216         parit.text()->setMacrocontextPosition(parit);
5217
5218         depth_type maxdepth = 0;
5219         pit_type const lastpit = parit.lastpit();
5220         for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
5221                 // reduce depth if necessary
5222                 if (parit->params().depth() > maxdepth) {
5223                         /** FIXME: this function is const, but
5224                          * nevertheless it modifies the buffer. To be
5225                          * cleaner, one should modify the buffer in
5226                          * another function, which is actually
5227                          * non-const. This would however be costly in
5228                          * terms of code duplication.
5229                          */
5230                         CursorData(parit).recordUndo();
5231                         parit->params().depth(maxdepth);
5232                 }
5233                 maxdepth = parit->getMaxDepthAfter();
5234
5235                 if (utype == OutputUpdate) {
5236                         // track the active counters
5237                         // we have to do this for the master buffer, since the local
5238                         // buffer isn't tracking anything.
5239                         masterBuffer()->params().documentClass().counters().
5240                                         setActiveLayout(parit->layout());
5241                 }
5242
5243                 // set the counter for this paragraph
5244                 d->setLabel(parit, utype);
5245
5246                 // update change-tracking flag
5247                 parit->addChangesToBuffer(*this);
5248
5249                 // now the insets
5250                 for (auto const & insit : parit->insetList()) {
5251                         parit.pos() = insit.pos;
5252                         insit.inset->updateBuffer(parit, utype);
5253                 }
5254         }
5255 }
5256
5257
5258 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
5259         WordLangTuple & word_lang, docstring_list & suggestions) const
5260 {
5261         int progress = 0;
5262         WordLangTuple wl;
5263         suggestions.clear();
5264         word_lang = WordLangTuple();
5265         bool const to_end = to.empty();
5266         DocIterator const end = to_end ? doc_iterator_end(this) : to;
5267         // OK, we start from here.
5268         for (; from != end; from.forwardPos()) {
5269                 // This skips all insets with spell check disabled.
5270                 while (!from.allowSpellCheck()) {
5271                         from.pop_back();
5272                         from.pos()++;
5273                 }
5274                 // If from is at the end of the document (which is possible
5275                 // when "from" was changed above) LyX will crash later otherwise.
5276                 if (from.atEnd() || (!to_end && from >= end))
5277                         break;
5278                 to = from;
5279                 from.paragraph().spellCheck();
5280                 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
5281                 if (SpellChecker::misspelled(res)) {
5282                         word_lang = wl;
5283                         break;
5284                 }
5285                 // Do not increase progress when from == to, otherwise the word
5286                 // count will be wrong.
5287                 if (from != to) {
5288                         from = to;
5289                         ++progress;
5290                 }
5291         }
5292         return progress;
5293 }
5294
5295
5296 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
5297 {
5298         bool inword = false;
5299         word_count_ = 0;
5300         char_count_ = 0;
5301         blank_count_ = 0;
5302
5303         for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
5304                 if (!dit.inTexted()) {
5305                         dit.forwardPos();
5306                         continue;
5307                 }
5308
5309                 Paragraph const & par = dit.paragraph();
5310                 pos_type const pos = dit.pos();
5311
5312                 // Copied and adapted from isWordSeparator() in Paragraph
5313                 if (pos == dit.lastpos()) {
5314                         inword = false;
5315                 } else {
5316                         Inset const * ins = par.getInset(pos);
5317                         if (ins && skipNoOutput && !ins->producesOutput()) {
5318                                 // skip this inset
5319                                 ++dit.top().pos();
5320                                 // stop if end of range was skipped
5321                                 if (!to.atEnd() && dit >= to)
5322                                         break;
5323                                 continue;
5324                         } else if (!par.isDeleted(pos)) {
5325                                 if (par.isWordSeparator(pos))
5326                                         inword = false;
5327                                 else if (!inword) {
5328                                         ++word_count_;
5329                                         inword = true;
5330                                 }
5331                                 if (ins && ins->isLetter())
5332                                         ++char_count_;
5333                                 else if (ins && ins->isSpace())
5334                                         ++blank_count_;
5335                                 else {
5336                                         char_type const c = par.getChar(pos);
5337                                         if (isPrintableNonspace(c))
5338                                                 ++char_count_;
5339                                         else if (isSpace(c))
5340                                                 ++blank_count_;
5341                                 }
5342                         }
5343                 }
5344                 dit.forwardPos();
5345         }
5346 }
5347
5348
5349 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
5350 {
5351         d->updateStatistics(from, to, skipNoOutput);
5352 }
5353
5354
5355 int Buffer::wordCount() const
5356 {
5357         return d->wordCount();
5358 }
5359
5360
5361 int Buffer::charCount(bool with_blanks) const
5362 {
5363         return d->charCount(with_blanks);
5364 }
5365
5366
5367 Buffer::ReadStatus Buffer::reload()
5368 {
5369         setBusy(true);
5370         // c.f. bug https://www.lyx.org/trac/ticket/6587
5371         removeAutosaveFile();
5372         // e.g., read-only status could have changed due to version control
5373         d->filename.refresh();
5374         docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
5375
5376         // clear parent. this will get reset if need be.
5377         d->setParent(0);
5378         ReadStatus const status = loadLyXFile();
5379         if (status == ReadSuccess) {
5380                 updateBuffer();
5381                 changed(true);
5382                 updateTitles();
5383                 markClean();
5384                 message(bformat(_("Document %1$s reloaded."), disp_fn));
5385                 d->undo_.clear();
5386         } else {
5387                 message(bformat(_("Could not reload document %1$s."), disp_fn));
5388         }
5389         setBusy(false);
5390         removePreviews();
5391         updatePreviews();
5392         errors("Parse");
5393         return status;
5394 }
5395
5396
5397 bool Buffer::saveAs(FileName const & fn)
5398 {
5399         FileName const old_name = fileName();
5400         FileName const old_auto = getAutosaveFileName();
5401         bool const old_unnamed = isUnnamed();
5402         bool success = true;
5403         d->old_position = filePath();
5404
5405         setFileName(fn);
5406         markDirty();
5407         setUnnamed(false);
5408
5409         if (save()) {
5410                 // bring the autosave file with us, just in case.
5411                 moveAutosaveFile(old_auto);
5412                 // validate version control data and
5413                 // correct buffer title
5414                 lyxvc().file_found_hook(fileName());
5415                 updateTitles();
5416                 // the file has now been saved to the new location.
5417                 // we need to check that the locations of child buffers
5418                 // are still valid.
5419                 checkChildBuffers();
5420                 checkMasterBuffer();
5421         } else {
5422                 // save failed
5423                 // reset the old filename and unnamed state
5424                 setFileName(old_name);
5425                 setUnnamed(old_unnamed);
5426                 success = false;
5427         }
5428
5429         d->old_position.clear();
5430         return success;
5431 }
5432
5433
5434 void Buffer::checkChildBuffers()
5435 {
5436         for (auto const & bit : d->children_positions) {
5437                 DocIterator dit = bit.second;
5438                 Buffer * cbuf = const_cast<Buffer *>(bit.first);
5439                 if (!cbuf || !theBufferList().isLoaded(cbuf))
5440                         continue;
5441                 Inset * inset = dit.nextInset();
5442                 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
5443                 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
5444                 docstring const & incfile = inset_inc->getParam("filename");
5445                 string oldloc = cbuf->absFileName();
5446                 string newloc = makeAbsPath(to_utf8(incfile),
5447                                 onlyPath(absFileName())).absFileName();
5448                 if (oldloc == newloc)
5449                         continue;
5450                 // the location of the child file is incorrect.
5451                 cbuf->setParent(0);
5452                 inset_inc->setChildBuffer(0);
5453         }
5454         // invalidate cache of children
5455         d->children_positions.clear();
5456         d->position_to_children.clear();
5457 }
5458
5459
5460 // If a child has been saved under a different name/path, it might have been
5461 // orphaned. Therefore the master needs to be reset (bug 8161).
5462 void Buffer::checkMasterBuffer()
5463 {
5464         Buffer const * const master = masterBuffer();
5465         if (master == this)
5466                 return;
5467
5468         // necessary to re-register the child (bug 5873)
5469         // FIXME: clean up updateMacros (here, only
5470         // child registering is needed).
5471         master->updateMacros();
5472         // (re)set master as master buffer, but only
5473         // if we are a real child
5474         if (master->isChild(this))
5475                 setParent(master);
5476         else
5477                 setParent(0);
5478 }
5479
5480
5481 string Buffer::includedFilePath(string const & name, string const & ext) const
5482 {
5483         if (d->old_position.empty() ||
5484             equivalent(FileName(d->old_position), FileName(filePath())))
5485                 return name;
5486
5487         bool isabsolute = FileName::isAbsolute(name);
5488         // both old_position and filePath() end with a path separator
5489         string absname = isabsolute ? name : d->old_position + name;
5490
5491         // if old_position is set to origin, we need to do the equivalent of
5492         // getReferencedFileName() (see readDocument())
5493         if (!isabsolute && d->old_position == params().origin) {
5494                 FileName const test(addExtension(filePath() + name, ext));
5495                 if (test.exists())
5496                         absname = filePath() + name;
5497         }
5498
5499         if (!FileName(addExtension(absname, ext)).exists())
5500                 return name;
5501
5502         if (isabsolute)
5503                 return to_utf8(makeRelPath(from_utf8(name), from_utf8(filePath())));
5504
5505         return to_utf8(makeRelPath(from_utf8(FileName(absname).realPath()),
5506                                    from_utf8(filePath())));
5507 }
5508
5509
5510 void Buffer::setChangesPresent(bool b) const
5511 {
5512         d->tracked_changes_present_ = b;
5513 }
5514
5515
5516 bool Buffer::areChangesPresent() const
5517 {
5518         return d->tracked_changes_present_;
5519 }
5520
5521
5522 void Buffer::updateChangesPresent() const
5523 {
5524         LYXERR(Debug::CHANGES, "Buffer::updateChangesPresent");
5525         setChangesPresent(false);
5526         ParConstIterator it = par_iterator_begin();
5527         ParConstIterator const end = par_iterator_end();
5528         for (; !areChangesPresent() && it != end; ++it)
5529                 it->addChangesToBuffer(*this);
5530 }
5531
5532
5533 void Buffer::Impl::refreshFileMonitor()
5534 {
5535         if (file_monitor_ && file_monitor_->filename() == filename.absFileName()) {
5536                 file_monitor_->refresh();
5537                 return;
5538         }
5539
5540         // The previous file monitor is invalid
5541         // This also destroys the previous file monitor and all its connections
5542         file_monitor_ = FileSystemWatcher::monitor(filename);
5543         // file_monitor_ will be destroyed with *this, so it is not going to call a
5544         // destroyed object method.
5545         file_monitor_->connect([this](bool exists) {
5546                         fileExternallyModified(exists);
5547                 });
5548 }
5549
5550
5551 void Buffer::Impl::fileExternallyModified(bool const exists)
5552 {
5553         // ignore notifications after our own saving operations
5554         if (checksum_ == filename.checksum()) {
5555                 LYXERR(Debug::FILES, "External modification but "
5556                        "checksum unchanged: " << filename);
5557                 return;
5558         }
5559         // If the file has been deleted, only mark the file as dirty since it is
5560         // pointless to prompt for reloading. If later a file is moved into this
5561         // location, then the externally modified warning will appear then.
5562         if (exists)
5563                         externally_modified_ = true;
5564         // Update external modification notification.
5565         // Dirty buffers must be visible at all times.
5566         if (wa_ && wa_->unhide(owner_))
5567                 wa_->updateTitles();
5568         else
5569                 // Unable to unhide the buffer (e.g. no GUI or not current View)
5570                 lyx_clean = true;
5571 }
5572
5573
5574 bool Buffer::notifiesExternalModification() const
5575 {
5576         return d->externally_modified_;
5577 }
5578
5579
5580 void Buffer::clearExternalModification() const
5581 {
5582         d->externally_modified_ = false;
5583         if (d->wa_)
5584                 d->wa_->updateTitles();
5585 }
5586
5587
5588 } // namespace lyx