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