]> git.lyx.org Git - lyx.git/blob - src/Buffer.cpp
0f37edd9dcb1868dbad7bce1159a87a1172b8e60
[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         // This is necessary for LuaTeX/XeTeX with tex fonts.
1590         // See FIXME in BufferParams::encoding()
1591         if (runparams.isFullUnicode())
1592                 runparams.encoding = encodings.fromLyXName("utf8-plain");
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         // This is necessary for LuaTeX/XeTeX with tex fonts.
1677         // See FIXME in BufferParams::encoding()
1678         if (runparams.isFullUnicode())
1679                 runparams.encoding = encodings.fromLyXName("utf8-plain");
1680
1681         // If we are compiling a file standalone, even if this is the
1682         // child of some other buffer, let's cut the link here, so the
1683         // file is really independent and no concurring settings from
1684         // the master (e.g. branch state) interfere (see #8100).
1685         if (!runparams.is_child)
1686                 d->ignore_parent = true;
1687
1688         // Classify the unicode characters appearing in math insets
1689         BufferEncodings::initUnicodeMath(*this);
1690
1691         // validate the buffer.
1692         LYXERR(Debug::LATEX, "  Validating buffer...");
1693         LaTeXFeatures features(*this, params(), runparams);
1694         validate(features);
1695         // This is only set once per document (in master)
1696         if (!runparams.is_child)
1697                 runparams.use_polyglossia = features.usePolyglossia();
1698         LYXERR(Debug::LATEX, "  Buffer validation done.");
1699
1700         bool const output_preamble =
1701                 output == FullSource || output == OnlyPreamble;
1702         bool const output_body =
1703                 output == FullSource || output == OnlyBody;
1704
1705         // The starting paragraph of the coming rows is the
1706         // first paragraph of the document. (Asger)
1707         if (output_preamble && runparams.nice) {
1708                 os << "%% LyX " << lyx_version << " created this file.  "
1709                         "For more info, see http://www.lyx.org/.\n"
1710                         "%% Do not edit unless you really know what "
1711                         "you are doing.\n";
1712         }
1713         LYXERR(Debug::INFO, "lyx document header finished");
1714
1715         // There are a few differences between nice LaTeX and usual files:
1716         // usual files have \batchmode and special input@path to allow
1717         // inclusion of figures specified by an explicitly relative path
1718         // (i.e., a path starting with './' or '../') with either \input or
1719         // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1720         // input@path is set when the actual parameter original_path is set.
1721         // This is done for usual tex-file, but not for nice-latex-file.
1722         // (Matthias 250696)
1723         // Note that input@path is only needed for something the user does
1724         // in the preamble, included .tex files or ERT, files included by
1725         // LyX work without it.
1726         if (output_preamble) {
1727                 if (!runparams.nice) {
1728                         // code for usual, NOT nice-latex-file
1729                         os << "\\batchmode\n"; // changed from \nonstopmode
1730                 }
1731                 if (!original_path.empty()) {
1732                         // FIXME UNICODE
1733                         // We don't know the encoding of inputpath
1734                         docstring const inputpath = from_utf8(original_path);
1735                         docstring uncodable_glyphs;
1736                         Encoding const * const enc = runparams.encoding;
1737                         if (enc) {
1738                                 for (size_t n = 0; n < inputpath.size(); ++n) {
1739                                         if (!enc->encodable(inputpath[n])) {
1740                                                 docstring const glyph(1, inputpath[n]);
1741                                                 LYXERR0("Uncodable character '"
1742                                                         << glyph
1743                                                         << "' in input path!");
1744                                                 uncodable_glyphs += glyph;
1745                                         }
1746                                 }
1747                         }
1748
1749                         // warn user if we found uncodable glyphs.
1750                         if (!uncodable_glyphs.empty()) {
1751                                 frontend::Alert::warning(
1752                                         _("Uncodable character in file path"),
1753                                         support::bformat(
1754                                           _("The path of your document\n"
1755                                             "(%1$s)\n"
1756                                             "contains glyphs that are unknown "
1757                                             "in the current document encoding "
1758                                             "(namely %2$s). This may result in "
1759                                             "incomplete output, unless "
1760                                             "TEXINPUTS contains the document "
1761                                             "directory and you don't use "
1762                                             "explicitly relative paths (i.e., "
1763                                             "paths starting with './' or "
1764                                             "'../') in the preamble or in ERT."
1765                                             "\n\nIn case of problems, choose "
1766                                             "an appropriate document encoding\n"
1767                                             "(such as utf8) or change the "
1768                                             "file path name."),
1769                                           inputpath, uncodable_glyphs));
1770                         } else {
1771                                 string docdir =
1772                                         support::latex_path(original_path);
1773                                 if (contains(docdir, '#')) {
1774                                         docdir = subst(docdir, "#", "\\#");
1775                                         os << "\\catcode`\\#=11"
1776                                               "\\def\\#{#}\\catcode`\\#=6\n";
1777                                 }
1778                                 if (contains(docdir, '%')) {
1779                                         docdir = subst(docdir, "%", "\\%");
1780                                         os << "\\catcode`\\%=11"
1781                                               "\\def\\%{%}\\catcode`\\%=14\n";
1782                                 }
1783                                 os << "\\makeatletter\n"
1784                                    << "\\def\\input@path{{"
1785                                    << docdir << "}}\n"
1786                                    << "\\makeatother\n";
1787                         }
1788                 }
1789
1790                 // get parent macros (if this buffer has a parent) which will be
1791                 // written at the document begin further down.
1792                 MacroSet parentMacros;
1793                 listParentMacros(parentMacros, features);
1794
1795                 // Write the preamble
1796                 runparams.use_babel = params().writeLaTeX(os, features,
1797                                                           d->filename.onlyPath());
1798
1799                 // Japanese might be required only in some children of a document,
1800                 // but once required, we must keep use_japanese true.
1801                 runparams.use_japanese |= features.isRequired("japanese");
1802
1803                 if (!output_body) {
1804                         // Restore the parenthood if needed
1805                         if (!runparams.is_child)
1806                                 d->ignore_parent = false;
1807                         return;
1808                 }
1809
1810                 // make the body.
1811                 os << "\\begin{document}\n";
1812
1813                 // output the parent macros
1814                 MacroSet::iterator it = parentMacros.begin();
1815                 MacroSet::iterator end = parentMacros.end();
1816                 for (; it != end; ++it) {
1817                         int num_lines = (*it)->write(os.os(), true);
1818                         os.texrow().newlines(num_lines);
1819                 }
1820
1821         } // output_preamble
1822
1823         os.texrow().start(paragraphs().begin()->id(), 0);
1824
1825         LYXERR(Debug::INFO, "preamble finished, now the body.");
1826
1827         // the real stuff
1828         latexParagraphs(*this, text(), os, runparams);
1829
1830         // Restore the parenthood if needed
1831         if (!runparams.is_child)
1832                 d->ignore_parent = false;
1833
1834         // add this just in case after all the paragraphs
1835         os << endl;
1836
1837         if (output_preamble) {
1838                 os << "\\end{document}\n";
1839                 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1840         } else {
1841                 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1842         }
1843         runparams_in.encoding = runparams.encoding;
1844
1845         // Just to be sure. (Asger)
1846         os.texrow().newline();
1847
1848         //for (int i = 0; i<d->texrow.rows(); i++) {
1849         // int id,pos;
1850         // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1851         //      lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1852         //}
1853
1854         LYXERR(Debug::INFO, "Finished making LaTeX file.");
1855         LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1856 }
1857
1858
1859 void Buffer::makeDocBookFile(FileName const & fname,
1860                               OutputParams const & runparams,
1861                               OutputWhat output) const
1862 {
1863         LYXERR(Debug::LATEX, "makeDocBookFile...");
1864
1865         ofdocstream ofs;
1866         if (!openFileWrite(ofs, fname))
1867                 return;
1868
1869         // make sure we are ready to export
1870         // this needs to be done before we validate
1871         updateBuffer();
1872         updateMacroInstances(OutputUpdate);
1873
1874         writeDocBookSource(ofs, fname.absFileName(), runparams, output);
1875
1876         ofs.close();
1877         if (ofs.fail())
1878                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1879 }
1880
1881
1882 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1883                              OutputParams const & runparams,
1884                              OutputWhat output) const
1885 {
1886         LaTeXFeatures features(*this, params(), runparams);
1887         validate(features);
1888
1889         d->texrow.reset();
1890
1891         DocumentClass const & tclass = params().documentClass();
1892         string const & top_element = tclass.latexname();
1893
1894         bool const output_preamble =
1895                 output == FullSource || output == OnlyPreamble;
1896         bool const output_body =
1897           output == FullSource || output == OnlyBody;
1898
1899         if (output_preamble) {
1900                 if (runparams.flavor == OutputParams::XML)
1901                         os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1902
1903                 // FIXME UNICODE
1904                 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1905
1906                 // FIXME UNICODE
1907                 if (! tclass.class_header().empty())
1908                         os << from_ascii(tclass.class_header());
1909                 else if (runparams.flavor == OutputParams::XML)
1910                         os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1911                             << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1912                 else
1913                         os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1914
1915                 docstring preamble = from_utf8(params().preamble);
1916                 if (runparams.flavor != OutputParams::XML ) {
1917                         preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1918                         preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1919                         preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1920                         preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1921                 }
1922
1923                 string const name = runparams.nice
1924                         ? changeExtension(absFileName(), ".sgml") : fname;
1925                 preamble += features.getIncludedFiles(name);
1926                 preamble += features.getLyXSGMLEntities();
1927
1928                 if (!preamble.empty()) {
1929                         os << "\n [ " << preamble << " ]";
1930                 }
1931                 os << ">\n\n";
1932         }
1933
1934         if (output_body) {
1935                 string top = top_element;
1936                 top += " lang=\"";
1937                 if (runparams.flavor == OutputParams::XML)
1938                         top += params().language->code();
1939                 else
1940                         top += params().language->code().substr(0, 2);
1941                 top += '"';
1942
1943                 if (!params().options.empty()) {
1944                         top += ' ';
1945                         top += params().options;
1946                 }
1947
1948                 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1949                                 << " file was created by LyX " << lyx_version
1950                                 << "\n  See http://www.lyx.org/ for more information -->\n";
1951
1952                 params().documentClass().counters().reset();
1953
1954                 sgml::openTag(os, top);
1955                 os << '\n';
1956                 docbookParagraphs(text(), *this, os, runparams);
1957                 sgml::closeTag(os, top_element);
1958         }
1959 }
1960
1961
1962 void Buffer::makeLyXHTMLFile(FileName const & fname,
1963                               OutputParams const & runparams) const
1964 {
1965         LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1966
1967         ofdocstream ofs;
1968         if (!openFileWrite(ofs, fname))
1969                 return;
1970
1971         // make sure we are ready to export
1972         // this has to be done before we validate
1973         updateBuffer(UpdateMaster, OutputUpdate);
1974         updateMacroInstances(OutputUpdate);
1975
1976         writeLyXHTMLSource(ofs, runparams, FullSource);
1977
1978         ofs.close();
1979         if (ofs.fail())
1980                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1981 }
1982
1983
1984 void Buffer::writeLyXHTMLSource(odocstream & os,
1985                              OutputParams const & runparams,
1986                              OutputWhat output) const
1987 {
1988         LaTeXFeatures features(*this, params(), runparams);
1989         validate(features);
1990         d->bibinfo_.makeCitationLabels(*this);
1991
1992         bool const output_preamble =
1993                 output == FullSource || output == OnlyPreamble;
1994         bool const output_body =
1995           output == FullSource || output == OnlyBody || output == IncludedFile;
1996
1997         if (output_preamble) {
1998                 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1999                    << "<!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"
2000                    // FIXME Language should be set properly.
2001                    << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
2002                    << "<head>\n"
2003                    << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
2004                    // FIXME Presumably need to set this right
2005                    << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
2006
2007                 docstring const & doctitle = features.htmlTitle();
2008                 os << "<title>"
2009                    << (doctitle.empty() ?
2010                          from_ascii("LyX Document") :
2011                          html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
2012                    << "</title>\n";
2013
2014                 docstring styles = features.getTClassHTMLPreamble();
2015                 if (!styles.empty())
2016                         os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
2017
2018                 styles = from_utf8(features.getPreambleSnippets());
2019                 if (!styles.empty())
2020                         os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
2021
2022                 // we will collect CSS information in a stream, and then output it
2023                 // either here, as part of the header, or else in a separate file.
2024                 odocstringstream css;
2025                 styles = from_utf8(features.getCSSSnippets());
2026                 if (!styles.empty())
2027                         css << "/* LyX Provided Styles */\n" << styles << '\n';
2028
2029                 styles = features.getTClassHTMLStyles();
2030                 if (!styles.empty())
2031                         css << "/* Layout-provided Styles */\n" << styles << '\n';
2032
2033                 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
2034                 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
2035                 if (needfg || needbg) {
2036                                 css << "\nbody {\n";
2037                                 if (needfg)
2038                                    css << "  color: "
2039                                             << from_ascii(X11hexname(params().fontcolor))
2040                                             << ";\n";
2041                                 if (needbg)
2042                                    css << "  background-color: "
2043                                             << from_ascii(X11hexname(params().backgroundcolor))
2044                                             << ";\n";
2045                                 css << "}\n";
2046                 }
2047
2048                 docstring const dstyles = css.str();
2049                 if (!dstyles.empty()) {
2050                         bool written = false;
2051                         if (params().html_css_as_file) {
2052                                 // open a file for CSS info
2053                                 ofdocstream ocss;
2054                                 string const fcssname = addName(temppath(), "docstyle.css");
2055                                 FileName const fcssfile = FileName(fcssname);
2056                                 if (openFileWrite(ocss, fcssfile)) {
2057                                         ocss << dstyles;
2058                                         ocss.close();
2059                                         written = true;
2060                                         // write link to header
2061                                         os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
2062                                         // register file
2063                                         runparams.exportdata->addExternalFile("xhtml", fcssfile);
2064                                 }
2065                         }
2066                         // we are here if the CSS is supposed to be written to the header
2067                         // or if we failed to write it to an external file.
2068                         if (!written) {
2069                                 os << "<style type='text/css'>\n"
2070                                          << dstyles
2071                                          << "\n</style>\n";
2072                         }
2073                 }
2074                 os << "</head>\n";
2075         }
2076
2077         if (output_body) {
2078                 bool const output_body_tag = (output != IncludedFile);
2079                 if (output_body_tag)
2080                         os << "<body>\n";
2081                 XHTMLStream xs(os);
2082                 if (output != IncludedFile)
2083                         // if we're an included file, the counters are in the master.
2084                         params().documentClass().counters().reset();
2085                 xhtmlParagraphs(text(), *this, xs, runparams);
2086                 if (output_body_tag)
2087                         os << "</body>\n";
2088         }
2089
2090         if (output_preamble)
2091                 os << "</html>\n";
2092 }
2093
2094
2095 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2096 // Other flags: -wall -v0 -x
2097 int Buffer::runChktex()
2098 {
2099         setBusy(true);
2100
2101         // get LaTeX-Filename
2102         FileName const path(temppath());
2103         string const name = addName(path.absFileName(), latexName());
2104         string const org_path = filePath();
2105
2106         PathChanger p(path); // path to LaTeX file
2107         message(_("Running chktex..."));
2108
2109         // Generate the LaTeX file if neccessary
2110         OutputParams runparams(&params().encoding());
2111         runparams.flavor = OutputParams::LATEX;
2112         runparams.nice = false;
2113         runparams.linelen = lyxrc.plaintext_linelen;
2114         makeLaTeXFile(FileName(name), org_path, runparams);
2115
2116         TeXErrors terr;
2117         Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
2118         int const res = chktex.run(terr); // run chktex
2119
2120         if (res == -1) {
2121                 Alert::error(_("chktex failure"),
2122                              _("Could not run chktex successfully."));
2123         } else {
2124                 ErrorList & errlist = d->errorLists["ChkTeX"];
2125                 errlist.clear();
2126                 bufferErrors(terr, errlist);
2127         }
2128
2129         setBusy(false);
2130
2131         if (runparams.silent)
2132                 d->errorLists["ChkTeX"].clear();
2133         else
2134                 errors("ChkTeX");
2135
2136         return res;
2137 }
2138
2139
2140 void Buffer::validate(LaTeXFeatures & features) const
2141 {
2142         // Validate the buffer params, but not for included
2143         // files, since they also use the parent buffer's
2144         // params (# 5941)
2145         if (!features.runparams().is_child)
2146                 params().validate(features);
2147
2148         for_each(paragraphs().begin(), paragraphs().end(),
2149                  bind(&Paragraph::validate, _1, ref(features)));
2150
2151         if (lyxerr.debugging(Debug::LATEX)) {
2152                 features.showStruct();
2153         }
2154 }
2155
2156
2157 void Buffer::getLabelList(vector<docstring> & list) const
2158 {
2159         // If this is a child document, use the master's list instead.
2160         if (parent()) {
2161                 masterBuffer()->getLabelList(list);
2162                 return;
2163         }
2164
2165         list.clear();
2166         shared_ptr<Toc> toc = d->toc_backend.toc("label");
2167         TocIterator toc_it = toc->begin();
2168         TocIterator end = toc->end();
2169         for (; toc_it != end; ++toc_it) {
2170                 if (toc_it->depth() == 0)
2171                         list.push_back(toc_it->str());
2172         }
2173 }
2174
2175
2176 void Buffer::updateBibfilesCache(UpdateScope scope) const
2177 {
2178         // FIXME This is probably unnecssary, given where we call this.
2179         // If this is a child document, use the parent's cache instead.
2180         if (parent() && scope != UpdateChildOnly) {
2181                 masterBuffer()->updateBibfilesCache();
2182                 return;
2183         }
2184
2185         d->bibfiles_cache_.clear();
2186         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2187                 if (it->lyxCode() == BIBTEX_CODE) {
2188                         InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
2189                         support::FileNameList const bibfiles = inset.getBibFiles();
2190                         d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2191                                 bibfiles.begin(),
2192                                 bibfiles.end());
2193                 } else if (it->lyxCode() == INCLUDE_CODE) {
2194                         InsetInclude & inset = static_cast<InsetInclude &>(*it);
2195                         Buffer const * const incbuf = inset.getChildBuffer();
2196                         if (!incbuf)
2197                                 continue;
2198                         support::FileNameList const & bibfiles =
2199                                         incbuf->getBibfilesCache(UpdateChildOnly);
2200                         if (!bibfiles.empty()) {
2201                                 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2202                                         bibfiles.begin(),
2203                                         bibfiles.end());
2204                         }
2205                 }
2206         }
2207         d->bibfile_cache_valid_ = true;
2208         d->bibinfo_cache_valid_ = false;
2209         d->cite_labels_valid_ = false;
2210 }
2211
2212
2213 void Buffer::invalidateBibinfoCache() const
2214 {
2215         d->bibinfo_cache_valid_ = false;
2216         d->cite_labels_valid_ = false;
2217         // also invalidate the cache for the parent buffer
2218         Buffer const * const pbuf = d->parent();
2219         if (pbuf)
2220                 pbuf->invalidateBibinfoCache();
2221 }
2222
2223
2224 void Buffer::invalidateBibfileCache() const
2225 {
2226         d->bibfile_cache_valid_ = false;
2227         d->bibinfo_cache_valid_ = false;
2228         d->cite_labels_valid_ = false;
2229         // also invalidate the cache for the parent buffer
2230         Buffer const * const pbuf = d->parent();
2231         if (pbuf)
2232                 pbuf->invalidateBibfileCache();
2233 }
2234
2235
2236 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
2237 {
2238         // FIXME This is probably unnecessary, given where we call this.
2239         // If this is a child document, use the master's cache instead.
2240         Buffer const * const pbuf = masterBuffer();
2241         if (pbuf != this && scope != UpdateChildOnly)
2242                 return pbuf->getBibfilesCache();
2243
2244         if (!d->bibfile_cache_valid_)
2245                 this->updateBibfilesCache(scope);
2246
2247         return d->bibfiles_cache_;
2248 }
2249
2250
2251 BiblioInfo const & Buffer::masterBibInfo() const
2252 {
2253         Buffer const * const tmp = masterBuffer();
2254         if (tmp != this)
2255                 return tmp->masterBibInfo();
2256         return d->bibinfo_;
2257 }
2258
2259
2260 void Buffer::checkIfBibInfoCacheIsValid() const
2261 {
2262         // use the master's cache
2263         Buffer const * const tmp = masterBuffer();
2264         if (tmp != this) {
2265                 tmp->checkIfBibInfoCacheIsValid();
2266                 return;
2267         }
2268
2269         // compare the cached timestamps with the actual ones.
2270         FileNameList const & bibfiles_cache = getBibfilesCache();
2271         FileNameList::const_iterator ei = bibfiles_cache.begin();
2272         FileNameList::const_iterator en = bibfiles_cache.end();
2273         for (; ei != en; ++ ei) {
2274                 time_t lastw = ei->lastModified();
2275                 time_t prevw = d->bibfile_status_[*ei];
2276                 if (lastw != prevw) {
2277                         d->bibinfo_cache_valid_ = false;
2278                         d->cite_labels_valid_ = false;
2279                         d->bibfile_status_[*ei] = lastw;
2280                 }
2281         }
2282 }
2283
2284
2285 void Buffer::reloadBibInfoCache() const
2286 {
2287         // use the master's cache
2288         Buffer const * const tmp = masterBuffer();
2289         if (tmp != this) {
2290                 tmp->reloadBibInfoCache();
2291                 return;
2292         }
2293
2294         checkIfBibInfoCacheIsValid();
2295         if (d->bibinfo_cache_valid_)
2296                 return;
2297
2298         d->bibinfo_.clear();
2299         collectBibKeys();
2300         d->bibinfo_cache_valid_ = true;
2301 }
2302
2303
2304 void Buffer::collectBibKeys() const
2305 {
2306         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2307                 it->collectBibKeys(it);
2308 }
2309
2310
2311 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
2312 {
2313         Buffer const * tmp = masterBuffer();
2314         BiblioInfo & masterbi = (tmp == this) ?
2315                 d->bibinfo_ : tmp->d->bibinfo_;
2316         masterbi.mergeBiblioInfo(bi);
2317 }
2318
2319
2320 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
2321 {
2322         Buffer const * tmp = masterBuffer();
2323         BiblioInfo & masterbi = (tmp == this) ?
2324                 d->bibinfo_ : tmp->d->bibinfo_;
2325         masterbi[key] = bi;
2326 }
2327
2328
2329 void Buffer::makeCitationLabels() const
2330 {
2331         Buffer const * const master = masterBuffer();
2332         return d->bibinfo_.makeCitationLabels(*master);
2333 }
2334
2335
2336 bool Buffer::citeLabelsValid() const
2337 {
2338         return masterBuffer()->d->cite_labels_valid_;
2339 }
2340
2341
2342 void Buffer::removeBiblioTempFiles() const
2343 {
2344         // We remove files that contain LaTeX commands specific to the
2345         // particular bibliographic style being used, in order to avoid
2346         // LaTeX errors when we switch style.
2347         FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2348         FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2349         LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2350         aux_file.removeFile();
2351         LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2352         bbl_file.removeFile();
2353         // Also for the parent buffer
2354         Buffer const * const pbuf = parent();
2355         if (pbuf)
2356                 pbuf->removeBiblioTempFiles();
2357 }
2358
2359
2360 bool Buffer::isDepClean(string const & name) const
2361 {
2362         DepClean::const_iterator const it = d->dep_clean.find(name);
2363         if (it == d->dep_clean.end())
2364                 return true;
2365         return it->second;
2366 }
2367
2368
2369 void Buffer::markDepClean(string const & name)
2370 {
2371         d->dep_clean[name] = true;
2372 }
2373
2374
2375 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2376 {
2377         if (isInternal()) {
2378                 // FIXME? if there is an Buffer LFUN that can be dispatched even
2379                 // if internal, put a switch '(cmd.action)' here.
2380                 return false;
2381         }
2382
2383         bool enable = true;
2384
2385         switch (cmd.action()) {
2386
2387         case LFUN_BUFFER_TOGGLE_READ_ONLY:
2388                 flag.setOnOff(isReadonly());
2389                 break;
2390
2391                 // FIXME: There is need for a command-line import.
2392                 //case LFUN_BUFFER_IMPORT:
2393
2394         case LFUN_BUFFER_AUTO_SAVE:
2395                 break;
2396
2397         case LFUN_BUFFER_EXPORT_CUSTOM:
2398                 // FIXME: Nothing to check here?
2399                 break;
2400
2401         case LFUN_BUFFER_EXPORT: {
2402                 docstring const arg = cmd.argument();
2403                 if (arg == "custom") {
2404                         enable = true;
2405                         break;
2406                 }
2407                 string format = to_utf8(arg);
2408                 size_t pos = format.find(' ');
2409                 if (pos != string::npos)
2410                         format = format.substr(0, pos);
2411                 enable = params().isExportable(format);
2412                 if (!enable)
2413                         flag.message(bformat(
2414                                              _("Don't know how to export to format: %1$s"), arg));
2415                 break;
2416         }
2417
2418         case LFUN_BUFFER_CHKTEX:
2419                 enable = params().isLatex() && !lyxrc.chktex_command.empty();
2420                 break;
2421
2422         case LFUN_BUILD_PROGRAM:
2423                 enable = params().isExportable("program");
2424                 break;
2425
2426         case LFUN_BRANCH_ACTIVATE:
2427         case LFUN_BRANCH_DEACTIVATE:
2428         case LFUN_BRANCH_MASTER_ACTIVATE:
2429         case LFUN_BRANCH_MASTER_DEACTIVATE: {
2430                 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2431                                      || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2432                 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2433                         : params().branchlist();
2434                 docstring const branchName = cmd.argument();
2435                 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2436                 break;
2437         }
2438
2439         case LFUN_BRANCH_ADD:
2440         case LFUN_BRANCHES_RENAME:
2441                 // if no Buffer is present, then of course we won't be called!
2442                 break;
2443
2444         case LFUN_BUFFER_LANGUAGE:
2445                 enable = !isReadonly();
2446                 break;
2447
2448         case LFUN_BUFFER_VIEW_CACHE:
2449                 (d->preview_file_).refresh();
2450                 enable = (d->preview_file_).exists();
2451                 break;
2452
2453         default:
2454                 return false;
2455         }
2456         flag.setEnabled(enable);
2457         return true;
2458 }
2459
2460
2461 void Buffer::dispatch(string const & command, DispatchResult & result)
2462 {
2463         return dispatch(lyxaction.lookupFunc(command), result);
2464 }
2465
2466
2467 // NOTE We can end up here even if we have no GUI, because we are called
2468 // by LyX::exec to handled command-line requests. So we may need to check
2469 // whether we have a GUI or not. The boolean use_gui holds this information.
2470 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2471 {
2472         if (isInternal()) {
2473                 // FIXME? if there is an Buffer LFUN that can be dispatched even
2474                 // if internal, put a switch '(cmd.action())' here.
2475                 dr.dispatched(false);
2476                 return;
2477         }
2478         string const argument = to_utf8(func.argument());
2479         // We'll set this back to false if need be.
2480         bool dispatched = true;
2481         undo().beginUndoGroup();
2482
2483         switch (func.action()) {
2484         case LFUN_BUFFER_TOGGLE_READ_ONLY:
2485                 if (lyxvc().inUse()) {
2486                         string log = lyxvc().toggleReadOnly();
2487                         if (!log.empty())
2488                                 dr.setMessage(log);
2489                 }
2490                 else
2491                         setReadonly(!isReadonly());
2492                 break;
2493
2494         case LFUN_BUFFER_EXPORT: {
2495                 ExportStatus const status = doExport(argument, false);
2496                 dr.setError(status != ExportSuccess);
2497                 if (status != ExportSuccess)
2498                         dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2499                                               func.argument()));
2500                 break;
2501         }
2502
2503         case LFUN_BUILD_PROGRAM: {
2504                 ExportStatus const status = doExport("program", true);
2505                 dr.setError(status != ExportSuccess);
2506                 if (status != ExportSuccess)
2507                         dr.setMessage(_("Error generating literate programming code."));
2508                 break;
2509         }
2510
2511         case LFUN_BUFFER_CHKTEX:
2512                 runChktex();
2513                 break;
2514
2515         case LFUN_BUFFER_EXPORT_CUSTOM: {
2516                 string format_name;
2517                 string command = split(argument, format_name, ' ');
2518                 Format const * format = formats.getFormat(format_name);
2519                 if (!format) {
2520                         lyxerr << "Format \"" << format_name
2521                                 << "\" not recognized!"
2522                                 << endl;
2523                         break;
2524                 }
2525
2526                 // The name of the file created by the conversion process
2527                 string filename;
2528
2529                 // Output to filename
2530                 if (format->name() == "lyx") {
2531                         string const latexname = latexName(false);
2532                         filename = changeExtension(latexname,
2533                                 format->extension());
2534                         filename = addName(temppath(), filename);
2535
2536                         if (!writeFile(FileName(filename)))
2537                                 break;
2538
2539                 } else {
2540                         doExport(format_name, true, filename);
2541                 }
2542
2543                 // Substitute $$FName for filename
2544                 if (!contains(command, "$$FName"))
2545                         command = "( " + command + " ) < $$FName";
2546                 command = subst(command, "$$FName", filename);
2547
2548                 // Execute the command in the background
2549                 Systemcall call;
2550                 call.startscript(Systemcall::DontWait, command,
2551                                  filePath(), layoutPos());
2552                 break;
2553         }
2554
2555         // FIXME: There is need for a command-line import.
2556         /*
2557         case LFUN_BUFFER_IMPORT:
2558                 doImport(argument);
2559                 break;
2560         */
2561
2562         case LFUN_BUFFER_AUTO_SAVE:
2563                 autoSave();
2564                 resetAutosaveTimers();
2565                 break;
2566
2567         case LFUN_BRANCH_ACTIVATE:
2568         case LFUN_BRANCH_DEACTIVATE:
2569         case LFUN_BRANCH_MASTER_ACTIVATE:
2570         case LFUN_BRANCH_MASTER_DEACTIVATE: {
2571                 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2572                                      || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2573                 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2574                                       : this;
2575
2576                 docstring const branch_name = func.argument();
2577                 // the case without a branch name is handled elsewhere
2578                 if (branch_name.empty()) {
2579                         dispatched = false;
2580                         break;
2581                 }
2582                 Branch * branch = buf->params().branchlist().find(branch_name);
2583                 if (!branch) {
2584                         LYXERR0("Branch " << branch_name << " does not exist.");
2585                         dr.setError(true);
2586                         docstring const msg =
2587                                 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2588                         dr.setMessage(msg);
2589                         break;
2590                 }
2591                 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2592                                        || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2593                 if (branch->isSelected() != activate) {
2594                         buf->undo().recordUndoBufferParams(CursorData());
2595                         branch->setSelected(activate);
2596                         dr.setError(false);
2597                         dr.screenUpdate(Update::Force);
2598                         dr.forceBufferUpdate();
2599                 }
2600                 break;
2601         }
2602
2603         case LFUN_BRANCH_ADD: {
2604                 docstring branch_name = func.argument();
2605                 if (branch_name.empty()) {
2606                         dispatched = false;
2607                         break;
2608                 }
2609                 BranchList & branch_list = params().branchlist();
2610                 vector<docstring> const branches =
2611                         getVectorFromString(branch_name, branch_list.separator());
2612                 docstring msg;
2613                 for (vector<docstring>::const_iterator it = branches.begin();
2614                      it != branches.end(); ++it) {
2615                         branch_name = *it;
2616                         Branch * branch = branch_list.find(branch_name);
2617                         if (branch) {
2618                                 LYXERR0("Branch " << branch_name << " already exists.");
2619                                 dr.setError(true);
2620                                 if (!msg.empty())
2621                                         msg += ("\n");
2622                                 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2623                         } else {
2624                                 undo().recordUndoBufferParams(CursorData());
2625                                 branch_list.add(branch_name);
2626                                 branch = branch_list.find(branch_name);
2627                                 string const x11hexname = X11hexname(branch->color());
2628                                 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2629                                 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2630                                 dr.setError(false);
2631                                 dr.screenUpdate(Update::Force);
2632                         }
2633                 }
2634                 if (!msg.empty())
2635                         dr.setMessage(msg);
2636                 break;
2637         }
2638
2639         case LFUN_BRANCHES_RENAME: {
2640                 if (func.argument().empty())
2641                         break;
2642
2643                 docstring const oldname = from_utf8(func.getArg(0));
2644                 docstring const newname = from_utf8(func.getArg(1));
2645                 InsetIterator it  = inset_iterator_begin(inset());
2646                 InsetIterator const end = inset_iterator_end(inset());
2647                 bool success = false;
2648                 for (; it != end; ++it) {
2649                         if (it->lyxCode() == BRANCH_CODE) {
2650                                 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2651                                 if (ins.branch() == oldname) {
2652                                         undo().recordUndo(CursorData(it));
2653                                         ins.rename(newname);
2654                                         success = true;
2655                                         continue;
2656                                 }
2657                         }
2658                         if (it->lyxCode() == INCLUDE_CODE) {
2659                                 // get buffer of external file
2660                                 InsetInclude const & ins =
2661                                         static_cast<InsetInclude const &>(*it);
2662                                 Buffer * child = ins.getChildBuffer();
2663                                 if (!child)
2664                                         continue;
2665                                 child->dispatch(func, dr);
2666                         }
2667                 }
2668
2669                 if (success) {
2670                         dr.screenUpdate(Update::Force);
2671                         dr.forceBufferUpdate();
2672                 }
2673                 break;
2674         }
2675
2676         case LFUN_BUFFER_VIEW_CACHE:
2677                 if (!formats.view(*this, d->preview_file_,
2678                                   d->preview_format_))
2679                         dr.setMessage(_("Error viewing the output file."));
2680                 break;
2681
2682         default:
2683                 dispatched = false;
2684                 break;
2685         }
2686         dr.dispatched(dispatched);
2687         undo().endUndoGroup();
2688 }
2689
2690
2691 void Buffer::changeLanguage(Language const * from, Language const * to)
2692 {
2693         LASSERT(from, return);
2694         LASSERT(to, return);
2695
2696         for_each(par_iterator_begin(),
2697                  par_iterator_end(),
2698                  bind(&Paragraph::changeLanguage, _1, params(), from, to));
2699 }
2700
2701
2702 bool Buffer::isMultiLingual() const
2703 {
2704         ParConstIterator end = par_iterator_end();
2705         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2706                 if (it->isMultiLingual(params()))
2707                         return true;
2708
2709         return false;
2710 }
2711
2712
2713 std::set<Language const *> Buffer::getLanguages() const
2714 {
2715         std::set<Language const *> languages;
2716         getLanguages(languages);
2717         return languages;
2718 }
2719
2720
2721 void Buffer::getLanguages(std::set<Language const *> & languages) const
2722 {
2723         ParConstIterator end = par_iterator_end();
2724         // add the buffer language, even if it's not actively used
2725         languages.insert(language());
2726         // iterate over the paragraphs
2727         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2728                 it->getLanguages(languages);
2729         // also children
2730         ListOfBuffers clist = getDescendents();
2731         ListOfBuffers::const_iterator cit = clist.begin();
2732         ListOfBuffers::const_iterator const cen = clist.end();
2733         for (; cit != cen; ++cit)
2734                 (*cit)->getLanguages(languages);
2735 }
2736
2737
2738 DocIterator Buffer::getParFromID(int const id) const
2739 {
2740         Buffer * buf = const_cast<Buffer *>(this);
2741         if (id < 0) {
2742                 // John says this is called with id == -1 from undo
2743                 lyxerr << "getParFromID(), id: " << id << endl;
2744                 return doc_iterator_end(buf);
2745         }
2746
2747         for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2748                 if (it.paragraph().id() == id)
2749                         return it;
2750
2751         return doc_iterator_end(buf);
2752 }
2753
2754
2755 bool Buffer::hasParWithID(int const id) const
2756 {
2757         return !getParFromID(id).atEnd();
2758 }
2759
2760
2761 ParIterator Buffer::par_iterator_begin()
2762 {
2763         return ParIterator(doc_iterator_begin(this));
2764 }
2765
2766
2767 ParIterator Buffer::par_iterator_end()
2768 {
2769         return ParIterator(doc_iterator_end(this));
2770 }
2771
2772
2773 ParConstIterator Buffer::par_iterator_begin() const
2774 {
2775         return ParConstIterator(doc_iterator_begin(this));
2776 }
2777
2778
2779 ParConstIterator Buffer::par_iterator_end() const
2780 {
2781         return ParConstIterator(doc_iterator_end(this));
2782 }
2783
2784
2785 Language const * Buffer::language() const
2786 {
2787         return params().language;
2788 }
2789
2790
2791 docstring const Buffer::B_(string const & l10n) const
2792 {
2793         return params().B_(l10n);
2794 }
2795
2796
2797 bool Buffer::isClean() const
2798 {
2799         return d->lyx_clean;
2800 }
2801
2802
2803 bool Buffer::isExternallyModified(CheckMethod method) const
2804 {
2805         LASSERT(d->filename.exists(), return false);
2806         // if method == timestamp, check timestamp before checksum
2807         return (method == checksum_method
2808                 || d->timestamp_ != d->filename.lastModified())
2809                 && d->checksum_ != d->filename.checksum();
2810 }
2811
2812
2813 void Buffer::saveCheckSum() const
2814 {
2815         FileName const & file = d->filename;
2816
2817         file.refresh();
2818         if (file.exists()) {
2819                 d->timestamp_ = file.lastModified();
2820                 d->checksum_ = file.checksum();
2821         } else {
2822                 // in the case of save to a new file.
2823                 d->timestamp_ = 0;
2824                 d->checksum_ = 0;
2825         }
2826 }
2827
2828
2829 void Buffer::markClean() const
2830 {
2831         if (!d->lyx_clean) {
2832                 d->lyx_clean = true;
2833                 updateTitles();
2834         }
2835         // if the .lyx file has been saved, we don't need an
2836         // autosave
2837         d->bak_clean = true;
2838         d->undo_.markDirty();
2839 }
2840
2841
2842 void Buffer::setUnnamed(bool flag)
2843 {
2844         d->unnamed = flag;
2845 }
2846
2847
2848 bool Buffer::isUnnamed() const
2849 {
2850         return d->unnamed;
2851 }
2852
2853
2854 /// \note
2855 /// Don't check unnamed, here: isInternal() is used in
2856 /// newBuffer(), where the unnamed flag has not been set by anyone
2857 /// yet. Also, for an internal buffer, there should be no need for
2858 /// retrieving fileName() nor for checking if it is unnamed or not.
2859 bool Buffer::isInternal() const
2860 {
2861         return d->internal_buffer;
2862 }
2863
2864
2865 void Buffer::setInternal(bool flag)
2866 {
2867         d->internal_buffer = flag;
2868 }
2869
2870
2871 void Buffer::markDirty()
2872 {
2873         if (d->lyx_clean) {
2874                 d->lyx_clean = false;
2875                 updateTitles();
2876         }
2877         d->bak_clean = false;
2878
2879         DepClean::iterator it = d->dep_clean.begin();
2880         DepClean::const_iterator const end = d->dep_clean.end();
2881
2882         for (; it != end; ++it)
2883                 it->second = false;
2884 }
2885
2886
2887 FileName Buffer::fileName() const
2888 {
2889         return d->filename;
2890 }
2891
2892
2893 string Buffer::absFileName() const
2894 {
2895         return d->filename.absFileName();
2896 }
2897
2898
2899 string Buffer::filePath() const
2900 {
2901         string const abs = d->filename.onlyPath().absFileName();
2902         if (abs.empty())
2903                 return abs;
2904         int last = abs.length() - 1;
2905
2906         return abs[last] == '/' ? abs : abs + '/';
2907 }
2908
2909
2910 string Buffer::originFilePath() const
2911 {
2912         if (FileName::isAbsolute(params().origin))
2913                 return params().origin;
2914
2915         return filePath();
2916 }
2917
2918
2919 string Buffer::layoutPos() const
2920 {
2921         return d->layout_position;
2922 }
2923
2924
2925 void Buffer::setLayoutPos(string const & path)
2926 {
2927         if (path.empty()) {
2928                 d->layout_position.clear();
2929                 return;
2930         }
2931
2932         LATTEST(FileName::isAbsolute(path));
2933
2934         d->layout_position =
2935                 to_utf8(makeRelPath(from_utf8(path), from_utf8(filePath())));
2936
2937         if (d->layout_position.empty())
2938                 d->layout_position = ".";
2939 }
2940
2941
2942 bool Buffer::isReadonly() const
2943 {
2944         return d->read_only;
2945 }
2946
2947
2948 void Buffer::setParent(Buffer const * buffer)
2949 {
2950         // Avoids recursive include.
2951         d->setParent(buffer == this ? 0 : buffer);
2952         updateMacros();
2953 }
2954
2955
2956 Buffer const * Buffer::parent() const
2957 {
2958         return d->parent();
2959 }
2960
2961
2962 ListOfBuffers Buffer::allRelatives() const
2963 {
2964         ListOfBuffers lb = masterBuffer()->getDescendents();
2965         lb.push_front(const_cast<Buffer *>(masterBuffer()));
2966         return lb;
2967 }
2968
2969
2970 Buffer const * Buffer::masterBuffer() const
2971 {
2972         // FIXME Should be make sure we are not in some kind
2973         // of recursive include? A -> B -> A will crash this.
2974         Buffer const * const pbuf = d->parent();
2975         if (!pbuf)
2976                 return this;
2977
2978         return pbuf->masterBuffer();
2979 }
2980
2981
2982 bool Buffer::isChild(Buffer * child) const
2983 {
2984         return d->children_positions.find(child) != d->children_positions.end();
2985 }
2986
2987
2988 DocIterator Buffer::firstChildPosition(Buffer const * child)
2989 {
2990         Impl::BufferPositionMap::iterator it;
2991         it = d->children_positions.find(child);
2992         if (it == d->children_positions.end())
2993                 return DocIterator(this);
2994         return it->second;
2995 }
2996
2997
2998 bool Buffer::hasChildren() const
2999 {
3000         return !d->children_positions.empty();
3001 }
3002
3003
3004 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
3005 {
3006         // loop over children
3007         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3008         Impl::BufferPositionMap::iterator end = d->children_positions.end();
3009         for (; it != end; ++it) {
3010                 Buffer * child = const_cast<Buffer *>(it->first);
3011                 // No duplicates
3012                 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
3013                 if (bit != clist.end())
3014                         continue;
3015                 clist.push_back(child);
3016                 if (grand_children)
3017                         // there might be grandchildren
3018                         child->collectChildren(clist, true);
3019         }
3020 }
3021
3022
3023 ListOfBuffers Buffer::getChildren() const
3024 {
3025         ListOfBuffers v;
3026         collectChildren(v, false);
3027         // Make sure we have not included ourselves.
3028         ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3029         if (bit != v.end()) {
3030                 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3031                 v.erase(bit);
3032         }
3033         return v;
3034 }
3035
3036
3037 ListOfBuffers Buffer::getDescendents() const
3038 {
3039         ListOfBuffers v;
3040         collectChildren(v, true);
3041         // Make sure we have not included ourselves.
3042         ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3043         if (bit != v.end()) {
3044                 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3045                 v.erase(bit);
3046         }
3047         return v;
3048 }
3049
3050
3051 template<typename M>
3052 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3053 {
3054         if (m.empty())
3055                 return m.end();
3056
3057         typename M::const_iterator it = m.lower_bound(x);
3058         if (it == m.begin())
3059                 return m.end();
3060
3061         it--;
3062         return it;
3063 }
3064
3065
3066 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3067                                          DocIterator const & pos) const
3068 {
3069         LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3070
3071         // if paragraphs have no macro context set, pos will be empty
3072         if (pos.empty())
3073                 return 0;
3074
3075         // we haven't found anything yet
3076         DocIterator bestPos = owner_->par_iterator_begin();
3077         MacroData const * bestData = 0;
3078
3079         // find macro definitions for name
3080         NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3081         if (nameIt != macros.end()) {
3082                 // find last definition in front of pos or at pos itself
3083                 PositionScopeMacroMap::const_iterator it
3084                         = greatest_below(nameIt->second, pos);
3085                 if (it != nameIt->second.end()) {
3086                         while (true) {
3087                                 // scope ends behind pos?
3088                                 if (pos < it->second.scope) {
3089                                         // Looks good, remember this. If there
3090                                         // is no external macro behind this,
3091                                         // we found the right one already.
3092                                         bestPos = it->first;
3093                                         bestData = &it->second.macro;
3094                                         break;
3095                                 }
3096
3097                                 // try previous macro if there is one
3098                                 if (it == nameIt->second.begin())
3099                                         break;
3100                                 --it;
3101                         }
3102                 }
3103         }
3104
3105         // find macros in included files
3106         PositionScopeBufferMap::const_iterator it
3107                 = greatest_below(position_to_children, pos);
3108         if (it == position_to_children.end())
3109                 // no children before
3110                 return bestData;
3111
3112         while (true) {
3113                 // do we know something better (i.e. later) already?
3114                 if (it->first < bestPos )
3115                         break;
3116
3117                 // scope ends behind pos?
3118                 if (pos < it->second.scope
3119                         && (cloned_buffer_ ||
3120                             theBufferList().isLoaded(it->second.buffer))) {
3121                         // look for macro in external file
3122                         macro_lock = true;
3123                         MacroData const * data
3124                                 = it->second.buffer->getMacro(name, false);
3125                         macro_lock = false;
3126                         if (data) {
3127                                 bestPos = it->first;
3128                                 bestData = data;
3129                                 break;
3130                         }
3131                 }
3132
3133                 // try previous file if there is one
3134                 if (it == position_to_children.begin())
3135                         break;
3136                 --it;
3137         }
3138
3139         // return the best macro we have found
3140         return bestData;
3141 }
3142
3143
3144 MacroData const * Buffer::getMacro(docstring const & name,
3145         DocIterator const & pos, bool global) const
3146 {
3147         if (d->macro_lock)
3148                 return 0;
3149
3150         // query buffer macros
3151         MacroData const * data = d->getBufferMacro(name, pos);
3152         if (data != 0)
3153                 return data;
3154
3155         // If there is a master buffer, query that
3156         Buffer const * const pbuf = d->parent();
3157         if (pbuf) {
3158                 d->macro_lock = true;
3159                 MacroData const * macro = pbuf->getMacro(
3160                         name, *this, false);
3161                 d->macro_lock = false;
3162                 if (macro)
3163                         return macro;
3164         }
3165
3166         if (global) {
3167                 data = MacroTable::globalMacros().get(name);
3168                 if (data != 0)
3169                         return data;
3170         }
3171
3172         return 0;
3173 }
3174
3175
3176 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3177 {
3178         // set scope end behind the last paragraph
3179         DocIterator scope = par_iterator_begin();
3180         scope.pit() = scope.lastpit() + 1;
3181
3182         return getMacro(name, scope, global);
3183 }
3184
3185
3186 MacroData const * Buffer::getMacro(docstring const & name,
3187         Buffer const & child, bool global) const
3188 {
3189         // look where the child buffer is included first
3190         Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3191         if (it == d->children_positions.end())
3192                 return 0;
3193
3194         // check for macros at the inclusion position
3195         return getMacro(name, it->second, global);
3196 }
3197
3198
3199 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3200 {
3201         pit_type const lastpit = it.lastpit();
3202
3203         // look for macros in each paragraph
3204         while (it.pit() <= lastpit) {
3205                 Paragraph & par = it.paragraph();
3206
3207                 // iterate over the insets of the current paragraph
3208                 InsetList const & insets = par.insetList();
3209                 InsetList::const_iterator iit = insets.begin();
3210                 InsetList::const_iterator end = insets.end();
3211                 for (; iit != end; ++iit) {
3212                         it.pos() = iit->pos;
3213
3214                         // is it a nested text inset?
3215                         if (iit->inset->asInsetText()) {
3216                                 // Inset needs its own scope?
3217                                 InsetText const * itext = iit->inset->asInsetText();
3218                                 bool newScope = itext->isMacroScope();
3219
3220                                 // scope which ends just behind the inset
3221                                 DocIterator insetScope = it;
3222                                 ++insetScope.pos();
3223
3224                                 // collect macros in inset
3225                                 it.push_back(CursorSlice(*iit->inset));
3226                                 updateMacros(it, newScope ? insetScope : scope);
3227                                 it.pop_back();
3228                                 continue;
3229                         }
3230
3231                         if (iit->inset->asInsetTabular()) {
3232                                 CursorSlice slice(*iit->inset);
3233                                 size_t const numcells = slice.nargs();
3234                                 for (; slice.idx() < numcells; slice.forwardIdx()) {
3235                                         it.push_back(slice);
3236                                         updateMacros(it, scope);
3237                                         it.pop_back();
3238                                 }
3239                                 continue;
3240                         }
3241
3242                         // is it an external file?
3243                         if (iit->inset->lyxCode() == INCLUDE_CODE) {
3244                                 // get buffer of external file
3245                                 InsetInclude const & inset =
3246                                         static_cast<InsetInclude const &>(*iit->inset);
3247                                 macro_lock = true;
3248                                 Buffer * child = inset.getChildBuffer();
3249                                 macro_lock = false;
3250                                 if (!child)
3251                                         continue;
3252
3253                                 // register its position, but only when it is
3254                                 // included first in the buffer
3255                                 if (children_positions.find(child) ==
3256                                         children_positions.end())
3257                                                 children_positions[child] = it;
3258
3259                                 // register child with its scope
3260                                 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3261                                 continue;
3262                         }
3263
3264                         InsetMath * im = iit->inset->asInsetMath();
3265                         if (doing_export && im)  {
3266                                 InsetMathHull * hull = im->asHullInset();
3267                                 if (hull)
3268                                         hull->recordLocation(it);
3269                         }
3270
3271                         if (iit->inset->lyxCode() != MATHMACRO_CODE)
3272                                 continue;
3273
3274                         // get macro data
3275                         MathMacroTemplate & macroTemplate =
3276                                 *iit->inset->asInsetMath()->asMacroTemplate();
3277                         MacroContext mc(owner_, it);
3278                         macroTemplate.updateToContext(mc);
3279
3280                         // valid?
3281                         bool valid = macroTemplate.validMacro();
3282                         // FIXME: Should be fixNameAndCheckIfValid() in fact,
3283                         // then the BufferView's cursor will be invalid in
3284                         // some cases which leads to crashes.
3285                         if (!valid)
3286                                 continue;
3287
3288                         // register macro
3289                         // FIXME (Abdel), I don't understand why we pass 'it' here
3290                         // instead of 'macroTemplate' defined above... is this correct?
3291                         macros[macroTemplate.name()][it] =
3292                                 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3293                 }
3294
3295                 // next paragraph
3296                 it.pit()++;
3297                 it.pos() = 0;
3298         }
3299 }
3300
3301
3302 void Buffer::updateMacros() const
3303 {
3304         if (d->macro_lock)
3305                 return;
3306
3307         LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3308
3309         // start with empty table
3310         d->macros.clear();
3311         d->children_positions.clear();
3312         d->position_to_children.clear();
3313
3314         // Iterate over buffer, starting with first paragraph
3315         // The scope must be bigger than any lookup DocIterator
3316         // later. For the global lookup, lastpit+1 is used, hence
3317         // we use lastpit+2 here.
3318         DocIterator it = par_iterator_begin();
3319         DocIterator outerScope = it;
3320         outerScope.pit() = outerScope.lastpit() + 2;
3321         d->updateMacros(it, outerScope);
3322 }
3323
3324
3325 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3326 {
3327         InsetIterator it  = inset_iterator_begin(inset());
3328         InsetIterator const end = inset_iterator_end(inset());
3329         for (; it != end; ++it) {
3330                 if (it->lyxCode() == BRANCH_CODE) {
3331                         InsetBranch & br = static_cast<InsetBranch &>(*it);
3332                         docstring const name = br.branch();
3333                         if (!from_master && !params().branchlist().find(name))
3334                                 result.push_back(name);
3335                         else if (from_master && !masterBuffer()->params().branchlist().find(name))
3336                                 result.push_back(name);
3337                         continue;
3338                 }
3339                 if (it->lyxCode() == INCLUDE_CODE) {
3340                         // get buffer of external file
3341                         InsetInclude const & ins =
3342                                 static_cast<InsetInclude const &>(*it);
3343                         Buffer * child = ins.getChildBuffer();
3344                         if (!child)
3345                                 continue;
3346                         child->getUsedBranches(result, true);
3347                 }
3348         }
3349         // remove duplicates
3350         result.unique();
3351 }
3352
3353
3354 void Buffer::updateMacroInstances(UpdateType utype) const
3355 {
3356         LYXERR(Debug::MACROS, "updateMacroInstances for "
3357                 << d->filename.onlyFileName());
3358         DocIterator it = doc_iterator_begin(this);
3359         it.forwardInset();
3360         DocIterator const end = doc_iterator_end(this);
3361         for (; it != end; it.forwardInset()) {
3362                 // look for MathData cells in InsetMathNest insets
3363                 InsetMath * minset = it.nextInset()->asInsetMath();
3364                 if (!minset)
3365                         continue;
3366
3367                 // update macro in all cells of the InsetMathNest
3368                 DocIterator::idx_type n = minset->nargs();
3369                 MacroContext mc = MacroContext(this, it);
3370                 for (DocIterator::idx_type i = 0; i < n; ++i) {
3371                         MathData & data = minset->cell(i);
3372                         data.updateMacros(0, mc, utype);
3373                 }
3374         }
3375 }
3376
3377
3378 void Buffer::listMacroNames(MacroNameSet & macros) const
3379 {
3380         if (d->macro_lock)
3381                 return;
3382
3383         d->macro_lock = true;
3384
3385         // loop over macro names
3386         Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3387         Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3388         for (; nameIt != nameEnd; ++nameIt)
3389                 macros.insert(nameIt->first);
3390
3391         // loop over children
3392         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3393         Impl::BufferPositionMap::iterator end = d->children_positions.end();
3394         for (; it != end; ++it)
3395                 it->first->listMacroNames(macros);
3396
3397         // call parent
3398         Buffer const * const pbuf = d->parent();
3399         if (pbuf)
3400                 pbuf->listMacroNames(macros);
3401
3402         d->macro_lock = false;
3403 }
3404
3405
3406 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3407 {
3408         Buffer const * const pbuf = d->parent();
3409         if (!pbuf)
3410                 return;
3411
3412         MacroNameSet names;
3413         pbuf->listMacroNames(names);
3414
3415         // resolve macros
3416         MacroNameSet::iterator it = names.begin();
3417         MacroNameSet::iterator end = names.end();
3418         for (; it != end; ++it) {
3419                 // defined?
3420                 MacroData const * data =
3421                 pbuf->getMacro(*it, *this, false);
3422                 if (data) {
3423                         macros.insert(data);
3424
3425                         // we cannot access the original MathMacroTemplate anymore
3426                         // here to calls validate method. So we do its work here manually.
3427                         // FIXME: somehow make the template accessible here.
3428                         if (data->optionals() > 0)
3429                                 features.require("xargs");
3430                 }
3431         }
3432 }
3433
3434
3435 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3436 {
3437         if (d->parent())
3438                 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3439
3440         RefCache::iterator it = d->ref_cache_.find(label);
3441         if (it != d->ref_cache_.end())
3442                 return it->second.second;
3443
3444         static InsetLabel const * dummy_il = 0;
3445         static References const dummy_refs;
3446         it = d->ref_cache_.insert(
3447                 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3448         return it->second.second;
3449 }
3450
3451
3452 Buffer::References const & Buffer::references(docstring const & label) const
3453 {
3454         return const_cast<Buffer *>(this)->getReferenceCache(label);
3455 }
3456
3457
3458 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3459 {
3460         References & refs = getReferenceCache(label);
3461         refs.push_back(make_pair(inset, it));
3462 }
3463
3464
3465 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3466 {
3467         masterBuffer()->d->ref_cache_[label].first = il;
3468 }
3469
3470
3471 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3472 {
3473         return masterBuffer()->d->ref_cache_[label].first;
3474 }
3475
3476
3477 void Buffer::clearReferenceCache() const
3478 {
3479         if (!d->parent())
3480                 d->ref_cache_.clear();
3481 }
3482
3483
3484 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
3485 {
3486         //FIXME: This does not work for child documents yet.
3487         reloadBibInfoCache();
3488
3489         // Check if the label 'from' appears more than once
3490         BiblioInfo const & keys = masterBibInfo();
3491         BiblioInfo::const_iterator bit  = keys.begin();
3492         BiblioInfo::const_iterator bend = keys.end();
3493         vector<docstring> labels;
3494
3495         for (; bit != bend; ++bit)
3496                 // FIXME UNICODE
3497                 labels.push_back(bit->first);
3498
3499         if (count(labels.begin(), labels.end(), from) > 1)
3500                 return;
3501
3502         string const paramName = "key";
3503         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3504                 if (it->lyxCode() != CITE_CODE)
3505                         continue;
3506                 InsetCommand * inset = it->asInsetCommand();
3507                 docstring const oldValue = inset->getParam(paramName);
3508                 if (oldValue == from)
3509                         inset->setParam(paramName, to);
3510         }
3511 }
3512
3513 // returns NULL if id-to-row conversion is unsupported
3514 auto_ptr<TexRow> Buffer::getSourceCode(odocstream & os, string const & format,
3515                            pit_type par_begin, pit_type par_end,
3516                            OutputWhat output, bool master) const
3517 {
3518         auto_ptr<TexRow> texrow(NULL);
3519         OutputParams runparams(&params().encoding());
3520         runparams.nice = true;
3521         runparams.flavor = params().getOutputFlavor(format);
3522         runparams.linelen = lyxrc.plaintext_linelen;
3523         // No side effect of file copying and image conversion
3524         runparams.dryrun = true;
3525
3526         if (output == CurrentParagraph) {
3527                 runparams.par_begin = par_begin;
3528                 runparams.par_end = par_end;
3529                 if (par_begin + 1 == par_end) {
3530                         os << "% "
3531                            << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3532                            << "\n\n";
3533                 } else {
3534                         os << "% "
3535                            << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3536                                         convert<docstring>(par_begin),
3537                                         convert<docstring>(par_end - 1))
3538                            << "\n\n";
3539                 }
3540                 // output paragraphs
3541                 if (runparams.flavor == OutputParams::LYX) {
3542                         Paragraph const & par = text().paragraphs()[par_begin];
3543                         ostringstream ods;
3544                         depth_type dt = par.getDepth();
3545                         par.write(ods, params(), dt);
3546                         os << from_utf8(ods.str());
3547                 } else if (runparams.flavor == OutputParams::HTML) {
3548                         XHTMLStream xs(os);
3549                         setMathFlavor(runparams);
3550                         xhtmlParagraphs(text(), *this, xs, runparams);
3551                 } else if (runparams.flavor == OutputParams::TEXT) {
3552                         bool dummy = false;
3553                         // FIXME Handles only one paragraph, unlike the others.
3554                         // Probably should have some routine with a signature like them.
3555                         writePlaintextParagraph(*this,
3556                                 text().paragraphs()[par_begin], os, runparams, dummy);
3557                 } else if (params().isDocBook()) {
3558                         docbookParagraphs(text(), *this, os, runparams);
3559                 } else {
3560                         // If we are previewing a paragraph, even if this is the
3561                         // child of some other buffer, let's cut the link here,
3562                         // so that no concurring settings from the master
3563                         // (e.g. branch state) interfere (see #8101).
3564                         if (!master)
3565                                 d->ignore_parent = true;
3566                         // We need to validate the Buffer params' features here
3567                         // in order to know if we should output polyglossia
3568                         // macros (instead of babel macros)
3569                         LaTeXFeatures features(*this, params(), runparams);
3570                         params().validate(features);
3571                         runparams.use_polyglossia = features.usePolyglossia();
3572                         texrow.reset(new TexRow());
3573                         texrow->reset();
3574                         texrow->newline();
3575                         texrow->newline();
3576                         // latex or literate
3577                         otexstream ots(os, *texrow);
3578
3579                         // the real stuff
3580                         latexParagraphs(*this, text(), ots, runparams);
3581
3582                         // Restore the parenthood
3583                         if (!master)
3584                                 d->ignore_parent = false;
3585                 }
3586         } else {
3587                 os << "% ";
3588                 if (output == FullSource)
3589                         os << _("Preview source code");
3590                 else if (output == OnlyPreamble)
3591                         os << _("Preview preamble");
3592                 else if (output == OnlyBody)
3593                         os << _("Preview body");
3594                 os << "\n\n";
3595                 if (runparams.flavor == OutputParams::LYX) {
3596                         ostringstream ods;
3597                         if (output == FullSource)
3598                                 write(ods);
3599                         else if (output == OnlyPreamble)
3600                                 params().writeFile(ods, this);
3601                         else if (output == OnlyBody)
3602                                 text().write(ods);
3603                         os << from_utf8(ods.str());
3604                 } else if (runparams.flavor == OutputParams::HTML) {
3605                         writeLyXHTMLSource(os, runparams, output);
3606                 } else if (runparams.flavor == OutputParams::TEXT) {
3607                         if (output == OnlyPreamble) {
3608                                 os << "% "<< _("Plain text does not have a preamble.");
3609                         } else
3610                                 writePlaintextFile(*this, os, runparams);
3611                 } else if (params().isDocBook()) {
3612                                 writeDocBookSource(os, absFileName(), runparams, output);
3613                 } else {
3614                         // latex or literate
3615                         texrow.reset(new TexRow());
3616                         texrow->reset();
3617                         texrow->newline();
3618                         texrow->newline();
3619                         otexstream ots(os, *texrow);
3620                         if (master)
3621                                 runparams.is_child = true;
3622                         writeLaTeXSource(ots, string(), runparams, output);
3623                 }
3624         }
3625         return texrow;
3626 }
3627
3628
3629 ErrorList & Buffer::errorList(string const & type) const
3630 {
3631         return d->errorLists[type];
3632 }
3633
3634
3635 void Buffer::updateTocItem(std::string const & type,
3636         DocIterator const & dit) const
3637 {
3638         if (d->gui_)
3639                 d->gui_->updateTocItem(type, dit);
3640 }
3641
3642
3643 void Buffer::structureChanged() const
3644 {
3645         if (d->gui_)
3646                 d->gui_->structureChanged();
3647 }
3648
3649
3650 void Buffer::errors(string const & err, bool from_master) const
3651 {
3652         if (d->gui_)
3653                 d->gui_->errors(err, from_master);
3654 }
3655
3656
3657 void Buffer::message(docstring const & msg) const
3658 {
3659         if (d->gui_)
3660                 d->gui_->message(msg);
3661 }
3662
3663
3664 void Buffer::setBusy(bool on) const
3665 {
3666         if (d->gui_)
3667                 d->gui_->setBusy(on);
3668 }
3669
3670
3671 void Buffer::updateTitles() const
3672 {
3673         if (d->wa_)
3674                 d->wa_->updateTitles();
3675 }
3676
3677
3678 void Buffer::resetAutosaveTimers() const
3679 {
3680         if (d->gui_)
3681                 d->gui_->resetAutosaveTimers();
3682 }
3683
3684
3685 bool Buffer::hasGuiDelegate() const
3686 {
3687         return d->gui_;
3688 }
3689
3690
3691 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3692 {
3693         d->gui_ = gui;
3694 }
3695
3696
3697
3698 namespace {
3699
3700 class AutoSaveBuffer : public ForkedProcess {
3701 public:
3702         ///
3703         AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3704                 : buffer_(buffer), fname_(fname) {}
3705         ///
3706         virtual shared_ptr<ForkedProcess> clone() const
3707         {
3708                 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3709         }
3710         ///
3711         int start()
3712         {
3713                 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3714                                                  from_utf8(fname_.absFileName())));
3715                 return run(DontWait);
3716         }
3717 private:
3718         ///
3719         virtual int generateChild();
3720         ///
3721         Buffer const & buffer_;
3722         FileName fname_;
3723 };
3724
3725
3726 int AutoSaveBuffer::generateChild()
3727 {
3728 #if defined(__APPLE__)
3729         /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3730          *   We should use something else like threads.
3731          *
3732          * Since I do not know how to determine at run time what is the OS X
3733          * version, I just disable forking altogether for now (JMarc)
3734          */
3735         pid_t const pid = -1;
3736 #else
3737         // tmp_ret will be located (usually) in /tmp
3738         // will that be a problem?
3739         // Note that this calls ForkedCalls::fork(), so it's
3740         // ok cross-platform.
3741         pid_t const pid = fork();
3742         // If you want to debug the autosave
3743         // you should set pid to -1, and comment out the fork.
3744         if (pid != 0 && pid != -1)
3745                 return pid;
3746 #endif
3747
3748         // pid = -1 signifies that lyx was unable
3749         // to fork. But we will do the save
3750         // anyway.
3751         bool failed = false;
3752         TempFile tempfile("lyxautoXXXXXX.lyx");
3753         tempfile.setAutoRemove(false);
3754         FileName const tmp_ret = tempfile.name();
3755         if (!tmp_ret.empty()) {
3756                 if (!buffer_.writeFile(tmp_ret))
3757                         failed = true;
3758                 else if (!tmp_ret.moveTo(fname_))
3759                         failed = true;
3760         } else
3761                 failed = true;
3762
3763         if (failed) {
3764                 // failed to write/rename tmp_ret so try writing direct
3765                 if (!buffer_.writeFile(fname_)) {
3766                         // It is dangerous to do this in the child,
3767                         // but safe in the parent, so...
3768                         if (pid == -1) // emit message signal.
3769                                 buffer_.message(_("Autosave failed!"));
3770                 }
3771         }
3772
3773         if (pid == 0) // we are the child so...
3774                 _exit(0);
3775
3776         return pid;
3777 }
3778
3779 } // namespace anon
3780
3781
3782 FileName Buffer::getEmergencyFileName() const
3783 {
3784         return FileName(d->filename.absFileName() + ".emergency");
3785 }
3786
3787
3788 FileName Buffer::getAutosaveFileName() const
3789 {
3790         // if the document is unnamed try to save in the backup dir, else
3791         // in the default document path, and as a last try in the filePath,
3792         // which will most often be the temporary directory
3793         string fpath;
3794         if (isUnnamed())
3795                 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3796                         : lyxrc.backupdir_path;
3797         if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3798                 fpath = filePath();
3799
3800         string const fname = "#" + d->filename.onlyFileName() + "#";
3801
3802         return makeAbsPath(fname, fpath);
3803 }
3804
3805
3806 void Buffer::removeAutosaveFile() const
3807 {
3808         FileName const f = getAutosaveFileName();
3809         if (f.exists())
3810                 f.removeFile();
3811 }
3812
3813
3814 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3815 {
3816         FileName const newauto = getAutosaveFileName();
3817         oldauto.refresh();
3818         if (newauto != oldauto && oldauto.exists())
3819                 if (!oldauto.moveTo(newauto))
3820                         LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3821 }
3822
3823
3824 bool Buffer::autoSave() const
3825 {
3826         Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3827         if (buf->d->bak_clean || isReadonly())
3828                 return true;
3829
3830         message(_("Autosaving current document..."));
3831         buf->d->bak_clean = true;
3832
3833         FileName const fname = getAutosaveFileName();
3834         LASSERT(d->cloned_buffer_, return false);
3835
3836         // If this buffer is cloned, we assume that
3837         // we are running in a separate thread already.
3838         TempFile tempfile("lyxautoXXXXXX.lyx");
3839         tempfile.setAutoRemove(false);
3840         FileName const tmp_ret = tempfile.name();
3841         if (!tmp_ret.empty()) {
3842                 writeFile(tmp_ret);
3843                 // assume successful write of tmp_ret
3844                 if (tmp_ret.moveTo(fname))
3845                         return true;
3846         }
3847         // failed to write/rename tmp_ret so try writing direct
3848         return writeFile(fname);
3849 }
3850
3851
3852 void Buffer::setExportStatus(bool e) const
3853 {
3854         d->doing_export = e;
3855         ListOfBuffers clist = getDescendents();
3856         ListOfBuffers::const_iterator cit = clist.begin();
3857         ListOfBuffers::const_iterator const cen = clist.end();
3858         for (; cit != cen; ++cit)
3859                 (*cit)->d->doing_export = e;
3860 }
3861
3862
3863 bool Buffer::isExporting() const
3864 {
3865         return d->doing_export;
3866 }
3867
3868
3869 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
3870         const
3871 {
3872         string result_file;
3873         return doExport(target, put_in_tempdir, result_file);
3874 }
3875
3876 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3877         string & result_file) const
3878 {
3879         bool const update_unincluded =
3880                         params().maintain_unincluded_children
3881                         && !params().getIncludedChildren().empty();
3882
3883         // (1) export with all included children (omit \includeonly)
3884         if (update_unincluded) {
3885                 ExportStatus const status =
3886                         doExport(target, put_in_tempdir, true, result_file);
3887                 if (status != ExportSuccess)
3888                         return status;
3889         }
3890         // (2) export with included children only
3891         return doExport(target, put_in_tempdir, false, result_file);
3892 }
3893
3894
3895 void Buffer::setMathFlavor(OutputParams & op) const
3896 {
3897         switch (params().html_math_output) {
3898         case BufferParams::MathML:
3899                 op.math_flavor = OutputParams::MathAsMathML;
3900                 break;
3901         case BufferParams::HTML:
3902                 op.math_flavor = OutputParams::MathAsHTML;
3903                 break;
3904         case BufferParams::Images:
3905                 op.math_flavor = OutputParams::MathAsImages;
3906                 break;
3907         case BufferParams::LaTeX:
3908                 op.math_flavor = OutputParams::MathAsLaTeX;
3909                 break;
3910         }
3911 }
3912
3913
3914 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3915         bool includeall, string & result_file) const
3916 {
3917         LYXERR(Debug::FILES, "target=" << target);
3918         OutputParams runparams(&params().encoding());
3919         string format = target;
3920         string dest_filename;
3921         size_t pos = target.find(' ');
3922         if (pos != string::npos) {
3923                 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
3924                 format = target.substr(0, pos);
3925                 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
3926                 FileName(dest_filename).onlyPath().createPath();
3927                 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
3928         }
3929         MarkAsExporting exporting(this);
3930         string backend_format;
3931         runparams.flavor = OutputParams::LATEX;
3932         runparams.linelen = lyxrc.plaintext_linelen;
3933         runparams.includeall = includeall;
3934         vector<string> backs = params().backends();
3935         Converters converters = theConverters();
3936         bool need_nice_file = false;
3937         if (find(backs.begin(), backs.end(), format) == backs.end()) {
3938                 // Get shortest path to format
3939                 converters.buildGraph();
3940                 Graph::EdgePath path;
3941                 for (vector<string>::const_iterator it = backs.begin();
3942                      it != backs.end(); ++it) {
3943                         Graph::EdgePath p = converters.getPath(*it, format);
3944                         if (!p.empty() && (path.empty() || p.size() < path.size())) {
3945                                 backend_format = *it;
3946                                 path = p;
3947                         }
3948                 }
3949                 if (path.empty()) {
3950                         if (!put_in_tempdir) {
3951                                 // Only show this alert if this is an export to a non-temporary
3952                                 // file (not for previewing).
3953                                 Alert::error(_("Couldn't export file"), bformat(
3954                                         _("No information for exporting the format %1$s."),
3955                                         formats.prettyName(format)));
3956                         }
3957                         return ExportNoPathToFormat;
3958                 }
3959                 runparams.flavor = converters.getFlavor(path, this);
3960                 Graph::EdgePath::const_iterator it = path.begin();
3961                 Graph::EdgePath::const_iterator en = path.end();
3962                 for (; it != en; ++it)
3963                         if (theConverters().get(*it).nice()) {
3964                                 need_nice_file = true;
3965                                 break;
3966                         }
3967
3968         } else {
3969                 backend_format = format;
3970                 LYXERR(Debug::FILES, "backend_format=" << backend_format);
3971                 // FIXME: Don't hardcode format names here, but use a flag
3972                 if (backend_format == "pdflatex")
3973                         runparams.flavor = OutputParams::PDFLATEX;
3974                 else if (backend_format == "luatex")
3975                         runparams.flavor = OutputParams::LUATEX;
3976                 else if (backend_format == "dviluatex")
3977                         runparams.flavor = OutputParams::DVILUATEX;
3978                 else if (backend_format == "xetex")
3979                         runparams.flavor = OutputParams::XETEX;
3980         }
3981
3982         string filename = latexName(false);
3983         filename = addName(temppath(), filename);
3984         filename = changeExtension(filename,
3985                                    formats.extension(backend_format));
3986         LYXERR(Debug::FILES, "filename=" << filename);
3987
3988         // Plain text backend
3989         if (backend_format == "text") {
3990                 runparams.flavor = OutputParams::TEXT;
3991                 writePlaintextFile(*this, FileName(filename), runparams);
3992         }
3993         // HTML backend
3994         else if (backend_format == "xhtml") {
3995                 runparams.flavor = OutputParams::HTML;
3996                 setMathFlavor(runparams);
3997                 makeLyXHTMLFile(FileName(filename), runparams);
3998         } else if (backend_format == "lyx")
3999                 writeFile(FileName(filename));
4000         // Docbook backend
4001         else if (params().isDocBook()) {
4002                 runparams.nice = !put_in_tempdir;
4003                 makeDocBookFile(FileName(filename), runparams);
4004         }
4005         // LaTeX backend
4006         else if (backend_format == format || need_nice_file) {
4007                 runparams.nice = true;
4008                 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
4009                 if (d->cloned_buffer_)
4010                         d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4011                 if (!success)
4012                         return ExportError;
4013         } else if (!lyxrc.tex_allows_spaces
4014                    && contains(filePath(), ' ')) {
4015                 Alert::error(_("File name error"),
4016                            _("The directory path to the document cannot contain spaces."));
4017                 return ExportTexPathHasSpaces;
4018         } else {
4019                 runparams.nice = false;
4020                 bool const success = makeLaTeXFile(
4021                         FileName(filename), filePath(), runparams);
4022                 if (d->cloned_buffer_)
4023                         d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4024                 if (!success)
4025                         return ExportError;
4026         }
4027
4028         string const error_type = (format == "program")
4029                 ? "Build" : params().bufferFormat();
4030         ErrorList & error_list = d->errorLists[error_type];
4031         string const ext = formats.extension(format);
4032         FileName const tmp_result_file(changeExtension(filename, ext));
4033         bool const success = converters.convert(this, FileName(filename),
4034                 tmp_result_file, FileName(absFileName()), backend_format, format,
4035                 error_list);
4036
4037         // Emit the signal to show the error list or copy it back to the
4038         // cloned Buffer so that it can be emitted afterwards.
4039         if (format != backend_format) {
4040                 if (runparams.silent)
4041                         error_list.clear();
4042                 else if (d->cloned_buffer_)
4043                         d->cloned_buffer_->d->errorLists[error_type] =
4044                                 d->errorLists[error_type];
4045                 else
4046                         errors(error_type);
4047                 // also to the children, in case of master-buffer-view
4048                 ListOfBuffers clist = getDescendents();
4049                 ListOfBuffers::const_iterator cit = clist.begin();
4050                 ListOfBuffers::const_iterator const cen = clist.end();
4051                 for (; cit != cen; ++cit) {
4052                         if (runparams.silent)
4053                                 (*cit)->d->errorLists[error_type].clear();
4054                         else if (d->cloned_buffer_) {
4055                                 // Enable reverse search by copying back the
4056                                 // texrow object to the cloned buffer.
4057                                 // FIXME: this is not thread safe.
4058                                 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
4059                                 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
4060                                         (*cit)->d->errorLists[error_type];
4061                         } else
4062                                 (*cit)->errors(error_type, true);
4063                 }
4064         }
4065
4066         if (d->cloned_buffer_) {
4067                 // Enable reverse dvi or pdf to work by copying back the texrow
4068                 // object to the cloned buffer.
4069                 // FIXME: There is a possibility of concurrent access to texrow
4070                 // here from the main GUI thread that should be securized.
4071                 d->cloned_buffer_->d->texrow = d->texrow;
4072                 string const error_type = params().bufferFormat();
4073                 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
4074         }
4075
4076
4077         if (put_in_tempdir) {
4078                 result_file = tmp_result_file.absFileName();
4079                 return success ? ExportSuccess : ExportConverterError;
4080         }
4081
4082         if (dest_filename.empty())
4083                 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4084         else
4085                 result_file = dest_filename;
4086         // We need to copy referenced files (e. g. included graphics
4087         // if format == "dvi") to the result dir.
4088         vector<ExportedFile> const files =
4089                 runparams.exportdata->externalFiles(format);
4090         string const dest = runparams.export_folder.empty() ?
4091                 onlyPath(result_file) : runparams.export_folder;
4092         bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4093                                  : force_overwrite == ALL_FILES;
4094         CopyStatus status = use_force ? FORCE : SUCCESS;
4095
4096         vector<ExportedFile>::const_iterator it = files.begin();
4097         vector<ExportedFile>::const_iterator const en = files.end();
4098         for (; it != en && status != CANCEL; ++it) {
4099                 string const fmt = formats.getFormatFromFile(it->sourceName);
4100                 string fixedName = it->exportName;
4101                 if (!runparams.export_folder.empty()) {
4102                         // Relative pathnames starting with ../ will be sanitized
4103                         // if exporting to a different folder
4104                         while (fixedName.substr(0, 3) == "../")
4105                                 fixedName = fixedName.substr(3, fixedName.length() - 3);
4106                 }
4107                 FileName fixedFileName = makeAbsPath(fixedName, dest);
4108                 fixedFileName.onlyPath().createPath();
4109                 status = copyFile(fmt, it->sourceName,
4110                         fixedFileName,
4111                         it->exportName, status == FORCE,
4112                         runparams.export_folder.empty());
4113         }
4114
4115         if (status == CANCEL) {
4116                 message(_("Document export cancelled."));
4117                 return ExportCancel;
4118         }
4119
4120         if (tmp_result_file.exists()) {
4121                 // Finally copy the main file
4122                 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4123                                     : force_overwrite != NO_FILES;
4124                 if (status == SUCCESS && use_force)
4125                         status = FORCE;
4126                 status = copyFile(format, tmp_result_file,
4127                         FileName(result_file), result_file,
4128                         status == FORCE);
4129                 if (status == CANCEL) {
4130                         message(_("Document export cancelled."));
4131                         return ExportCancel;
4132                 } else {
4133                         message(bformat(_("Document exported as %1$s "
4134                                 "to file `%2$s'"),
4135                                 formats.prettyName(format),
4136                                 makeDisplayPath(result_file)));
4137                 }
4138         } else {
4139                 // This must be a dummy converter like fax (bug 1888)
4140                 message(bformat(_("Document exported as %1$s"),
4141                         formats.prettyName(format)));
4142         }
4143
4144         return success ? ExportSuccess : ExportConverterError;
4145 }
4146
4147
4148 Buffer::ExportStatus Buffer::preview(string const & format) const
4149 {
4150         bool const update_unincluded =
4151                         params().maintain_unincluded_children
4152                         && !params().getIncludedChildren().empty();
4153         return preview(format, update_unincluded);
4154 }
4155
4156
4157 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4158 {
4159         MarkAsExporting exporting(this);
4160         string result_file;
4161         // (1) export with all included children (omit \includeonly)
4162         if (includeall) {
4163                 ExportStatus const status = doExport(format, true, true, result_file);
4164                 if (status != ExportSuccess)
4165                         return status;
4166         }
4167         // (2) export with included children only
4168         ExportStatus const status = doExport(format, true, false, result_file);
4169         FileName const previewFile(result_file);
4170
4171         LATTEST (isClone());
4172         d->cloned_buffer_->d->preview_file_ = previewFile;
4173         d->cloned_buffer_->d->preview_format_ = format;
4174         d->cloned_buffer_->d->preview_error_ = (status != ExportSuccess);
4175
4176         if (status != ExportSuccess)
4177                 return status;
4178         if (previewFile.exists()) {
4179                 if (!formats.view(*this, previewFile, format))
4180                         return PreviewError;
4181                 else
4182                         return PreviewSuccess;
4183         }
4184         else {
4185                 // Successful export but no output file?
4186                 // Probably a bug in error detection.
4187                 LATTEST (status != ExportSuccess);
4188
4189                 return status;
4190         }
4191 }
4192
4193
4194 Buffer::ReadStatus Buffer::extractFromVC()
4195 {
4196         bool const found = LyXVC::file_not_found_hook(d->filename);
4197         if (!found)
4198                 return ReadFileNotFound;
4199         if (!d->filename.isReadableFile())
4200                 return ReadVCError;
4201         return ReadSuccess;
4202 }
4203
4204
4205 Buffer::ReadStatus Buffer::loadEmergency()
4206 {
4207         FileName const emergencyFile = getEmergencyFileName();
4208         if (!emergencyFile.exists()
4209                   || emergencyFile.lastModified() <= d->filename.lastModified())
4210                 return ReadFileNotFound;
4211
4212         docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4213         docstring const text = bformat(_("An emergency save of the document "
4214                 "%1$s exists.\n\nRecover emergency save?"), file);
4215
4216         int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4217                 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4218
4219         switch (load_emerg)
4220         {
4221         case 0: {
4222                 docstring str;
4223                 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4224                 bool const success = (ret_llf == ReadSuccess);
4225                 if (success) {
4226                         if (isReadonly()) {
4227                                 Alert::warning(_("File is read-only"),
4228                                         bformat(_("An emergency file is successfully loaded, "
4229                                         "but the original file %1$s is marked read-only. "
4230                                         "Please make sure to save the document as a different "
4231                                         "file."), from_utf8(d->filename.absFileName())));
4232                         }
4233                         markDirty();
4234                         lyxvc().file_found_hook(d->filename);
4235                         str = _("Document was successfully recovered.");
4236                 } else
4237                         str = _("Document was NOT successfully recovered.");
4238                 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4239                         makeDisplayPath(emergencyFile.absFileName()));
4240
4241                 int const del_emerg =
4242                         Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4243                                 _("&Remove"), _("&Keep"));
4244                 if (del_emerg == 0) {
4245                         emergencyFile.removeFile();
4246                         if (success)
4247                                 Alert::warning(_("Emergency file deleted"),
4248                                         _("Do not forget to save your file now!"), true);
4249                         }
4250                 return success ? ReadSuccess : ReadEmergencyFailure;
4251         }
4252         case 1: {
4253                 int const del_emerg =
4254                         Alert::prompt(_("Delete emergency file?"),
4255                                 _("Remove emergency file now?"), 1, 1,
4256                                 _("&Remove"), _("&Keep"));
4257                 if (del_emerg == 0)
4258                         emergencyFile.removeFile();
4259                 return ReadOriginal;
4260         }
4261
4262         default:
4263                 break;
4264         }
4265         return ReadCancel;
4266 }
4267
4268
4269 Buffer::ReadStatus Buffer::loadAutosave()
4270 {
4271         // Now check if autosave file is newer.
4272         FileName const autosaveFile = getAutosaveFileName();
4273         if (!autosaveFile.exists()
4274                   || autosaveFile.lastModified() <= d->filename.lastModified())
4275                 return ReadFileNotFound;
4276
4277         docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4278         docstring const text = bformat(_("The backup of the document %1$s "
4279                 "is newer.\n\nLoad the backup instead?"), file);
4280         int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4281                 _("&Load backup"), _("Load &original"), _("&Cancel"));
4282
4283         switch (ret)
4284         {
4285         case 0: {
4286                 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4287                 // the file is not saved if we load the autosave file.
4288                 if (ret_llf == ReadSuccess) {
4289                         if (isReadonly()) {
4290                                 Alert::warning(_("File is read-only"),
4291                                         bformat(_("A backup file is successfully loaded, "
4292                                         "but the original file %1$s is marked read-only. "
4293                                         "Please make sure to save the document as a "
4294                                         "different file."),
4295                                         from_utf8(d->filename.absFileName())));
4296                         }
4297                         markDirty();
4298                         lyxvc().file_found_hook(d->filename);
4299                         return ReadSuccess;
4300                 }
4301                 return ReadAutosaveFailure;
4302         }
4303         case 1:
4304                 // Here we delete the autosave
4305                 autosaveFile.removeFile();
4306                 return ReadOriginal;
4307         default:
4308                 break;
4309         }
4310         return ReadCancel;
4311 }
4312
4313
4314 Buffer::ReadStatus Buffer::loadLyXFile()
4315 {
4316         if (!d->filename.isReadableFile()) {
4317                 ReadStatus const ret_rvc = extractFromVC();
4318                 if (ret_rvc != ReadSuccess)
4319                         return ret_rvc;
4320         }
4321
4322         ReadStatus const ret_re = loadEmergency();
4323         if (ret_re == ReadSuccess || ret_re == ReadCancel)
4324                 return ret_re;
4325
4326         ReadStatus const ret_ra = loadAutosave();
4327         if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4328                 return ret_ra;
4329
4330         return loadThisLyXFile(d->filename);
4331 }
4332
4333
4334 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4335 {
4336         return readFile(fn);
4337 }
4338
4339
4340 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4341 {
4342         TeXErrors::Errors::const_iterator it = terr.begin();
4343         TeXErrors::Errors::const_iterator end = terr.end();
4344         ListOfBuffers clist = getDescendents();
4345         ListOfBuffers::const_iterator cen = clist.end();
4346
4347         for (; it != end; ++it) {
4348                 int id_start = -1;
4349                 int pos_start = -1;
4350                 int errorRow = it->error_in_line;
4351                 Buffer const * buf = 0;
4352                 Impl const * p = d;
4353                 if (it->child_name.empty())
4354                     p->texrow.getIdFromRow(errorRow, id_start, pos_start);
4355                 else {
4356                         // The error occurred in a child
4357                         ListOfBuffers::const_iterator cit = clist.begin();
4358                         for (; cit != cen; ++cit) {
4359                                 string const child_name =
4360                                         DocFileName(changeExtension(
4361                                                 (*cit)->absFileName(), "tex")).
4362                                                         mangledFileName();
4363                                 if (it->child_name != child_name)
4364                                         continue;
4365                                 (*cit)->d->texrow.getIdFromRow(errorRow,
4366                                                         id_start, pos_start);
4367                                 if (id_start != -1) {
4368                                         buf = d->cloned_buffer_
4369                                                 ? (*cit)->d->cloned_buffer_->d->owner_
4370                                                 : (*cit)->d->owner_;
4371                                         p = (*cit)->d;
4372                                         break;
4373                                 }
4374                         }
4375                 }
4376                 int id_end = -1;
4377                 int pos_end = -1;
4378                 bool found;
4379                 do {
4380                         ++errorRow;
4381                         found = p->texrow.getIdFromRow(errorRow, id_end, pos_end);
4382                 } while (found && id_start == id_end && pos_start == pos_end);
4383
4384                 if (id_start != id_end) {
4385                         // Next registered position is outside the inset where
4386                         // the error occurred, so signal end-of-paragraph
4387                         pos_end = 0;
4388                 }
4389
4390                 errorList.push_back(ErrorItem(it->error_desc,
4391                         it->error_text, id_start, pos_start, pos_end, buf));
4392         }
4393 }
4394
4395
4396 void Buffer::setBuffersForInsets() const
4397 {
4398         inset().setBuffer(const_cast<Buffer &>(*this));
4399 }
4400
4401
4402 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4403 {
4404         LBUFERR(!text().paragraphs().empty());
4405
4406         // Use the master text class also for child documents
4407         Buffer const * const master = masterBuffer();
4408         DocumentClass const & textclass = master->params().documentClass();
4409
4410         // do this only if we are the top-level Buffer
4411         if (master == this) {
4412                 textclass.counters().reset(from_ascii("bibitem"));
4413                 reloadBibInfoCache();
4414         }
4415
4416         // keep the buffers to be children in this set. If the call from the
4417         // master comes back we can see which of them were actually seen (i.e.
4418         // via an InsetInclude). The remaining ones in the set need still be updated.
4419         static std::set<Buffer const *> bufToUpdate;
4420         if (scope == UpdateMaster) {
4421                 // If this is a child document start with the master
4422                 if (master != this) {
4423                         bufToUpdate.insert(this);
4424                         master->updateBuffer(UpdateMaster, utype);
4425                         // If the master buffer has no gui associated with it, then the TocModel is
4426                         // not updated during the updateBuffer call and TocModel::toc_ is invalid
4427                         // (bug 5699). The same happens if the master buffer is open in a different
4428                         // window. This test catches both possibilities.
4429                         // See: http://marc.info/?l=lyx-devel&m=138590578911716&w=2
4430                         // There remains a problem here: If there is another child open in yet a third
4431                         // window, that TOC is not updated. So some more general solution is needed at
4432                         // some point.
4433                         if (master->d->gui_ != d->gui_)
4434                                 structureChanged();
4435
4436                         // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4437                         if (bufToUpdate.find(this) == bufToUpdate.end())
4438                                 return;
4439                 }
4440
4441                 // start over the counters in the master
4442                 textclass.counters().reset();
4443         }
4444
4445         // update will be done below for this buffer
4446         bufToUpdate.erase(this);
4447
4448         // update all caches
4449         clearReferenceCache();
4450         updateMacros();
4451
4452         Buffer & cbuf = const_cast<Buffer &>(*this);
4453
4454         // do the real work
4455         ParIterator parit = cbuf.par_iterator_begin();
4456         updateBuffer(parit, utype);
4457
4458         if (master != this)
4459                 // TocBackend update will be done later.
4460                 return;
4461
4462         d->bibinfo_cache_valid_ = true;
4463         d->cite_labels_valid_ = true;
4464         /// FIXME: Perf
4465         cbuf.tocBackend().update(utype == OutputUpdate);
4466         if (scope == UpdateMaster)
4467                 cbuf.structureChanged();
4468 }
4469
4470
4471 static depth_type getDepth(DocIterator const & it)
4472 {
4473         depth_type depth = 0;
4474         for (size_t i = 0 ; i < it.depth() ; ++i)
4475                 if (!it[i].inset().inMathed())
4476                         depth += it[i].paragraph().getDepth() + 1;
4477         // remove 1 since the outer inset does not count
4478         return depth - 1;
4479 }
4480
4481 static depth_type getItemDepth(ParIterator const & it)
4482 {
4483         Paragraph const & par = *it;
4484         LabelType const labeltype = par.layout().labeltype;
4485
4486         if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4487                 return 0;
4488
4489         // this will hold the lowest depth encountered up to now.
4490         depth_type min_depth = getDepth(it);
4491         ParIterator prev_it = it;
4492         while (true) {
4493                 if (prev_it.pit())
4494                         --prev_it.top().pit();
4495                 else {
4496                         // start of nested inset: go to outer par
4497                         prev_it.pop_back();
4498                         if (prev_it.empty()) {
4499                                 // start of document: nothing to do
4500                                 return 0;
4501                         }
4502                 }
4503
4504                 // We search for the first paragraph with same label
4505                 // that is not more deeply nested.
4506                 Paragraph & prev_par = *prev_it;
4507                 depth_type const prev_depth = getDepth(prev_it);
4508                 if (labeltype == prev_par.layout().labeltype) {
4509                         if (prev_depth < min_depth)
4510                                 return prev_par.itemdepth + 1;
4511                         if (prev_depth == min_depth)
4512                                 return prev_par.itemdepth;
4513                 }
4514                 min_depth = min(min_depth, prev_depth);
4515                 // small optimization: if we are at depth 0, we won't
4516                 // find anything else
4517                 if (prev_depth == 0)
4518                         return 0;
4519         }
4520 }
4521
4522
4523 static bool needEnumCounterReset(ParIterator const & it)
4524 {
4525         Paragraph const & par = *it;
4526         LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
4527         depth_type const cur_depth = par.getDepth();
4528         ParIterator prev_it = it;
4529         while (prev_it.pit()) {
4530                 --prev_it.top().pit();
4531                 Paragraph const & prev_par = *prev_it;
4532                 if (prev_par.getDepth() <= cur_depth)
4533                         return  prev_par.layout().labeltype != LABEL_ENUMERATE;
4534         }
4535         // start of nested inset: reset
4536         return true;
4537 }
4538
4539
4540 // set the label of a paragraph. This includes the counters.
4541 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4542 {
4543         BufferParams const & bp = owner_->masterBuffer()->params();
4544         DocumentClass const & textclass = bp.documentClass();
4545         Paragraph & par = it.paragraph();
4546         Layout const & layout = par.layout();
4547         Counters & counters = textclass.counters();
4548
4549         if (par.params().startOfAppendix()) {
4550                 // We want to reset the counter corresponding to toplevel sectioning
4551                 Layout const & lay = textclass.getTOCLayout();
4552                 docstring const cnt = lay.counter;
4553                 if (!cnt.empty())
4554                         counters.reset(cnt);
4555                 counters.appendix(true);
4556         }
4557         par.params().appendix(counters.appendix());
4558
4559         // Compute the item depth of the paragraph
4560         par.itemdepth = getItemDepth(it);
4561
4562         if (layout.margintype == MARGIN_MANUAL) {
4563                 if (par.params().labelWidthString().empty())
4564                         par.params().labelWidthString(par.expandLabel(layout, bp));
4565         } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4566                 // we do not need to do anything here, since the empty case is
4567                 // handled during export.
4568         } else {
4569                 par.params().labelWidthString(docstring());
4570         }
4571
4572         switch(layout.labeltype) {
4573         case LABEL_ITEMIZE: {
4574                 // At some point of time we should do something more
4575                 // clever here, like:
4576                 //   par.params().labelString(
4577                 //    bp.user_defined_bullet(par.itemdepth).getText());
4578                 // for now, use a simple hardcoded label
4579                 docstring itemlabel;
4580                 switch (par.itemdepth) {
4581                 case 0:
4582                         itemlabel = char_type(0x2022);
4583                         break;
4584                 case 1:
4585                         itemlabel = char_type(0x2013);
4586                         break;
4587                 case 2:
4588                         itemlabel = char_type(0x2217);
4589                         break;
4590                 case 3:
4591                         itemlabel = char_type(0x2219); // or 0x00b7
4592                         break;
4593                 }
4594                 par.params().labelString(itemlabel);
4595                 break;
4596         }
4597
4598         case LABEL_ENUMERATE: {
4599                 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4600
4601                 switch (par.itemdepth) {
4602                 case 2:
4603                         enumcounter += 'i';
4604                 case 1:
4605                         enumcounter += 'i';
4606                 case 0:
4607                         enumcounter += 'i';
4608                         break;
4609                 case 3:
4610                         enumcounter += "iv";
4611                         break;
4612                 default:
4613                         // not a valid enumdepth...
4614                         break;
4615                 }
4616
4617                 // Maybe we have to reset the enumeration counter.
4618                 if (needEnumCounterReset(it))
4619                         counters.reset(enumcounter);
4620                 counters.step(enumcounter, utype);
4621
4622                 string const & lang = par.getParLanguage(bp)->code();
4623                 par.params().labelString(counters.theCounter(enumcounter, lang));
4624
4625                 break;
4626         }
4627
4628         case LABEL_SENSITIVE: {
4629                 string const & type = counters.current_float();
4630                 docstring full_label;
4631                 if (type.empty())
4632                         full_label = owner_->B_("Senseless!!! ");
4633                 else {
4634                         docstring name = owner_->B_(textclass.floats().getType(type).name());
4635                         if (counters.hasCounter(from_utf8(type))) {
4636                                 string const & lang = par.getParLanguage(bp)->code();
4637                                 counters.step(from_utf8(type), utype);
4638                                 full_label = bformat(from_ascii("%1$s %2$s:"),
4639                                                      name,
4640                                                      counters.theCounter(from_utf8(type), lang));
4641                         } else
4642                                 full_label = bformat(from_ascii("%1$s #:"), name);
4643                 }
4644                 par.params().labelString(full_label);
4645                 break;
4646         }
4647
4648         case LABEL_NO_LABEL:
4649                 par.params().labelString(docstring());
4650                 break;
4651
4652         case LABEL_ABOVE:
4653         case LABEL_CENTERED:
4654         case LABEL_STATIC: {
4655                 docstring const & lcounter = layout.counter;
4656                 if (!lcounter.empty()) {
4657                         if (layout.toclevel <= bp.secnumdepth
4658                                                 && (layout.latextype != LATEX_ENVIRONMENT
4659                                         || it.text()->isFirstInSequence(it.pit()))) {
4660                                 if (counters.hasCounter(lcounter))
4661                                         counters.step(lcounter, utype);
4662                                 par.params().labelString(par.expandLabel(layout, bp));
4663                         } else
4664                                 par.params().labelString(docstring());
4665                 } else
4666                         par.params().labelString(par.expandLabel(layout, bp));
4667                 break;
4668         }
4669
4670         case LABEL_MANUAL:
4671         case LABEL_BIBLIO:
4672                 par.params().labelString(par.expandLabel(layout, bp));
4673         }
4674 }
4675
4676
4677 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4678 {
4679         // LASSERT: Is it safe to continue here, or should we just return?
4680         LASSERT(parit.pit() == 0, /**/);
4681
4682         // Set the position of the text in the buffer to be able
4683         // to resolve macros in it.
4684         parit.text()->setMacrocontextPosition(parit);
4685
4686         depth_type maxdepth = 0;
4687         pit_type const lastpit = parit.lastpit();
4688         for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4689                 // reduce depth if necessary
4690                 if (parit->params().depth() > maxdepth) {
4691                         /** FIXME: this function is const, but
4692                          * nevertheless it modifies the buffer. To be
4693                          * cleaner, one should modify the buffer in
4694                          * another function, which is actually
4695                          * non-const. This would however be costly in
4696                          * terms of code duplication.
4697                          */
4698                         const_cast<Buffer *>(this)->undo().recordUndo(CursorData(parit));
4699                         parit->params().depth(maxdepth);
4700                 }
4701                 maxdepth = parit->getMaxDepthAfter();
4702
4703                 if (utype == OutputUpdate) {
4704                         // track the active counters
4705                         // we have to do this for the master buffer, since the local
4706                         // buffer isn't tracking anything.
4707                         masterBuffer()->params().documentClass().counters().
4708                                         setActiveLayout(parit->layout());
4709                 }
4710
4711                 // set the counter for this paragraph
4712                 d->setLabel(parit, utype);
4713
4714                 // now the insets
4715                 InsetList::const_iterator iit = parit->insetList().begin();
4716                 InsetList::const_iterator end = parit->insetList().end();
4717                 for (; iit != end; ++iit) {
4718                         parit.pos() = iit->pos;
4719                         iit->inset->updateBuffer(parit, utype);
4720                 }
4721         }
4722 }
4723
4724
4725 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4726         WordLangTuple & word_lang, docstring_list & suggestions) const
4727 {
4728         int progress = 0;
4729         WordLangTuple wl;
4730         suggestions.clear();
4731         word_lang = WordLangTuple();
4732         bool const to_end = to.empty();
4733         DocIterator const end = to_end ? doc_iterator_end(this) : to;
4734         // OK, we start from here.
4735         for (; from != end; from.forwardPos()) {
4736                 // This skips all insets with spell check disabled.
4737                 while (!from.allowSpellCheck()) {
4738                         from.pop_back();
4739                         from.pos()++;
4740                 }
4741                 // If from is at the end of the document (which is possible
4742                 // when "from" was changed above) LyX will crash later otherwise.
4743                 if (from.atEnd() || (!to_end && from >= end))
4744                         break;
4745                 to = from;
4746                 from.paragraph().spellCheck();
4747                 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4748                 if (SpellChecker::misspelled(res)) {
4749                         word_lang = wl;
4750                         break;
4751                 }
4752                 // Do not increase progress when from == to, otherwise the word
4753                 // count will be wrong.
4754                 if (from != to) {
4755                         from = to;
4756                         ++progress;
4757                 }
4758         }
4759         return progress;
4760 }
4761
4762
4763 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
4764 {
4765         bool inword = false;
4766         word_count_ = 0;
4767         char_count_ = 0;
4768         blank_count_ = 0;
4769
4770         for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
4771                 if (!dit.inTexted()) {
4772                         dit.forwardPos();
4773                         continue;
4774                 }
4775
4776                 Paragraph const & par = dit.paragraph();
4777                 pos_type const pos = dit.pos();
4778
4779                 // Copied and adapted from isWordSeparator() in Paragraph
4780                 if (pos == dit.lastpos()) {
4781                         inword = false;
4782                 } else {
4783                         Inset const * ins = par.getInset(pos);
4784                         if (ins && skipNoOutput && !ins->producesOutput()) {
4785                                 // skip this inset
4786                                 ++dit.top().pos();
4787                                 // stop if end of range was skipped
4788                                 if (!to.atEnd() && dit >= to)
4789                                         break;
4790                                 continue;
4791                         } else if (!par.isDeleted(pos)) {
4792                                 if (par.isWordSeparator(pos))
4793                                         inword = false;
4794                                 else if (!inword) {
4795                                         ++word_count_;
4796                                         inword = true;
4797                                 }
4798                                 if (ins && ins->isLetter())
4799                                         ++char_count_;
4800                                 else if (ins && ins->isSpace())
4801                                         ++blank_count_;
4802                                 else {
4803                                         char_type const c = par.getChar(pos);
4804                                         if (isPrintableNonspace(c))
4805                                                 ++char_count_;
4806                                         else if (isSpace(c))
4807                                                 ++blank_count_;
4808                                 }
4809                         }
4810                 }
4811                 dit.forwardPos();
4812         }
4813 }
4814
4815
4816 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
4817 {
4818         d->updateStatistics(from, to, skipNoOutput);
4819 }
4820
4821
4822 int Buffer::wordCount() const
4823 {
4824         return d->wordCount();
4825 }
4826
4827
4828 int Buffer::charCount(bool with_blanks) const
4829 {
4830         return d->charCount(with_blanks);
4831 }
4832
4833
4834 Buffer::ReadStatus Buffer::reload()
4835 {
4836         setBusy(true);
4837         // c.f. bug http://www.lyx.org/trac/ticket/6587
4838         removeAutosaveFile();
4839         // e.g., read-only status could have changed due to version control
4840         d->filename.refresh();
4841         docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4842
4843         // clear parent. this will get reset if need be.
4844         d->setParent(0);
4845         ReadStatus const status = loadLyXFile();
4846         if (status == ReadSuccess) {
4847                 updateBuffer();
4848                 changed(true);
4849                 updateTitles();
4850                 markClean();
4851                 message(bformat(_("Document %1$s reloaded."), disp_fn));
4852                 d->undo_.clear();
4853         } else {
4854                 message(bformat(_("Could not reload document %1$s."), disp_fn));
4855         }
4856         setBusy(false);
4857         removePreviews();
4858         updatePreviews();
4859         errors("Parse");
4860         return status;
4861 }
4862
4863
4864 bool Buffer::saveAs(FileName const & fn)
4865 {
4866         FileName const old_name = fileName();
4867         FileName const old_auto = getAutosaveFileName();
4868         bool const old_unnamed = isUnnamed();
4869         bool success = true;
4870         d->old_position = filePath();
4871
4872         setFileName(fn);
4873         markDirty();
4874         setUnnamed(false);
4875
4876         if (save()) {
4877                 // bring the autosave file with us, just in case.
4878                 moveAutosaveFile(old_auto);
4879                 // validate version control data and
4880                 // correct buffer title
4881                 lyxvc().file_found_hook(fileName());
4882                 updateTitles();
4883                 // the file has now been saved to the new location.
4884                 // we need to check that the locations of child buffers
4885                 // are still valid.
4886                 checkChildBuffers();
4887                 checkMasterBuffer();
4888         } else {
4889                 // save failed
4890                 // reset the old filename and unnamed state
4891                 setFileName(old_name);
4892                 setUnnamed(old_unnamed);
4893                 success = false;
4894         }
4895
4896         d->old_position.clear();
4897         return success;
4898 }
4899
4900
4901 void Buffer::checkChildBuffers()
4902 {
4903         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4904         Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4905         for (; it != en; ++it) {
4906                 DocIterator dit = it->second;
4907                 Buffer * cbuf = const_cast<Buffer *>(it->first);
4908                 if (!cbuf || !theBufferList().isLoaded(cbuf))
4909                         continue;
4910                 Inset * inset = dit.nextInset();
4911                 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4912                 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4913                 docstring const & incfile = inset_inc->getParam("filename");
4914                 string oldloc = cbuf->absFileName();
4915                 string newloc = makeAbsPath(to_utf8(incfile),
4916                                 onlyPath(absFileName())).absFileName();
4917                 if (oldloc == newloc)
4918                         continue;
4919                 // the location of the child file is incorrect.
4920                 cbuf->setParent(0);
4921                 inset_inc->setChildBuffer(0);
4922         }
4923         // invalidate cache of children
4924         d->children_positions.clear();
4925         d->position_to_children.clear();
4926 }
4927
4928
4929 // If a child has been saved under a different name/path, it might have been
4930 // orphaned. Therefore the master needs to be reset (bug 8161).
4931 void Buffer::checkMasterBuffer()
4932 {
4933         Buffer const * const master = masterBuffer();
4934         if (master == this)
4935                 return;
4936
4937         // necessary to re-register the child (bug 5873)
4938         // FIXME: clean up updateMacros (here, only
4939         // child registering is needed).
4940         master->updateMacros();
4941         // (re)set master as master buffer, but only
4942         // if we are a real child
4943         if (master->isChild(this))
4944                 setParent(master);
4945         else
4946                 setParent(0);
4947 }
4948
4949
4950 string Buffer::includedFilePath(string const & name, string const & ext) const
4951 {
4952         bool isabsolute = FileName::isAbsolute(name);
4953         // old_position already contains a trailing path separator
4954         string const absname = isabsolute ? name : d->old_position + name;
4955
4956         if (d->old_position.empty()
4957             || equivalent(FileName(d->old_position), FileName(filePath()))
4958             || !FileName(addExtension(absname, ext)).exists())
4959                 return name;
4960
4961         if (isabsolute)
4962                 return to_utf8(makeRelPath(from_utf8(name), from_utf8(filePath())));
4963
4964         return to_utf8(makeRelPath(from_utf8(FileName(absname).realPath()),
4965                                    from_utf8(filePath())));
4966 }
4967
4968 } // namespace lyx