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