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