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