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