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