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