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