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