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