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