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