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