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