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