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