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