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