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