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