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