]> git.lyx.org Git - lyx.git/blob - src/Buffer.cpp
01a72f287951c4a9e9e412f7bac6b03de6a5f8be
[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 if (res > 0) {
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         InsetCode code)
3364 {
3365         //FIXME: This does not work for child documents yet.
3366         LASSERT(code == CITE_CODE, /**/);
3367
3368         reloadBibInfoCache();
3369
3370         // Check if the label 'from' appears more than once
3371         BiblioInfo const & keys = masterBibInfo();
3372         BiblioInfo::const_iterator bit  = keys.begin();
3373         BiblioInfo::const_iterator bend = keys.end();
3374         vector<docstring> labels;
3375
3376         for (; bit != bend; ++bit)
3377                 // FIXME UNICODE
3378                 labels.push_back(bit->first);
3379
3380         if (count(labels.begin(), labels.end(), from) > 1)
3381                 return;
3382
3383         string const paramName = "key";
3384         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3385                 if (it->lyxCode() == code) {
3386                         InsetCommand * inset = it->asInsetCommand();
3387                         if (!inset)
3388                                 continue;
3389                         docstring const oldValue = inset->getParam(paramName);
3390                         if (oldValue == from)
3391                                 inset->setParam(paramName, to);
3392                 }
3393         }
3394 }
3395
3396
3397 void Buffer::getSourceCode(odocstream & os, string const format,
3398                            pit_type par_begin, pit_type par_end,
3399                            OutputWhat output, bool master) const
3400 {
3401         OutputParams runparams(&params().encoding());
3402         runparams.nice = true;
3403         runparams.flavor = params().getOutputFlavor(format);
3404         runparams.linelen = lyxrc.plaintext_linelen;
3405         // No side effect of file copying and image conversion
3406         runparams.dryrun = true;
3407
3408         if (output == CurrentParagraph) {
3409                 runparams.par_begin = par_begin;
3410                 runparams.par_end = par_end;
3411                 if (par_begin + 1 == par_end) {
3412                         os << "% "
3413                            << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3414                            << "\n\n";
3415                 } else {
3416                         os << "% "
3417                            << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3418                                         convert<docstring>(par_begin),
3419                                         convert<docstring>(par_end - 1))
3420                            << "\n\n";
3421                 }
3422                 // output paragraphs
3423                 if (runparams.flavor == OutputParams::LYX) {
3424                         Paragraph const & par = text().paragraphs()[par_begin];
3425                         ostringstream ods;
3426                         depth_type dt = par.getDepth();
3427                         par.write(ods, params(), dt);
3428                         os << from_utf8(ods.str());
3429                 } else if (runparams.flavor == OutputParams::HTML) {
3430                         XHTMLStream xs(os);
3431                         setMathFlavor(runparams);
3432                         xhtmlParagraphs(text(), *this, xs, runparams);
3433                 } else if (runparams.flavor == OutputParams::TEXT) {
3434                         bool dummy;
3435                         // FIXME Handles only one paragraph, unlike the others.
3436                         // Probably should have some routine with a signature like them.
3437                         writePlaintextParagraph(*this,
3438                                 text().paragraphs()[par_begin], os, runparams, dummy);
3439                 } else if (params().isDocBook()) {
3440                         docbookParagraphs(text(), *this, os, runparams);
3441                 } else {
3442                         // If we are previewing a paragraph, even if this is the
3443                         // child of some other buffer, let's cut the link here,
3444                         // so that no concurring settings from the master
3445                         // (e.g. branch state) interfere (see #8101).
3446                         if (!master)
3447                                 d->ignore_parent = true;
3448                         // We need to validate the Buffer params' features here
3449                         // in order to know if we should output polyglossia
3450                         // macros (instead of babel macros)
3451                         LaTeXFeatures features(*this, params(), runparams);
3452                         params().validate(features);
3453                         runparams.use_polyglossia = features.usePolyglossia();
3454                         TexRow texrow;
3455                         texrow.reset();
3456                         texrow.newline();
3457                         texrow.newline();
3458                         // latex or literate
3459                         otexstream ots(os, texrow);
3460
3461                         // the real stuff
3462                         latexParagraphs(*this, text(), ots, runparams);
3463
3464                         // Restore the parenthood
3465                         if (!master)
3466                                 d->ignore_parent = false;
3467                 }
3468         } else {
3469                 os << "% ";
3470                 if (output == FullSource)
3471                         os << _("Preview source code");
3472                 else if (output == OnlyPreamble)
3473                         os << _("Preview preamble");
3474                 else if (output == OnlyBody)
3475                         os << _("Preview body");
3476                 os << "\n\n";
3477                 if (runparams.flavor == OutputParams::LYX) {
3478                         ostringstream ods;
3479                         if (output == FullSource)
3480                                 write(ods);
3481                         else if (output == OnlyPreamble)
3482                                 params().writeFile(ods);
3483                         else if (output == OnlyBody)
3484                                 text().write(ods);
3485                         os << from_utf8(ods.str());
3486                 } else if (runparams.flavor == OutputParams::HTML) {
3487                         writeLyXHTMLSource(os, runparams, output);
3488                 } else if (runparams.flavor == OutputParams::TEXT) {
3489                         if (output == OnlyPreamble) {
3490                                 os << "% "<< _("Plain text does not have a preamble.");
3491                         } else
3492                                 writePlaintextFile(*this, os, runparams);
3493                 } else if (params().isDocBook()) {
3494                                 writeDocBookSource(os, absFileName(), runparams, output);
3495                 } else {
3496                         // latex or literate
3497                         d->texrow.reset();
3498                         d->texrow.newline();
3499                         d->texrow.newline();
3500                         otexstream ots(os, d->texrow);
3501                         if (master)
3502                                 runparams.is_child = true;
3503                         writeLaTeXSource(ots, string(), runparams, output);
3504                 }
3505         }
3506 }
3507
3508
3509 ErrorList & Buffer::errorList(string const & type) const
3510 {
3511         return d->errorLists[type];
3512 }
3513
3514
3515 void Buffer::updateTocItem(std::string const & type,
3516         DocIterator const & dit) const
3517 {
3518         if (d->gui_)
3519                 d->gui_->updateTocItem(type, dit);
3520 }
3521
3522
3523 void Buffer::structureChanged() const
3524 {
3525         if (d->gui_)
3526                 d->gui_->structureChanged();
3527 }
3528
3529
3530 void Buffer::errors(string const & err, bool from_master) const
3531 {
3532         if (d->gui_)
3533                 d->gui_->errors(err, from_master);
3534 }
3535
3536
3537 void Buffer::message(docstring const & msg) const
3538 {
3539         if (d->gui_)
3540                 d->gui_->message(msg);
3541 }
3542
3543
3544 void Buffer::setBusy(bool on) const
3545 {
3546         if (d->gui_)
3547                 d->gui_->setBusy(on);
3548 }
3549
3550
3551 void Buffer::updateTitles() const
3552 {
3553         if (d->wa_)
3554                 d->wa_->updateTitles();
3555 }
3556
3557
3558 void Buffer::resetAutosaveTimers() const
3559 {
3560         if (d->gui_)
3561                 d->gui_->resetAutosaveTimers();
3562 }
3563
3564
3565 bool Buffer::hasGuiDelegate() const
3566 {
3567         return d->gui_;
3568 }
3569
3570
3571 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3572 {
3573         d->gui_ = gui;
3574 }
3575
3576
3577
3578 namespace {
3579
3580 class AutoSaveBuffer : public ForkedProcess {
3581 public:
3582         ///
3583         AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3584                 : buffer_(buffer), fname_(fname) {}
3585         ///
3586         virtual shared_ptr<ForkedProcess> clone() const
3587         {
3588                 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3589         }
3590         ///
3591         int start()
3592         {
3593                 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3594                                                  from_utf8(fname_.absFileName())));
3595                 return run(DontWait);
3596         }
3597 private:
3598         ///
3599         virtual int generateChild();
3600         ///
3601         Buffer const & buffer_;
3602         FileName fname_;
3603 };
3604
3605
3606 int AutoSaveBuffer::generateChild()
3607 {
3608 #if defined(__APPLE__)
3609         /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3610          *   We should use something else like threads.
3611          *
3612          * Since I do not know how to determine at run time what is the OS X
3613          * version, I just disable forking altogether for now (JMarc)
3614          */
3615         pid_t const pid = -1;
3616 #else
3617         // tmp_ret will be located (usually) in /tmp
3618         // will that be a problem?
3619         // Note that this calls ForkedCalls::fork(), so it's
3620         // ok cross-platform.
3621         pid_t const pid = fork();
3622         // If you want to debug the autosave
3623         // you should set pid to -1, and comment out the fork.
3624         if (pid != 0 && pid != -1)
3625                 return pid;
3626 #endif
3627
3628         // pid = -1 signifies that lyx was unable
3629         // to fork. But we will do the save
3630         // anyway.
3631         bool failed = false;
3632         FileName const tmp_ret = FileName::tempName("lyxauto");
3633         if (!tmp_ret.empty()) {
3634                 buffer_.writeFile(tmp_ret);
3635                 // assume successful write of tmp_ret
3636                 if (!tmp_ret.moveTo(fname_))
3637                         failed = true;
3638         } else
3639                 failed = true;
3640
3641         if (failed) {
3642                 // failed to write/rename tmp_ret so try writing direct
3643                 if (!buffer_.writeFile(fname_)) {
3644                         // It is dangerous to do this in the child,
3645                         // but safe in the parent, so...
3646                         if (pid == -1) // emit message signal.
3647                                 buffer_.message(_("Autosave failed!"));
3648                 }
3649         }
3650
3651         if (pid == 0) // we are the child so...
3652                 _exit(0);
3653
3654         return pid;
3655 }
3656
3657 } // namespace anon
3658
3659
3660 FileName Buffer::getEmergencyFileName() const
3661 {
3662         return FileName(d->filename.absFileName() + ".emergency");
3663 }
3664
3665
3666 FileName Buffer::getAutosaveFileName() const
3667 {
3668         // if the document is unnamed try to save in the backup dir, else
3669         // in the default document path, and as a last try in the filePath,
3670         // which will most often be the temporary directory
3671         string fpath;
3672         if (isUnnamed())
3673                 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3674                         : lyxrc.backupdir_path;
3675         if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3676                 fpath = filePath();
3677
3678         string const fname = "#" + d->filename.onlyFileName() + "#";
3679
3680         return makeAbsPath(fname, fpath);
3681 }
3682
3683
3684 void Buffer::removeAutosaveFile() const
3685 {
3686         FileName const f = getAutosaveFileName();
3687         if (f.exists())
3688                 f.removeFile();
3689 }
3690
3691
3692 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3693 {
3694         FileName const newauto = getAutosaveFileName();
3695         oldauto.refresh();
3696         if (newauto != oldauto && oldauto.exists())
3697                 if (!oldauto.moveTo(newauto))
3698                         LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3699 }
3700
3701
3702 bool Buffer::autoSave() const
3703 {
3704         Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3705         if (buf->d->bak_clean || isReadonly())
3706                 return true;
3707
3708         message(_("Autosaving current document..."));
3709         buf->d->bak_clean = true;
3710
3711         FileName const fname = getAutosaveFileName();
3712         LASSERT(d->cloned_buffer_, return false);
3713
3714         // If this buffer is cloned, we assume that
3715         // we are running in a separate thread already.
3716         FileName const tmp_ret = FileName::tempName("lyxauto");
3717         if (!tmp_ret.empty()) {
3718                 writeFile(tmp_ret);
3719                 // assume successful write of tmp_ret
3720                 if (tmp_ret.moveTo(fname))
3721                         return true;
3722         }
3723         // failed to write/rename tmp_ret so try writing direct
3724         return writeFile(fname);
3725 }
3726
3727
3728 void Buffer::setExportStatus(bool e) const
3729 {
3730         d->doing_export = e;
3731         ListOfBuffers clist = getDescendents();
3732         ListOfBuffers::const_iterator cit = clist.begin();
3733         ListOfBuffers::const_iterator const cen = clist.end();
3734         for (; cit != cen; ++cit)
3735                 (*cit)->d->doing_export = e;
3736 }
3737
3738
3739 bool Buffer::isExporting() const
3740 {
3741         return d->doing_export;
3742 }
3743
3744
3745 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
3746         const
3747 {
3748         string result_file;
3749         return doExport(target, put_in_tempdir, result_file);
3750 }
3751
3752 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3753         string & result_file) const
3754 {
3755         bool const update_unincluded =
3756                         params().maintain_unincluded_children
3757                         && !params().getIncludedChildren().empty();
3758
3759         // (1) export with all included children (omit \includeonly)
3760         if (update_unincluded) {
3761                 ExportStatus const status =
3762                         doExport(target, put_in_tempdir, true, result_file);
3763                 if (status != ExportSuccess)
3764                         return status;
3765         }
3766         // (2) export with included children only
3767         return doExport(target, put_in_tempdir, false, result_file);
3768 }
3769
3770
3771 void Buffer::setMathFlavor(OutputParams & op) const
3772 {
3773         switch (params().html_math_output) {
3774         case BufferParams::MathML:
3775                 op.math_flavor = OutputParams::MathAsMathML;
3776                 break;
3777         case BufferParams::HTML:
3778                 op.math_flavor = OutputParams::MathAsHTML;
3779                 break;
3780         case BufferParams::Images:
3781                 op.math_flavor = OutputParams::MathAsImages;
3782                 break;
3783         case BufferParams::LaTeX:
3784                 op.math_flavor = OutputParams::MathAsLaTeX;
3785                 break;
3786         }
3787 }
3788
3789
3790 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3791         bool includeall, string & result_file) const
3792 {
3793         LYXERR(Debug::FILES, "target=" << target);
3794         OutputParams runparams(&params().encoding());
3795         string format = target;
3796         string dest_filename;
3797         size_t pos = target.find(' ');
3798         if (pos != string::npos) {
3799                 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
3800                 format = target.substr(0, pos);
3801                 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
3802                 FileName(dest_filename).onlyPath().createPath();
3803                 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
3804         }
3805         MarkAsExporting exporting(this);
3806         string backend_format;
3807         runparams.flavor = OutputParams::LATEX;
3808         runparams.linelen = lyxrc.plaintext_linelen;
3809         runparams.includeall = includeall;
3810         vector<string> backs = params().backends();
3811         Converters converters = theConverters();
3812         bool need_nice_file = false;
3813         if (find(backs.begin(), backs.end(), format) == backs.end()) {
3814                 // Get shortest path to format
3815                 converters.buildGraph();
3816                 Graph::EdgePath path;
3817                 for (vector<string>::const_iterator it = backs.begin();
3818                      it != backs.end(); ++it) {
3819                         Graph::EdgePath p = converters.getPath(*it, format);
3820                         if (!p.empty() && (path.empty() || p.size() < path.size())) {
3821                                 backend_format = *it;
3822                                 path = p;
3823                         }
3824                 }
3825                 if (path.empty()) {
3826                         if (!put_in_tempdir) {
3827                                 // Only show this alert if this is an export to a non-temporary
3828                                 // file (not for previewing).
3829                                 Alert::error(_("Couldn't export file"), bformat(
3830                                         _("No information for exporting the format %1$s."),
3831                                         formats.prettyName(format)));
3832                         }
3833                         return ExportNoPathToFormat;
3834                 }
3835                 runparams.flavor = converters.getFlavor(path, this);
3836                 Graph::EdgePath::const_iterator it = path.begin();
3837                 Graph::EdgePath::const_iterator en = path.end();
3838                 for (; it != en; ++it)
3839                         if (theConverters().get(*it).nice) {
3840                                 need_nice_file = true;
3841                                 break;
3842                         }
3843
3844         } else {
3845                 backend_format = format;
3846                 LYXERR(Debug::FILES, "backend_format=" << backend_format);
3847                 // FIXME: Don't hardcode format names here, but use a flag
3848                 if (backend_format == "pdflatex")
3849                         runparams.flavor = OutputParams::PDFLATEX;
3850                 else if (backend_format == "luatex")
3851                         runparams.flavor = OutputParams::LUATEX;
3852                 else if (backend_format == "dviluatex")
3853                         runparams.flavor = OutputParams::DVILUATEX;
3854                 else if (backend_format == "xetex")
3855                         runparams.flavor = OutputParams::XETEX;
3856         }
3857
3858         string filename = latexName(false);
3859         filename = addName(temppath(), filename);
3860         filename = changeExtension(filename,
3861                                    formats.extension(backend_format));
3862         LYXERR(Debug::FILES, "filename=" << filename);
3863
3864         // Plain text backend
3865         if (backend_format == "text") {
3866                 runparams.flavor = OutputParams::TEXT;
3867                 writePlaintextFile(*this, FileName(filename), runparams);
3868         }
3869         // HTML backend
3870         else if (backend_format == "xhtml") {
3871                 runparams.flavor = OutputParams::HTML;
3872                 setMathFlavor(runparams);
3873                 makeLyXHTMLFile(FileName(filename), runparams);
3874         } else if (backend_format == "lyx")
3875                 writeFile(FileName(filename));
3876         // Docbook backend
3877         else if (params().isDocBook()) {
3878                 runparams.nice = !put_in_tempdir;
3879                 makeDocBookFile(FileName(filename), runparams);
3880         }
3881         // LaTeX backend
3882         else if (backend_format == format || need_nice_file) {
3883                 runparams.nice = true;
3884                 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
3885                 if (d->cloned_buffer_)
3886                         d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
3887                 if (!success)
3888                         return ExportError;
3889         } else if (!lyxrc.tex_allows_spaces
3890                    && contains(filePath(), ' ')) {
3891                 Alert::error(_("File name error"),
3892                            _("The directory path to the document cannot contain spaces."));
3893                 return ExportTexPathHasSpaces;
3894         } else {
3895                 runparams.nice = false;
3896                 bool const success = makeLaTeXFile(
3897                         FileName(filename), filePath(), runparams);
3898                 if (d->cloned_buffer_)
3899                         d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
3900                 if (!success)
3901                         return ExportError;
3902         }
3903
3904         string const error_type = (format == "program")
3905                 ? "Build" : params().bufferFormat();
3906         ErrorList & error_list = d->errorLists[error_type];
3907         string const ext = formats.extension(format);
3908         FileName const tmp_result_file(changeExtension(filename, ext));
3909         bool const success = converters.convert(this, FileName(filename),
3910                 tmp_result_file, FileName(absFileName()), backend_format, format,
3911                 error_list);
3912
3913         // Emit the signal to show the error list or copy it back to the
3914         // cloned Buffer so that it can be emitted afterwards.
3915         if (format != backend_format) {
3916                 if (d->cloned_buffer_) {
3917                         d->cloned_buffer_->d->errorLists[error_type] =
3918                                 d->errorLists[error_type];
3919                 } else
3920                         errors(error_type);
3921                 // also to the children, in case of master-buffer-view
3922                 ListOfBuffers clist = getDescendents();
3923                 ListOfBuffers::const_iterator cit = clist.begin();
3924                 ListOfBuffers::const_iterator const cen = clist.end();
3925                 for (; cit != cen; ++cit) {
3926                         if (d->cloned_buffer_) {
3927                                 // Enable reverse search by copying back the
3928                                 // texrow object to the cloned buffer.
3929                                 // FIXME: this is not thread safe.
3930                                 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
3931                                 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
3932                                         (*cit)->d->errorLists[error_type];
3933                         } else
3934                                 (*cit)->errors(error_type, true);
3935                 }
3936         }
3937
3938         if (d->cloned_buffer_) {
3939                 // Enable reverse dvi or pdf to work by copying back the texrow
3940                 // object to the cloned buffer.
3941                 // FIXME: There is a possibility of concurrent access to texrow
3942                 // here from the main GUI thread that should be securized.
3943                 d->cloned_buffer_->d->texrow = d->texrow;
3944                 string const error_type = params().bufferFormat();
3945                 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
3946         }
3947
3948         if (!success)
3949                 return ExportConverterError;
3950
3951         if (put_in_tempdir) {
3952                 result_file = tmp_result_file.absFileName();
3953                 return ExportSuccess;
3954         }
3955
3956         if (dest_filename.empty())
3957                 result_file = changeExtension(d->exportFileName().absFileName(), ext);
3958         else
3959                 result_file = dest_filename;
3960         // We need to copy referenced files (e. g. included graphics
3961         // if format == "dvi") to the result dir.
3962         vector<ExportedFile> const files =
3963                 runparams.exportdata->externalFiles(format);
3964         string const dest = runparams.export_folder.empty() ?
3965                 onlyPath(result_file) : runparams.export_folder;
3966         bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
3967                                  : force_overwrite == ALL_FILES;
3968         CopyStatus status = use_force ? FORCE : SUCCESS;
3969
3970         vector<ExportedFile>::const_iterator it = files.begin();
3971         vector<ExportedFile>::const_iterator const en = files.end();
3972         for (; it != en && status != CANCEL; ++it) {
3973                 string const fmt = formats.getFormatFromFile(it->sourceName);
3974                 string fixedName = it->exportName;
3975                 if (!runparams.export_folder.empty()) {
3976                         // Relative pathnames starting with ../ will be sanitized
3977                         // if exporting to a different folder
3978                         while (fixedName.substr(0, 3) == "../")
3979                                 fixedName = fixedName.substr(3, fixedName.length() - 3);
3980                 }
3981                 FileName fixedFileName = makeAbsPath(fixedName, dest);
3982                 fixedFileName.onlyPath().createPath();
3983                 status = copyFile(fmt, it->sourceName,
3984                         fixedFileName,
3985                         it->exportName, status == FORCE,
3986                         runparams.export_folder.empty());
3987         }
3988
3989         if (status == CANCEL) {
3990                 message(_("Document export cancelled."));
3991                 return ExportCancel;
3992         }
3993
3994         if (tmp_result_file.exists()) {
3995                 // Finally copy the main file
3996                 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
3997                                     : force_overwrite != NO_FILES;
3998                 if (status == SUCCESS && use_force)
3999                         status = FORCE;
4000                 status = copyFile(format, tmp_result_file,
4001                         FileName(result_file), result_file,
4002                         status == FORCE);
4003                 if (status == CANCEL) {
4004                         message(_("Document export cancelled."));
4005                         return ExportCancel;
4006                 } else {
4007                         message(bformat(_("Document exported as %1$s "
4008                                 "to file `%2$s'"),
4009                                 formats.prettyName(format),
4010                                 makeDisplayPath(result_file)));
4011                 }
4012         } else {
4013                 // This must be a dummy converter like fax (bug 1888)
4014                 message(bformat(_("Document exported as %1$s"),
4015                         formats.prettyName(format)));
4016         }
4017
4018         return ExportSuccess;
4019 }
4020
4021
4022 Buffer::ExportStatus Buffer::preview(string const & format) const
4023 {
4024         bool const update_unincluded =
4025                         params().maintain_unincluded_children
4026                         && !params().getIncludedChildren().empty();
4027         return preview(format, update_unincluded);
4028 }
4029
4030 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4031 {
4032         MarkAsExporting exporting(this);
4033         string result_file;
4034         // (1) export with all included children (omit \includeonly)
4035         if (includeall) {
4036                 ExportStatus const status = doExport(format, true, true, result_file);
4037                 if (status != ExportSuccess)
4038                         return status;
4039         }
4040         // (2) export with included children only
4041         ExportStatus const status = doExport(format, true, false, result_file);
4042         if (status != ExportSuccess)
4043                 return status;
4044         if (!formats.view(*this, FileName(result_file), format))
4045                 return PreviewError;
4046         return PreviewSuccess;
4047 }
4048
4049
4050 Buffer::ReadStatus Buffer::extractFromVC()
4051 {
4052         bool const found = LyXVC::file_not_found_hook(d->filename);
4053         if (!found)
4054                 return ReadFileNotFound;
4055         if (!d->filename.isReadableFile())
4056                 return ReadVCError;
4057         return ReadSuccess;
4058 }
4059
4060
4061 Buffer::ReadStatus Buffer::loadEmergency()
4062 {
4063         FileName const emergencyFile = getEmergencyFileName();
4064         if (!emergencyFile.exists()
4065                   || emergencyFile.lastModified() <= d->filename.lastModified())
4066                 return ReadFileNotFound;
4067
4068         docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4069         docstring const text = bformat(_("An emergency save of the document "
4070                 "%1$s exists.\n\nRecover emergency save?"), file);
4071
4072         int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4073                 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4074
4075         switch (load_emerg)
4076         {
4077         case 0: {
4078                 docstring str;
4079                 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4080                 bool const success = (ret_llf == ReadSuccess);
4081                 if (success) {
4082                         if (isReadonly()) {
4083                                 Alert::warning(_("File is read-only"),
4084                                         bformat(_("An emergency file is successfully loaded, "
4085                                         "but the original file %1$s is marked read-only. "
4086                                         "Please make sure to save the document as a different "
4087                                         "file."), from_utf8(d->filename.absFileName())));
4088                         }
4089                         markDirty();
4090                         lyxvc().file_found_hook(d->filename);
4091                         str = _("Document was successfully recovered.");
4092                 } else
4093                         str = _("Document was NOT successfully recovered.");
4094                 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4095                         makeDisplayPath(emergencyFile.absFileName()));
4096
4097                 int const del_emerg =
4098                         Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4099                                 _("&Remove"), _("&Keep"));
4100                 if (del_emerg == 0) {
4101                         emergencyFile.removeFile();
4102                         if (success)
4103                                 Alert::warning(_("Emergency file deleted"),
4104                                         _("Do not forget to save your file now!"), true);
4105                         }
4106                 return success ? ReadSuccess : ReadEmergencyFailure;
4107         }
4108         case 1: {
4109                 int const del_emerg =
4110                         Alert::prompt(_("Delete emergency file?"),
4111                                 _("Remove emergency file now?"), 1, 1,
4112                                 _("&Remove"), _("&Keep"));
4113                 if (del_emerg == 0)
4114                         emergencyFile.removeFile();
4115                 return ReadOriginal;
4116         }
4117
4118         default:
4119                 break;
4120         }
4121         return ReadCancel;
4122 }
4123
4124
4125 Buffer::ReadStatus Buffer::loadAutosave()
4126 {
4127         // Now check if autosave file is newer.
4128         FileName const autosaveFile = getAutosaveFileName();
4129         if (!autosaveFile.exists()
4130                   || autosaveFile.lastModified() <= d->filename.lastModified())
4131                 return ReadFileNotFound;
4132
4133         docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4134         docstring const text = bformat(_("The backup of the document %1$s "
4135                 "is newer.\n\nLoad the backup instead?"), file);
4136         int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4137                 _("&Load backup"), _("Load &original"), _("&Cancel"));
4138
4139         switch (ret)
4140         {
4141         case 0: {
4142                 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4143                 // the file is not saved if we load the autosave file.
4144                 if (ret_llf == ReadSuccess) {
4145                         if (isReadonly()) {
4146                                 Alert::warning(_("File is read-only"),
4147                                         bformat(_("A backup file is successfully loaded, "
4148                                         "but the original file %1$s is marked read-only. "
4149                                         "Please make sure to save the document as a "
4150                                         "different file."),
4151                                         from_utf8(d->filename.absFileName())));
4152                         }
4153                         markDirty();
4154                         lyxvc().file_found_hook(d->filename);
4155                         return ReadSuccess;
4156                 }
4157                 return ReadAutosaveFailure;
4158         }
4159         case 1:
4160                 // Here we delete the autosave
4161                 autosaveFile.removeFile();
4162                 return ReadOriginal;
4163         default:
4164                 break;
4165         }
4166         return ReadCancel;
4167 }
4168
4169
4170 Buffer::ReadStatus Buffer::loadLyXFile()
4171 {
4172         if (!d->filename.isReadableFile()) {
4173                 ReadStatus const ret_rvc = extractFromVC();
4174                 if (ret_rvc != ReadSuccess)
4175                         return ret_rvc;
4176         }
4177
4178         ReadStatus const ret_re = loadEmergency();
4179         if (ret_re == ReadSuccess || ret_re == ReadCancel)
4180                 return ret_re;
4181
4182         ReadStatus const ret_ra = loadAutosave();
4183         if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4184                 return ret_ra;
4185
4186         return loadThisLyXFile(d->filename);
4187 }
4188
4189
4190 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4191 {
4192         return readFile(fn);
4193 }
4194
4195
4196 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4197 {
4198         TeXErrors::Errors::const_iterator it = terr.begin();
4199         TeXErrors::Errors::const_iterator end = terr.end();
4200         ListOfBuffers clist = getDescendents();
4201         ListOfBuffers::const_iterator cen = clist.end();
4202
4203         for (; it != end; ++it) {
4204                 int id_start = -1;
4205                 int pos_start = -1;
4206                 int errorRow = it->error_in_line;
4207                 Buffer const * buf = 0;
4208                 Impl const * p = d;
4209                 if (it->child_name.empty())
4210                     p->texrow.getIdFromRow(errorRow, id_start, pos_start);
4211                 else {
4212                         // The error occurred in a child
4213                         ListOfBuffers::const_iterator cit = clist.begin();
4214                         for (; cit != cen; ++cit) {
4215                                 string const child_name =
4216                                         DocFileName(changeExtension(
4217                                                 (*cit)->absFileName(), "tex")).
4218                                                         mangledFileName();
4219                                 if (it->child_name != child_name)
4220                                         continue;
4221                                 (*cit)->d->texrow.getIdFromRow(errorRow,
4222                                                         id_start, pos_start);
4223                                 if (id_start != -1) {
4224                                         buf = d->cloned_buffer_
4225                                                 ? (*cit)->d->cloned_buffer_->d->owner_
4226                                                 : (*cit)->d->owner_;
4227                                         p = (*cit)->d;
4228                                         break;
4229                                 }
4230                         }
4231                 }
4232                 int id_end = -1;
4233                 int pos_end = -1;
4234                 bool found;
4235                 do {
4236                         ++errorRow;
4237                         found = p->texrow.getIdFromRow(errorRow, id_end, pos_end);
4238                 } while (found && id_start == id_end && pos_start == pos_end);
4239
4240                 if (id_start != id_end) {
4241                         // Next registered position is outside the inset where
4242                         // the error occurred, so signal end-of-paragraph
4243                         pos_end = 0;
4244                 }
4245
4246                 errorList.push_back(ErrorItem(it->error_desc,
4247                         it->error_text, id_start, pos_start, pos_end, buf));
4248         }
4249 }
4250
4251
4252 void Buffer::setBuffersForInsets() const
4253 {
4254         inset().setBuffer(const_cast<Buffer &>(*this));
4255 }
4256
4257
4258 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4259 {
4260         // Use the master text class also for child documents
4261         Buffer const * const master = masterBuffer();
4262         DocumentClass const & textclass = master->params().documentClass();
4263
4264         // do this only if we are the top-level Buffer
4265         if (master == this)
4266                 reloadBibInfoCache();
4267
4268         // keep the buffers to be children in this set. If the call from the
4269         // master comes back we can see which of them were actually seen (i.e.
4270         // via an InsetInclude). The remaining ones in the set need still be updated.
4271         static std::set<Buffer const *> bufToUpdate;
4272         if (scope == UpdateMaster) {
4273                 // If this is a child document start with the master
4274                 if (master != this) {
4275                         bufToUpdate.insert(this);
4276                         master->updateBuffer(UpdateMaster, utype);
4277                         // Do this here in case the master has no gui associated with it. Then,
4278                         // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
4279                         if (!master->d->gui_)
4280                                 structureChanged();
4281
4282                         // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4283                         if (bufToUpdate.find(this) == bufToUpdate.end())
4284                                 return;
4285                 }
4286
4287                 // start over the counters in the master
4288                 textclass.counters().reset();
4289         }
4290
4291         // update will be done below for this buffer
4292         bufToUpdate.erase(this);
4293
4294         // update all caches
4295         clearReferenceCache();
4296         updateMacros();
4297
4298         Buffer & cbuf = const_cast<Buffer &>(*this);
4299
4300         LASSERT(!text().paragraphs().empty(), /**/);
4301
4302         // do the real work
4303         ParIterator parit = cbuf.par_iterator_begin();
4304         updateBuffer(parit, utype);
4305
4306         if (master != this)
4307                 // TocBackend update will be done later.
4308                 return;
4309
4310         d->bibinfo_cache_valid_ = true;
4311         d->cite_labels_valid_ = true;
4312         cbuf.tocBackend().update(utype == OutputUpdate);
4313         if (scope == UpdateMaster)
4314                 cbuf.structureChanged();
4315 }
4316
4317
4318 static depth_type getDepth(DocIterator const & it)
4319 {
4320         depth_type depth = 0;
4321         for (size_t i = 0 ; i < it.depth() ; ++i)
4322                 if (!it[i].inset().inMathed())
4323                         depth += it[i].paragraph().getDepth() + 1;
4324         // remove 1 since the outer inset does not count
4325         return depth - 1;
4326 }
4327
4328 static depth_type getItemDepth(ParIterator const & it)
4329 {
4330         Paragraph const & par = *it;
4331         LabelType const labeltype = par.layout().labeltype;
4332
4333         if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4334                 return 0;
4335
4336         // this will hold the lowest depth encountered up to now.
4337         depth_type min_depth = getDepth(it);
4338         ParIterator prev_it = it;
4339         while (true) {
4340                 if (prev_it.pit())
4341                         --prev_it.top().pit();
4342                 else {
4343                         // start of nested inset: go to outer par
4344                         prev_it.pop_back();
4345                         if (prev_it.empty()) {
4346                                 // start of document: nothing to do
4347                                 return 0;
4348                         }
4349                 }
4350
4351                 // We search for the first paragraph with same label
4352                 // that is not more deeply nested.
4353                 Paragraph & prev_par = *prev_it;
4354                 depth_type const prev_depth = getDepth(prev_it);
4355                 if (labeltype == prev_par.layout().labeltype) {
4356                         if (prev_depth < min_depth)
4357                                 return prev_par.itemdepth + 1;
4358                         if (prev_depth == min_depth)
4359                                 return prev_par.itemdepth;
4360                 }
4361                 min_depth = min(min_depth, prev_depth);
4362                 // small optimization: if we are at depth 0, we won't
4363                 // find anything else
4364                 if (prev_depth == 0)
4365                         return 0;
4366         }
4367 }
4368
4369
4370 static bool needEnumCounterReset(ParIterator const & it)
4371 {
4372         Paragraph const & par = *it;
4373         LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
4374         depth_type const cur_depth = par.getDepth();
4375         ParIterator prev_it = it;
4376         while (prev_it.pit()) {
4377                 --prev_it.top().pit();
4378                 Paragraph const & prev_par = *prev_it;
4379                 if (prev_par.getDepth() <= cur_depth)
4380                         return  prev_par.layout().labeltype != LABEL_ENUMERATE;
4381         }
4382         // start of nested inset: reset
4383         return true;
4384 }
4385
4386
4387 // set the label of a paragraph. This includes the counters.
4388 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4389 {
4390         BufferParams const & bp = owner_->masterBuffer()->params();
4391         DocumentClass const & textclass = bp.documentClass();
4392         Paragraph & par = it.paragraph();
4393         Layout const & layout = par.layout();
4394         Counters & counters = textclass.counters();
4395
4396         if (par.params().startOfAppendix()) {
4397                 // We want to reset the counter corresponding to toplevel sectioning
4398                 Layout const & lay = textclass.getTOCLayout();
4399                 docstring const cnt = lay.counter;
4400                 if (!cnt.empty())
4401                         counters.reset(cnt);
4402                 counters.appendix(true);
4403         }
4404         par.params().appendix(counters.appendix());
4405
4406         // Compute the item depth of the paragraph
4407         par.itemdepth = getItemDepth(it);
4408
4409         if (layout.margintype == MARGIN_MANUAL) {
4410                 if (par.params().labelWidthString().empty())
4411                         par.params().labelWidthString(par.expandLabel(layout, bp));
4412         } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4413                 // we do not need to do anything here, since the empty case is
4414                 // handled during export.
4415         } else {
4416                 par.params().labelWidthString(docstring());
4417         }
4418
4419         switch(layout.labeltype) {
4420         case LABEL_ITEMIZE: {
4421                 // At some point of time we should do something more
4422                 // clever here, like:
4423                 //   par.params().labelString(
4424                 //    bp.user_defined_bullet(par.itemdepth).getText());
4425                 // for now, use a simple hardcoded label
4426                 docstring itemlabel;
4427                 switch (par.itemdepth) {
4428                 case 0:
4429                         itemlabel = char_type(0x2022);
4430                         break;
4431                 case 1:
4432                         itemlabel = char_type(0x2013);
4433                         break;
4434                 case 2:
4435                         itemlabel = char_type(0x2217);
4436                         break;
4437                 case 3:
4438                         itemlabel = char_type(0x2219); // or 0x00b7
4439                         break;
4440                 }
4441                 par.params().labelString(itemlabel);
4442                 break;
4443         }
4444
4445         case LABEL_ENUMERATE: {
4446                 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4447
4448                 switch (par.itemdepth) {
4449                 case 2:
4450                         enumcounter += 'i';
4451                 case 1:
4452                         enumcounter += 'i';
4453                 case 0:
4454                         enumcounter += 'i';
4455                         break;
4456                 case 3:
4457                         enumcounter += "iv";
4458                         break;
4459                 default:
4460                         // not a valid enumdepth...
4461                         break;
4462                 }
4463
4464                 // Maybe we have to reset the enumeration counter.
4465                 if (needEnumCounterReset(it))
4466                         counters.reset(enumcounter);
4467                 counters.step(enumcounter, utype);
4468
4469                 string const & lang = par.getParLanguage(bp)->code();
4470                 par.params().labelString(counters.theCounter(enumcounter, lang));
4471
4472                 break;
4473         }
4474
4475         case LABEL_SENSITIVE: {
4476                 string const & type = counters.current_float();
4477                 docstring full_label;
4478                 if (type.empty())
4479                         full_label = owner_->B_("Senseless!!! ");
4480                 else {
4481                         docstring name = owner_->B_(textclass.floats().getType(type).name());
4482                         if (counters.hasCounter(from_utf8(type))) {
4483                                 string const & lang = par.getParLanguage(bp)->code();
4484                                 counters.step(from_utf8(type), utype);
4485                                 full_label = bformat(from_ascii("%1$s %2$s:"),
4486                                                      name,
4487                                                      counters.theCounter(from_utf8(type), lang));
4488                         } else
4489                                 full_label = bformat(from_ascii("%1$s #:"), name);
4490                 }
4491                 par.params().labelString(full_label);
4492                 break;
4493         }
4494
4495         case LABEL_NO_LABEL:
4496                 par.params().labelString(docstring());
4497                 break;
4498
4499         case LABEL_ABOVE:
4500         case LABEL_CENTERED:
4501         case LABEL_STATIC: {
4502                 docstring const & lcounter = layout.counter;
4503                 if (!lcounter.empty()) {
4504                         if (layout.toclevel <= bp.secnumdepth
4505                                                 && (layout.latextype != LATEX_ENVIRONMENT
4506                                         || it.text()->isFirstInSequence(it.pit()))) {
4507                                 if (counters.hasCounter(lcounter))
4508                                         counters.step(lcounter, utype);
4509                                 par.params().labelString(par.expandLabel(layout, bp));
4510                         } else
4511                                 par.params().labelString(docstring());
4512                 } else
4513                         par.params().labelString(par.expandLabel(layout, bp));
4514                 break;
4515         }
4516
4517         case LABEL_MANUAL:
4518         case LABEL_BIBLIO:
4519                 par.params().labelString(par.expandLabel(layout, bp));
4520         }
4521 }
4522
4523
4524 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4525 {
4526         LASSERT(parit.pit() == 0, /**/);
4527
4528         // Set the position of the text in the buffer to be able
4529         // to resolve macros in it.
4530         parit.text()->setMacrocontextPosition(parit);
4531
4532         depth_type maxdepth = 0;
4533         pit_type const lastpit = parit.lastpit();
4534         for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4535                 // reduce depth if necessary
4536                 if (parit->params().depth() > maxdepth) {
4537                         /** FIXME: this function is const, but
4538                          * nevertheless it modifies the buffer. To be
4539                          * cleaner, one should modify the buffer in
4540                          * another function, which is actually
4541                          * non-const. This would however be costly in
4542                          * terms of code duplication.
4543                          */
4544                         const_cast<Buffer *>(this)->undo().recordUndo(CursorData(parit));
4545                         parit->params().depth(maxdepth);
4546                 }
4547                 maxdepth = parit->getMaxDepthAfter();
4548
4549                 if (utype == OutputUpdate) {
4550                         // track the active counters
4551                         // we have to do this for the master buffer, since the local
4552                         // buffer isn't tracking anything.
4553                         masterBuffer()->params().documentClass().counters().
4554                                         setActiveLayout(parit->layout());
4555                 }
4556
4557                 // set the counter for this paragraph
4558                 d->setLabel(parit, utype);
4559
4560                 // now the insets
4561                 InsetList::const_iterator iit = parit->insetList().begin();
4562                 InsetList::const_iterator end = parit->insetList().end();
4563                 for (; iit != end; ++iit) {
4564                         parit.pos() = iit->pos;
4565                         iit->inset->updateBuffer(parit, utype);
4566                 }
4567         }
4568 }
4569
4570
4571 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4572         WordLangTuple & word_lang, docstring_list & suggestions) const
4573 {
4574         int progress = 0;
4575         WordLangTuple wl;
4576         suggestions.clear();
4577         word_lang = WordLangTuple();
4578         bool const to_end = to.empty();
4579         DocIterator const end = to_end ? doc_iterator_end(this) : to;
4580         // OK, we start from here.
4581         for (; from != end; from.forwardPos()) {
4582                 // We are only interested in text so remove the math CursorSlice.
4583                 while (from.inMathed()) {
4584                         from.pop_back();
4585                         from.pos()++;
4586                 }
4587                 // If from is at the end of the document (which is possible
4588                 // when leaving the mathed) LyX will crash later otherwise.
4589                 if (from.atEnd() || (!to_end && from >= end))
4590                         break;
4591                 to = from;
4592                 from.paragraph().spellCheck();
4593                 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4594                 if (SpellChecker::misspelled(res)) {
4595                         word_lang = wl;
4596                         break;
4597                 }
4598
4599                 // Do not increase progress when from == to, otherwise the word
4600                 // count will be wrong.
4601                 if (from != to) {
4602                         from = to;
4603                         ++progress;
4604                 }
4605         }
4606         return progress;
4607 }
4608
4609
4610 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
4611 {
4612         bool inword = false;
4613         word_count_ = 0;
4614         char_count_ = 0;
4615         blank_count_ = 0;
4616  
4617         for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
4618                 if (!dit.inTexted()) {
4619                         dit.forwardPos();
4620                         continue;
4621                 }
4622                 
4623                 Paragraph const & par = dit.paragraph();
4624                 pos_type const pos = dit.pos();
4625                 
4626                 // Copied and adapted from isWordSeparator() in Paragraph
4627                 if (pos == dit.lastpos()) {
4628                         inword = false;
4629                 } else {
4630                         Inset const * ins = par.getInset(pos);
4631                         if (ins && skipNoOutput && !ins->producesOutput()) {
4632                                 // skip this inset
4633                                 ++dit.top().pos();
4634                                 // stop if end of range was skipped
4635                                 if (!to.atEnd() && dit >= to)
4636                                         break;
4637                                 continue;
4638                         } else if (!par.isDeleted(pos)) {
4639                                 if (par.isWordSeparator(pos)) 
4640                                         inword = false;
4641                                 else if (!inword) {
4642                                         ++word_count_;
4643                                         inword = true;
4644                                 }
4645                                 if (ins && ins->isLetter())
4646                                         ++char_count_;
4647                                 else if (ins && ins->isSpace())
4648                                         ++blank_count_;
4649                                 else {
4650                                         char_type const c = par.getChar(pos);
4651                                         if (isPrintableNonspace(c))
4652                                                 ++char_count_;
4653                                         else if (isSpace(c))
4654                                                 ++blank_count_;
4655                                 }
4656                         }
4657                 }
4658                 dit.forwardPos();
4659         }
4660 }
4661
4662
4663 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
4664 {
4665         d->updateStatistics(from, to, skipNoOutput);
4666 }
4667
4668
4669 int Buffer::wordCount() const
4670 {
4671         return d->wordCount();
4672 }
4673
4674
4675 int Buffer::charCount(bool with_blanks) const
4676 {
4677         return d->charCount(with_blanks);
4678 }
4679
4680
4681 Buffer::ReadStatus Buffer::reload(bool clearUndo)
4682 {
4683         setBusy(true);
4684         // c.f. bug http://www.lyx.org/trac/ticket/6587
4685         removeAutosaveFile();
4686         // e.g., read-only status could have changed due to version control
4687         d->filename.refresh();
4688         docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4689
4690         // clear parent. this will get reset if need be.
4691         d->setParent(0);
4692         ReadStatus const status = loadLyXFile();
4693         if (status == ReadSuccess) {
4694                 updateBuffer();
4695                 changed(true);
4696                 updateTitles();
4697                 markClean();
4698                 message(bformat(_("Document %1$s reloaded."), disp_fn));
4699                 if (clearUndo)
4700                         d->undo_.clear();
4701         } else {
4702                 message(bformat(_("Could not reload document %1$s."), disp_fn));
4703         }
4704         setBusy(false);
4705         removePreviews();
4706         updatePreviews();
4707         errors("Parse");
4708         return status;
4709 }
4710
4711
4712 bool Buffer::saveAs(FileName const & fn)
4713 {
4714         FileName const old_name = fileName();
4715         FileName const old_auto = getAutosaveFileName();
4716         bool const old_unnamed = isUnnamed();
4717
4718         setFileName(fn);
4719         markDirty();
4720         setUnnamed(false);
4721
4722         if (save()) {
4723                 // bring the autosave file with us, just in case.
4724                 moveAutosaveFile(old_auto);
4725                 // validate version control data and
4726                 // correct buffer title
4727                 lyxvc().file_found_hook(fileName());
4728                 updateTitles();
4729                 // the file has now been saved to the new location.
4730                 // we need to check that the locations of child buffers
4731                 // are still valid.
4732                 checkChildBuffers();
4733                 checkMasterBuffer();
4734                 return true;
4735         } else {
4736                 // save failed
4737                 // reset the old filename and unnamed state
4738                 setFileName(old_name);
4739                 setUnnamed(old_unnamed);
4740                 return false;
4741         }
4742 }
4743
4744
4745 // FIXME We could do better here, but it is complicated. What would be
4746 // nice is to offer either (a) to save the child buffer to an appropriate
4747 // location, so that it would "move with the master", or else (b) to update
4748 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4749 // complicated, because the code for this lives in GuiView.
4750 void Buffer::checkChildBuffers()
4751 {
4752         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4753         Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4754         for (; it != en; ++it) {
4755                 DocIterator dit = it->second;
4756                 Buffer * cbuf = const_cast<Buffer *>(it->first);
4757                 if (!cbuf || !theBufferList().isLoaded(cbuf))
4758                         continue;
4759                 Inset * inset = dit.nextInset();
4760                 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4761                 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4762                 docstring const & incfile = inset_inc->getParam("filename");
4763                 string oldloc = cbuf->absFileName();
4764                 string newloc = makeAbsPath(to_utf8(incfile),
4765                                 onlyPath(absFileName())).absFileName();
4766                 if (oldloc == newloc)
4767                         continue;
4768                 // the location of the child file is incorrect.
4769                 Alert::warning(_("Included File Invalid"),
4770                                 bformat(_("Saving this document to a new location has made the file:\n"
4771                                 "  %1$s\n"
4772                                 "inaccessible. You will need to update the included filename."),
4773                                 from_utf8(oldloc)));
4774                 cbuf->setParent(0);
4775                 inset_inc->setChildBuffer(0);
4776         }
4777         // invalidate cache of children
4778         d->children_positions.clear();
4779         d->position_to_children.clear();
4780 }
4781
4782
4783 // If a child has been saved under a different name/path, it might have been
4784 // orphaned. Therefore the master needs to be reset (bug 8161).
4785 void Buffer::checkMasterBuffer()
4786 {
4787         Buffer const * const master = masterBuffer();
4788         if (master == this)
4789                 return;
4790
4791         // necessary to re-register the child (bug 5873)
4792         // FIXME: clean up updateMacros (here, only
4793         // child registering is needed).
4794         master->updateMacros();
4795         // (re)set master as master buffer, but only
4796         // if we are a real child
4797         if (master->isChild(this))
4798                 setParent(master);
4799         else
4800                 setParent(0);
4801 }
4802
4803 } // namespace lyx