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