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