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