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