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