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