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