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