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