]> git.lyx.org Git - lyx.git/blob - src/Buffer.cpp
da64676d7bd0a47d7776533d48a399d90d4ceab2
[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                 } else {
2272                         branch->setSelected(func.action() == LFUN_BRANCH_ACTIVATE);
2273                         dr.setError(false);
2274                         dr.screenUpdate(Update::Force);
2275                         dr.forceBufferUpdate();
2276                 }
2277                 break;
2278         }
2279
2280         case LFUN_BRANCHES_RENAME: {
2281                 if (func.argument().empty())
2282                         break;
2283
2284                 docstring const oldname = from_utf8(func.getArg(0));
2285                 docstring const newname = from_utf8(func.getArg(1));
2286                 InsetIterator it  = inset_iterator_begin(inset());
2287                 InsetIterator const end = inset_iterator_end(inset());
2288                 bool success = false;
2289                 for (; it != end; ++it) {
2290                         if (it->lyxCode() == BRANCH_CODE) {
2291                                 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2292                                 if (ins.branch() == oldname) {
2293                                         undo().recordUndo(it);
2294                                         ins.rename(newname);
2295                                         success = true;
2296                                         continue;
2297                                 }
2298                         }
2299                         if (it->lyxCode() == INCLUDE_CODE) {
2300                                 // get buffer of external file
2301                                 InsetInclude const & ins =
2302                                         static_cast<InsetInclude const &>(*it);
2303                                 Buffer * child = ins.getChildBuffer();
2304                                 if (!child)
2305                                         continue;
2306                                 child->dispatch(func, dr);
2307                         }
2308                 }
2309
2310                 if (success) {
2311                         dr.screenUpdate(Update::Force);
2312                         dr.forceBufferUpdate();
2313                 }
2314                 break;
2315         }
2316
2317         case LFUN_BUFFER_PRINT: {
2318                 // we'll assume there's a problem until we succeed
2319                 dr.setError(true); 
2320                 string target = func.getArg(0);
2321                 string target_name = func.getArg(1);
2322                 string command = func.getArg(2);
2323
2324                 if (target.empty()
2325                     || target_name.empty()
2326                     || command.empty()) {
2327                         LYXERR0("Unable to parse " << func.argument());
2328                         docstring const msg = 
2329                                 bformat(_("Unable to parse \"%1$s\""), func.argument());
2330                         dr.setMessage(msg);
2331                         break;
2332                 }
2333                 if (target != "printer" && target != "file") {
2334                         LYXERR0("Unrecognized target \"" << target << '"');
2335                         docstring const msg = 
2336                                 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2337                         dr.setMessage(msg);
2338                         break;
2339                 }
2340
2341                 if (!doExport("dvi", true)) {
2342                         showPrintError(absFileName());
2343                         dr.setMessage(_("Error exporting to DVI."));
2344                         break;
2345                 }
2346
2347                 // Push directory path.
2348                 string const path = temppath();
2349                 // Prevent the compiler from optimizing away p
2350                 FileName pp(path);
2351                 PathChanger p(pp);
2352
2353                 // there are three cases here:
2354                 // 1. we print to a file
2355                 // 2. we print directly to a printer
2356                 // 3. we print using a spool command (print to file first)
2357                 Systemcall one;
2358                 int res = 0;
2359                 string const dviname = changeExtension(latexName(true), "dvi");
2360
2361                 if (target == "printer") {
2362                         if (!lyxrc.print_spool_command.empty()) {
2363                                 // case 3: print using a spool
2364                                 string const psname = changeExtension(dviname,".ps");
2365                                 command += ' ' + lyxrc.print_to_file
2366                                         + quoteName(psname)
2367                                         + ' '
2368                                         + quoteName(dviname);
2369
2370                                 string command2 = lyxrc.print_spool_command + ' ';
2371                                 if (target_name != "default") {
2372                                         command2 += lyxrc.print_spool_printerprefix
2373                                                 + target_name
2374                                                 + ' ';
2375                                 }
2376                                 command2 += quoteName(psname);
2377                                 // First run dvips.
2378                                 // If successful, then spool command
2379                                 res = one.startscript(Systemcall::Wait, command,
2380                                                       filePath());
2381
2382                                 if (res == 0) {
2383                                         // If there's no GUI, we have to wait on this command. Otherwise,
2384                                         // LyX deletes the temporary directory, and with it the spooled
2385                                         // file, before it can be printed!!
2386                                         Systemcall::Starttype stype = use_gui ?
2387                                                 Systemcall::DontWait : Systemcall::Wait;
2388                                         res = one.startscript(stype, command2,
2389                                                               filePath());
2390                                 }
2391                         } else {
2392                                 // case 2: print directly to a printer
2393                                 if (target_name != "default")
2394                                         command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2395                                 // as above....
2396                                 Systemcall::Starttype stype = use_gui ?
2397                                         Systemcall::DontWait : Systemcall::Wait;
2398                                 res = one.startscript(stype, command +
2399                                                 quoteName(dviname), filePath());
2400                         }
2401
2402                 } else {
2403                         // case 1: print to a file
2404                         FileName const filename(makeAbsPath(target_name, filePath()));
2405                         FileName const dvifile(makeAbsPath(dviname, path));
2406                         if (filename.exists()) {
2407                                 docstring text = bformat(
2408                                         _("The file %1$s already exists.\n\n"
2409                                           "Do you want to overwrite that file?"),
2410                                         makeDisplayPath(filename.absFileName()));
2411                                 if (Alert::prompt(_("Overwrite file?"),
2412                                                   text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2413                                         break;
2414                         }
2415                         command += ' ' + lyxrc.print_to_file
2416                                 + quoteName(filename.toFilesystemEncoding())
2417                                 + ' '
2418                                 + quoteName(dvifile.toFilesystemEncoding());
2419                         // as above....
2420                         Systemcall::Starttype stype = use_gui ?
2421                                 Systemcall::DontWait : Systemcall::Wait;
2422                         res = one.startscript(stype, command, filePath());
2423                 }
2424
2425                 if (res == 0) 
2426                         dr.setError(false);
2427                 else {
2428                         dr.setMessage(_("Error running external commands."));
2429                         showPrintError(absFileName());
2430                 }
2431                 break;
2432         }
2433
2434         default:
2435                 dispatched = false;
2436                 break;
2437         }
2438         dr.dispatched(dispatched);
2439         undo().endUndoGroup();
2440 }
2441
2442
2443 void Buffer::changeLanguage(Language const * from, Language const * to)
2444 {
2445         LASSERT(from, /**/);
2446         LASSERT(to, /**/);
2447
2448         for_each(par_iterator_begin(),
2449                  par_iterator_end(),
2450                  bind(&Paragraph::changeLanguage, _1, params(), from, to));
2451 }
2452
2453
2454 bool Buffer::isMultiLingual() const
2455 {
2456         ParConstIterator end = par_iterator_end();
2457         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2458                 if (it->isMultiLingual(params()))
2459                         return true;
2460
2461         return false;
2462 }
2463
2464
2465 std::set<Language const *> Buffer::getLanguages() const
2466 {
2467         std::set<Language const *> languages;
2468         getLanguages(languages);
2469         return languages;
2470 }
2471
2472
2473 void Buffer::getLanguages(std::set<Language const *> & languages) const
2474 {
2475         ParConstIterator end = par_iterator_end();
2476         // add the buffer language, even if it's not actively used
2477         languages.insert(language());
2478         // iterate over the paragraphs
2479         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2480                 it->getLanguages(languages);
2481         // also children
2482         ListOfBuffers clist = getDescendents();
2483         ListOfBuffers::const_iterator cit = clist.begin();
2484         ListOfBuffers::const_iterator const cen = clist.end();
2485         for (; cit != cen; ++cit)
2486                 (*cit)->getLanguages(languages);
2487 }
2488
2489
2490 DocIterator Buffer::getParFromID(int const id) const
2491 {
2492         Buffer * buf = const_cast<Buffer *>(this);
2493         if (id < 0) {
2494                 // John says this is called with id == -1 from undo
2495                 lyxerr << "getParFromID(), id: " << id << endl;
2496                 return doc_iterator_end(buf);
2497         }
2498
2499         for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2500                 if (it.paragraph().id() == id)
2501                         return it;
2502
2503         return doc_iterator_end(buf);
2504 }
2505
2506
2507 bool Buffer::hasParWithID(int const id) const
2508 {
2509         return !getParFromID(id).atEnd();
2510 }
2511
2512
2513 ParIterator Buffer::par_iterator_begin()
2514 {
2515         return ParIterator(doc_iterator_begin(this));
2516 }
2517
2518
2519 ParIterator Buffer::par_iterator_end()
2520 {
2521         return ParIterator(doc_iterator_end(this));
2522 }
2523
2524
2525 ParConstIterator Buffer::par_iterator_begin() const
2526 {
2527         return ParConstIterator(doc_iterator_begin(this));
2528 }
2529
2530
2531 ParConstIterator Buffer::par_iterator_end() const
2532 {
2533         return ParConstIterator(doc_iterator_end(this));
2534 }
2535
2536
2537 Language const * Buffer::language() const
2538 {
2539         return params().language;
2540 }
2541
2542
2543 docstring const Buffer::B_(string const & l10n) const
2544 {
2545         return params().B_(l10n);
2546 }
2547
2548
2549 bool Buffer::isClean() const
2550 {
2551         return d->lyx_clean;
2552 }
2553
2554
2555 bool Buffer::isExternallyModified(CheckMethod method) const
2556 {
2557         LASSERT(d->filename.exists(), /**/);
2558         // if method == timestamp, check timestamp before checksum
2559         return (method == checksum_method
2560                 || d->timestamp_ != d->filename.lastModified())
2561                 && d->checksum_ != d->filename.checksum();
2562 }
2563
2564
2565 void Buffer::saveCheckSum() const
2566 {
2567         FileName const & file = d->filename;
2568
2569         file.refresh();
2570         if (file.exists()) {
2571                 d->timestamp_ = file.lastModified();
2572                 d->checksum_ = file.checksum();
2573         } else {
2574                 // in the case of save to a new file.
2575                 d->timestamp_ = 0;
2576                 d->checksum_ = 0;
2577         }
2578 }
2579
2580
2581 void Buffer::markClean() const
2582 {
2583         if (!d->lyx_clean) {
2584                 d->lyx_clean = true;
2585                 updateTitles();
2586         }
2587         // if the .lyx file has been saved, we don't need an
2588         // autosave
2589         d->bak_clean = true;
2590         d->undo_.markDirty();
2591 }
2592
2593
2594 void Buffer::setUnnamed(bool flag)
2595 {
2596         d->unnamed = flag;
2597 }
2598
2599
2600 bool Buffer::isUnnamed() const
2601 {
2602         return d->unnamed;
2603 }
2604
2605
2606 /// \note
2607 /// Don't check unnamed, here: isInternal() is used in
2608 /// newBuffer(), where the unnamed flag has not been set by anyone
2609 /// yet. Also, for an internal buffer, there should be no need for
2610 /// retrieving fileName() nor for checking if it is unnamed or not.
2611 bool Buffer::isInternal() const
2612 {
2613         return fileName().extension() == "internal";
2614 }
2615
2616
2617 void Buffer::markDirty()
2618 {
2619         if (d->lyx_clean) {
2620                 d->lyx_clean = false;
2621                 updateTitles();
2622         }
2623         d->bak_clean = false;
2624
2625         DepClean::iterator it = d->dep_clean.begin();
2626         DepClean::const_iterator const end = d->dep_clean.end();
2627
2628         for (; it != end; ++it)
2629                 it->second = false;
2630 }
2631
2632
2633 FileName Buffer::fileName() const
2634 {
2635         return d->filename;
2636 }
2637
2638
2639 string Buffer::absFileName() const
2640 {
2641         return d->filename.absFileName();
2642 }
2643
2644
2645 string Buffer::filePath() const
2646 {
2647         return d->filename.onlyPath().absFileName() + "/";
2648 }
2649
2650
2651 bool Buffer::isReadonly() const
2652 {
2653         return d->read_only;
2654 }
2655
2656
2657 void Buffer::setParent(Buffer const * buffer)
2658 {
2659         // Avoids recursive include.
2660         d->setParent(buffer == this ? 0 : buffer);
2661         updateMacros();
2662 }
2663
2664
2665 Buffer const * Buffer::parent() const
2666 {
2667         return d->parent();
2668 }
2669
2670
2671 ListOfBuffers Buffer::allRelatives() const
2672 {
2673         ListOfBuffers lb = masterBuffer()->getDescendents();
2674         lb.push_front(const_cast<Buffer *>(masterBuffer()));
2675         return lb;
2676 }
2677
2678
2679 Buffer const * Buffer::masterBuffer() const
2680 {
2681         // FIXME Should be make sure we are not in some kind
2682         // of recursive include? A -> B -> A will crash this.
2683         Buffer const * const pbuf = d->parent();
2684         if (!pbuf)
2685                 return this;
2686
2687         return pbuf->masterBuffer();
2688 }
2689
2690
2691 bool Buffer::isChild(Buffer * child) const
2692 {
2693         return d->children_positions.find(child) != d->children_positions.end();
2694 }
2695
2696
2697 DocIterator Buffer::firstChildPosition(Buffer const * child)
2698 {
2699         Impl::BufferPositionMap::iterator it;
2700         it = d->children_positions.find(child);
2701         if (it == d->children_positions.end())
2702                 return DocIterator(this);
2703         return it->second;
2704 }
2705
2706
2707 bool Buffer::hasChildren() const
2708 {
2709         return !d->children_positions.empty();  
2710 }
2711
2712
2713 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
2714 {
2715         // loop over children
2716         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2717         Impl::BufferPositionMap::iterator end = d->children_positions.end();
2718         for (; it != end; ++it) {
2719                 Buffer * child = const_cast<Buffer *>(it->first);
2720                 // No duplicates
2721                 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
2722                 if (bit != clist.end())
2723                         continue;
2724                 clist.push_back(child);
2725                 if (grand_children) 
2726                         // there might be grandchildren
2727                         child->collectChildren(clist, true);
2728         }
2729 }
2730
2731
2732 ListOfBuffers Buffer::getChildren() const
2733 {
2734         ListOfBuffers v;
2735         collectChildren(v, false);
2736         // Make sure we have not included ourselves.
2737         ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
2738         if (bit != v.end()) {
2739                 LYXERR0("Recursive include detected in `" << fileName() << "'.");
2740                 v.erase(bit);
2741         }
2742         return v;
2743 }
2744
2745
2746 ListOfBuffers Buffer::getDescendents() const
2747 {
2748         ListOfBuffers v;
2749         collectChildren(v, true);
2750         // Make sure we have not included ourselves.
2751         ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
2752         if (bit != v.end()) {
2753                 LYXERR0("Recursive include detected in `" << fileName() << "'.");
2754                 v.erase(bit);
2755         }
2756         return v;
2757 }
2758
2759
2760 template<typename M>
2761 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
2762 {
2763         if (m.empty())
2764                 return m.end();
2765
2766         typename M::const_iterator it = m.lower_bound(x);
2767         if (it == m.begin())
2768                 return m.end();
2769
2770         it--;
2771         return it;
2772 }
2773
2774
2775 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
2776                                          DocIterator const & pos) const
2777 {
2778         LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2779
2780         // if paragraphs have no macro context set, pos will be empty
2781         if (pos.empty())
2782                 return 0;
2783
2784         // we haven't found anything yet
2785         DocIterator bestPos = owner_->par_iterator_begin();
2786         MacroData const * bestData = 0;
2787
2788         // find macro definitions for name
2789         NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
2790         if (nameIt != macros.end()) {
2791                 // find last definition in front of pos or at pos itself
2792                 PositionScopeMacroMap::const_iterator it
2793                         = greatest_below(nameIt->second, pos);
2794                 if (it != nameIt->second.end()) {
2795                         while (true) {
2796                                 // scope ends behind pos?
2797                                 if (pos < it->second.first) {
2798                                         // Looks good, remember this. If there
2799                                         // is no external macro behind this,
2800                                         // we found the right one already.
2801                                         bestPos = it->first;
2802                                         bestData = &it->second.second;
2803                                         break;
2804                                 }
2805
2806                                 // try previous macro if there is one
2807                                 if (it == nameIt->second.begin())
2808                                         break;
2809                                 it--;
2810                         }
2811                 }
2812         }
2813
2814         // find macros in included files
2815         PositionScopeBufferMap::const_iterator it
2816                 = greatest_below(position_to_children, pos);
2817         if (it == position_to_children.end())
2818                 // no children before
2819                 return bestData;
2820
2821         while (true) {
2822                 // do we know something better (i.e. later) already?
2823                 if (it->first < bestPos )
2824                         break;
2825
2826                 // scope ends behind pos?
2827                 if (pos < it->second.first
2828                         && (cloned_buffer_ ||
2829                             theBufferList().isLoaded(it->second.second))) {
2830                         // look for macro in external file
2831                         macro_lock = true;
2832                         MacroData const * data
2833                                 = it->second.second->getMacro(name, false);
2834                         macro_lock = false;
2835                         if (data) {
2836                                 bestPos = it->first;
2837                                 bestData = data;
2838                                 break;
2839                         }
2840                 }
2841
2842                 // try previous file if there is one
2843                 if (it == position_to_children.begin())
2844                         break;
2845                 --it;
2846         }
2847
2848         // return the best macro we have found
2849         return bestData;
2850 }
2851
2852
2853 MacroData const * Buffer::getMacro(docstring const & name,
2854         DocIterator const & pos, bool global) const
2855 {
2856         if (d->macro_lock)
2857                 return 0;
2858
2859         // query buffer macros
2860         MacroData const * data = d->getBufferMacro(name, pos);
2861         if (data != 0)
2862                 return data;
2863
2864         // If there is a master buffer, query that
2865         Buffer const * const pbuf = d->parent();
2866         if (pbuf) {
2867                 d->macro_lock = true;
2868                 MacroData const * macro = pbuf->getMacro(
2869                         name, *this, false);
2870                 d->macro_lock = false;
2871                 if (macro)
2872                         return macro;
2873         }
2874
2875         if (global) {
2876                 data = MacroTable::globalMacros().get(name);
2877                 if (data != 0)
2878                         return data;
2879         }
2880
2881         return 0;
2882 }
2883
2884
2885 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2886 {
2887         // set scope end behind the last paragraph
2888         DocIterator scope = par_iterator_begin();
2889         scope.pit() = scope.lastpit() + 1;
2890
2891         return getMacro(name, scope, global);
2892 }
2893
2894
2895 MacroData const * Buffer::getMacro(docstring const & name,
2896         Buffer const & child, bool global) const
2897 {
2898         // look where the child buffer is included first
2899         Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2900         if (it == d->children_positions.end())
2901                 return 0;
2902
2903         // check for macros at the inclusion position
2904         return getMacro(name, it->second, global);
2905 }
2906
2907
2908 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
2909 {
2910         pit_type const lastpit = it.lastpit();
2911
2912         // look for macros in each paragraph
2913         while (it.pit() <= lastpit) {
2914                 Paragraph & par = it.paragraph();
2915
2916                 // iterate over the insets of the current paragraph
2917                 InsetList const & insets = par.insetList();
2918                 InsetList::const_iterator iit = insets.begin();
2919                 InsetList::const_iterator end = insets.end();
2920                 for (; iit != end; ++iit) {
2921                         it.pos() = iit->pos;
2922
2923                         // is it a nested text inset?
2924                         if (iit->inset->asInsetText()) {
2925                                 // Inset needs its own scope?
2926                                 InsetText const * itext = iit->inset->asInsetText();
2927                                 bool newScope = itext->isMacroScope();
2928
2929                                 // scope which ends just behind the inset
2930                                 DocIterator insetScope = it;
2931                                 ++insetScope.pos();
2932
2933                                 // collect macros in inset
2934                                 it.push_back(CursorSlice(*iit->inset));
2935                                 updateMacros(it, newScope ? insetScope : scope);
2936                                 it.pop_back();
2937                                 continue;
2938                         }
2939                         
2940                         if (iit->inset->asInsetTabular()) {
2941                                 CursorSlice slice(*iit->inset);
2942                                 size_t const numcells = slice.nargs();
2943                                 for (; slice.idx() < numcells; slice.forwardIdx()) {
2944                                         it.push_back(slice);
2945                                         updateMacros(it, scope);
2946                                         it.pop_back();
2947                                 }
2948                                 continue;
2949                         }
2950
2951                         // is it an external file?
2952                         if (iit->inset->lyxCode() == INCLUDE_CODE) {
2953                                 // get buffer of external file
2954                                 InsetInclude const & inset =
2955                                         static_cast<InsetInclude const &>(*iit->inset);
2956                                 macro_lock = true;
2957                                 Buffer * child = inset.getChildBuffer();
2958                                 macro_lock = false;
2959                                 if (!child)
2960                                         continue;
2961
2962                                 // register its position, but only when it is
2963                                 // included first in the buffer
2964                                 if (children_positions.find(child) ==
2965                                         children_positions.end())
2966                                                 children_positions[child] = it;
2967
2968                                 // register child with its scope
2969                                 position_to_children[it] = Impl::ScopeBuffer(scope, child);
2970                                 continue;
2971                         }
2972
2973                         InsetMath * im = iit->inset->asInsetMath();
2974                         if (doing_export && im)  {
2975                                 InsetMathHull * hull = im->asHullInset();
2976                                 if (hull)
2977                                         hull->recordLocation(it);
2978                         }
2979
2980                         if (iit->inset->lyxCode() != MATHMACRO_CODE)
2981                                 continue;
2982
2983                         // get macro data
2984                         MathMacroTemplate & macroTemplate =
2985                                 *iit->inset->asInsetMath()->asMacroTemplate();
2986                         MacroContext mc(owner_, it);
2987                         macroTemplate.updateToContext(mc);
2988
2989                         // valid?
2990                         bool valid = macroTemplate.validMacro();
2991                         // FIXME: Should be fixNameAndCheckIfValid() in fact,
2992                         // then the BufferView's cursor will be invalid in
2993                         // some cases which leads to crashes.
2994                         if (!valid)
2995                                 continue;
2996
2997                         // register macro
2998                         // FIXME (Abdel), I don't understandt why we pass 'it' here
2999                         // instead of 'macroTemplate' defined above... is this correct?
3000                         macros[macroTemplate.name()][it] =
3001                                 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3002                 }
3003
3004                 // next paragraph
3005                 it.pit()++;
3006                 it.pos() = 0;
3007         }
3008 }
3009
3010
3011 void Buffer::updateMacros() const
3012 {
3013         if (d->macro_lock)
3014                 return;
3015
3016         LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3017
3018         // start with empty table
3019         d->macros.clear();
3020         d->children_positions.clear();
3021         d->position_to_children.clear();
3022
3023         // Iterate over buffer, starting with first paragraph
3024         // The scope must be bigger than any lookup DocIterator
3025         // later. For the global lookup, lastpit+1 is used, hence
3026         // we use lastpit+2 here.
3027         DocIterator it = par_iterator_begin();
3028         DocIterator outerScope = it;
3029         outerScope.pit() = outerScope.lastpit() + 2;
3030         d->updateMacros(it, outerScope);
3031 }
3032
3033
3034 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3035 {
3036         InsetIterator it  = inset_iterator_begin(inset());
3037         InsetIterator const end = inset_iterator_end(inset());
3038         for (; it != end; ++it) {
3039                 if (it->lyxCode() == BRANCH_CODE) {
3040                         InsetBranch & br = static_cast<InsetBranch &>(*it);
3041                         docstring const name = br.branch();
3042                         if (!from_master && !params().branchlist().find(name))
3043                                 result.push_back(name);
3044                         else if (from_master && !masterBuffer()->params().branchlist().find(name))
3045                                 result.push_back(name);
3046                         continue;
3047                 }
3048                 if (it->lyxCode() == INCLUDE_CODE) {
3049                         // get buffer of external file
3050                         InsetInclude const & ins =
3051                                 static_cast<InsetInclude const &>(*it);
3052                         Buffer * child = ins.getChildBuffer();
3053                         if (!child)
3054                                 continue;
3055                         child->getUsedBranches(result, true);
3056                 }
3057         }
3058         // remove duplicates
3059         result.unique();
3060 }
3061
3062
3063 void Buffer::updateMacroInstances(UpdateType utype) const
3064 {
3065         LYXERR(Debug::MACROS, "updateMacroInstances for "
3066                 << d->filename.onlyFileName());
3067         DocIterator it = doc_iterator_begin(this);
3068         it.forwardInset();
3069         DocIterator const end = doc_iterator_end(this);
3070         for (; it != end; it.forwardInset()) {
3071                 // look for MathData cells in InsetMathNest insets
3072                 InsetMath * minset = it.nextInset()->asInsetMath();
3073                 if (!minset)
3074                         continue;
3075
3076                 // update macro in all cells of the InsetMathNest
3077                 DocIterator::idx_type n = minset->nargs();
3078                 MacroContext mc = MacroContext(this, it);
3079                 for (DocIterator::idx_type i = 0; i < n; ++i) {
3080                         MathData & data = minset->cell(i);
3081                         data.updateMacros(0, mc, utype);
3082                 }
3083         }
3084 }
3085
3086
3087 void Buffer::listMacroNames(MacroNameSet & macros) const
3088 {
3089         if (d->macro_lock)
3090                 return;
3091
3092         d->macro_lock = true;
3093
3094         // loop over macro names
3095         Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3096         Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3097         for (; nameIt != nameEnd; ++nameIt)
3098                 macros.insert(nameIt->first);
3099
3100         // loop over children
3101         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3102         Impl::BufferPositionMap::iterator end = d->children_positions.end();
3103         for (; it != end; ++it)
3104                 it->first->listMacroNames(macros);
3105
3106         // call parent
3107         Buffer const * const pbuf = d->parent();
3108         if (pbuf)
3109                 pbuf->listMacroNames(macros);
3110
3111         d->macro_lock = false;
3112 }
3113
3114
3115 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3116 {
3117         Buffer const * const pbuf = d->parent();
3118         if (!pbuf)
3119                 return;
3120
3121         MacroNameSet names;
3122         pbuf->listMacroNames(names);
3123
3124         // resolve macros
3125         MacroNameSet::iterator it = names.begin();
3126         MacroNameSet::iterator end = names.end();
3127         for (; it != end; ++it) {
3128                 // defined?
3129                 MacroData const * data =
3130                 pbuf->getMacro(*it, *this, false);
3131                 if (data) {
3132                         macros.insert(data);
3133
3134                         // we cannot access the original MathMacroTemplate anymore
3135                         // here to calls validate method. So we do its work here manually.
3136                         // FIXME: somehow make the template accessible here.
3137                         if (data->optionals() > 0)
3138                                 features.require("xargs");
3139                 }
3140         }
3141 }
3142
3143
3144 Buffer::References & Buffer::references(docstring const & label)
3145 {
3146         if (d->parent())
3147                 return const_cast<Buffer *>(masterBuffer())->references(label);
3148
3149         RefCache::iterator it = d->ref_cache_.find(label);
3150         if (it != d->ref_cache_.end())
3151                 return it->second.second;
3152
3153         static InsetLabel const * dummy_il = 0;
3154         static References const dummy_refs;
3155         it = d->ref_cache_.insert(
3156                 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3157         return it->second.second;
3158 }
3159
3160
3161 Buffer::References const & Buffer::references(docstring const & label) const
3162 {
3163         return const_cast<Buffer *>(this)->references(label);
3164 }
3165
3166
3167 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3168 {
3169         masterBuffer()->d->ref_cache_[label].first = il;
3170 }
3171
3172
3173 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3174 {
3175         return masterBuffer()->d->ref_cache_[label].first;
3176 }
3177
3178
3179 void Buffer::clearReferenceCache() const
3180 {
3181         if (!d->parent())
3182                 d->ref_cache_.clear();
3183 }
3184
3185
3186 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
3187         InsetCode code)
3188 {
3189         //FIXME: This does not work for child documents yet.
3190         LASSERT(code == CITE_CODE, /**/);
3191
3192         reloadBibInfoCache();
3193
3194         // Check if the label 'from' appears more than once
3195         BiblioInfo const & keys = masterBibInfo();
3196         BiblioInfo::const_iterator bit  = keys.begin();
3197         BiblioInfo::const_iterator bend = keys.end();
3198         vector<docstring> labels;
3199
3200         for (; bit != bend; ++bit)
3201                 // FIXME UNICODE
3202                 labels.push_back(bit->first);
3203
3204         if (count(labels.begin(), labels.end(), from) > 1)
3205                 return;
3206
3207         string const paramName = "key";
3208         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3209                 if (it->lyxCode() == code) {
3210                         InsetCommand * inset = it->asInsetCommand();
3211                         if (!inset)
3212                                 continue;
3213                         docstring const oldValue = inset->getParam(paramName);
3214                         if (oldValue == from)
3215                                 inset->setParam(paramName, to);
3216                 }
3217         }
3218 }
3219
3220
3221 void Buffer::getSourceCode(odocstream & os, string const format,
3222                            pit_type par_begin, pit_type par_end,
3223                            OutputWhat output) const
3224 {
3225         OutputParams runparams(&params().encoding());
3226         runparams.nice = true;
3227         runparams.flavor = params().getOutputFlavor(format);
3228         runparams.linelen = lyxrc.plaintext_linelen;
3229         // No side effect of file copying and image conversion
3230         runparams.dryrun = true;
3231
3232         if (output == CurrentParagraph) {
3233                 runparams.par_begin = par_begin;
3234                 runparams.par_end = par_end;
3235                 if (par_begin + 1 == par_end) {
3236                         os << "% "
3237                            << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3238                            << "\n\n";
3239                 } else {
3240                         os << "% "
3241                            << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3242                                         convert<docstring>(par_begin),
3243                                         convert<docstring>(par_end - 1))
3244                            << "\n\n";
3245                 }
3246                 TexRow texrow;
3247                 texrow.reset();
3248                 texrow.newline();
3249                 texrow.newline();
3250                 // output paragraphs
3251                 if (params().isDocBook())
3252                         docbookParagraphs(text(), *this, os, runparams);
3253                 else if (runparams.flavor == OutputParams::HTML) {
3254                         XHTMLStream xs(os);
3255                         xhtmlParagraphs(text(), *this, xs, runparams);
3256                 } else {
3257                         // latex or literate
3258                         otexstream ots(os, texrow);
3259                         latexParagraphs(*this, text(), ots, runparams);
3260                 }
3261         } else {
3262                 os << "% ";
3263                 if (output == FullSource) 
3264                         os << _("Preview source code");
3265                 else if (output == OnlyPreamble)
3266                         os << _("Preview preamble");
3267                 else if (output == OnlyBody)
3268                         os << _("Preview body");
3269                 os << "\n\n";
3270                 d->texrow.reset();
3271                 d->texrow.newline();
3272                 d->texrow.newline();
3273                 if (params().isDocBook())
3274                         writeDocBookSource(os, absFileName(), runparams, output);
3275                 else if (runparams.flavor == OutputParams::HTML)
3276                         writeLyXHTMLSource(os, runparams, output);
3277                 else {
3278                         // latex or literate
3279                         otexstream ots(os, d->texrow);
3280                         writeLaTeXSource(ots, string(), runparams, output);
3281                 }
3282         }
3283 }
3284
3285
3286 ErrorList & Buffer::errorList(string const & type) const
3287 {
3288         return d->errorLists[type];
3289 }
3290
3291
3292 void Buffer::updateTocItem(std::string const & type,
3293         DocIterator const & dit) const
3294 {
3295         if (d->gui_)
3296                 d->gui_->updateTocItem(type, dit);
3297 }
3298
3299
3300 void Buffer::structureChanged() const
3301 {
3302         if (d->gui_)
3303                 d->gui_->structureChanged();
3304 }
3305
3306
3307 void Buffer::errors(string const & err, bool from_master) const
3308 {
3309         if (d->gui_)
3310                 d->gui_->errors(err, from_master);
3311 }
3312
3313
3314 void Buffer::message(docstring const & msg) const
3315 {
3316         if (d->gui_)
3317                 d->gui_->message(msg);
3318 }
3319
3320
3321 void Buffer::setBusy(bool on) const
3322 {
3323         if (d->gui_)
3324                 d->gui_->setBusy(on);
3325 }
3326
3327
3328 void Buffer::updateTitles() const
3329 {
3330         if (d->wa_)
3331                 d->wa_->updateTitles();
3332 }
3333
3334
3335 void Buffer::resetAutosaveTimers() const
3336 {
3337         if (d->gui_)
3338                 d->gui_->resetAutosaveTimers();
3339 }
3340
3341
3342 bool Buffer::hasGuiDelegate() const
3343 {
3344         return d->gui_;
3345 }
3346
3347
3348 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3349 {
3350         d->gui_ = gui;
3351 }
3352
3353
3354
3355 namespace {
3356
3357 class AutoSaveBuffer : public ForkedProcess {
3358 public:
3359         ///
3360         AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3361                 : buffer_(buffer), fname_(fname) {}
3362         ///
3363         virtual shared_ptr<ForkedProcess> clone() const
3364         {
3365                 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3366         }
3367         ///
3368         int start()
3369         {
3370                 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3371                                                  from_utf8(fname_.absFileName())));
3372                 return run(DontWait);
3373         }
3374 private:
3375         ///
3376         virtual int generateChild();
3377         ///
3378         Buffer const & buffer_;
3379         FileName fname_;
3380 };
3381
3382
3383 int AutoSaveBuffer::generateChild()
3384 {
3385 #if defined(__APPLE__)
3386         /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard) 
3387          *   We should use something else like threads.
3388          *
3389          * Since I do not know how to determine at run time what is the OS X
3390          * version, I just disable forking altogether for now (JMarc)
3391          */
3392         pid_t const pid = -1;
3393 #else
3394         // tmp_ret will be located (usually) in /tmp
3395         // will that be a problem?
3396         // Note that this calls ForkedCalls::fork(), so it's
3397         // ok cross-platform.
3398         pid_t const pid = fork();
3399         // If you want to debug the autosave
3400         // you should set pid to -1, and comment out the fork.
3401         if (pid != 0 && pid != -1)
3402                 return pid;
3403 #endif
3404
3405         // pid = -1 signifies that lyx was unable
3406         // to fork. But we will do the save
3407         // anyway.
3408         bool failed = false;
3409         FileName const tmp_ret = FileName::tempName("lyxauto");
3410         if (!tmp_ret.empty()) {
3411                 buffer_.writeFile(tmp_ret);
3412                 // assume successful write of tmp_ret
3413                 if (!tmp_ret.moveTo(fname_))
3414                         failed = true;
3415         } else
3416                 failed = true;
3417
3418         if (failed) {
3419                 // failed to write/rename tmp_ret so try writing direct
3420                 if (!buffer_.writeFile(fname_)) {
3421                         // It is dangerous to do this in the child,
3422                         // but safe in the parent, so...
3423                         if (pid == -1) // emit message signal.
3424                                 buffer_.message(_("Autosave failed!"));
3425                 }
3426         }
3427
3428         if (pid == 0) // we are the child so...
3429                 _exit(0);
3430
3431         return pid;
3432 }
3433
3434 } // namespace anon
3435
3436
3437 FileName Buffer::getEmergencyFileName() const
3438 {
3439         return FileName(d->filename.absFileName() + ".emergency");
3440 }
3441
3442
3443 FileName Buffer::getAutosaveFileName() const
3444 {
3445         // if the document is unnamed try to save in the backup dir, else
3446         // in the default document path, and as a last try in the filePath, 
3447         // which will most often be the temporary directory
3448         string fpath;
3449         if (isUnnamed())
3450                 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3451                         : lyxrc.backupdir_path;
3452         if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3453                 fpath = filePath();
3454
3455         string const fname = "#" + d->filename.onlyFileName() + "#";
3456
3457         return makeAbsPath(fname, fpath);
3458 }
3459
3460
3461 void Buffer::removeAutosaveFile() const
3462 {
3463         FileName const f = getAutosaveFileName();
3464         if (f.exists())
3465                 f.removeFile();
3466 }
3467
3468
3469 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3470 {
3471         FileName const newauto = getAutosaveFileName();
3472         oldauto.refresh();
3473         if (newauto != oldauto && oldauto.exists())
3474                 if (!oldauto.moveTo(newauto))
3475                         LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3476 }
3477
3478
3479 bool Buffer::autoSave() const 
3480 {
3481         Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3482         if (buf->d->bak_clean || isReadonly())
3483                 return true;
3484
3485         message(_("Autosaving current document..."));
3486         buf->d->bak_clean = true;
3487         
3488         FileName const fname = getAutosaveFileName();
3489         if (d->cloned_buffer_) {
3490                 // If this buffer is cloned, we assume that
3491                 // we are running in a separate thread already.
3492                 FileName const tmp_ret = FileName::tempName("lyxauto");
3493                 if (!tmp_ret.empty()) {
3494                         writeFile(tmp_ret);
3495                         // assume successful write of tmp_ret
3496                         if (tmp_ret.moveTo(fname))
3497                                 return true;
3498                 }
3499                 // failed to write/rename tmp_ret so try writing direct
3500                 return writeFile(fname);
3501         } else {        
3502                 /// This function is deprecated as the frontend needs to take care
3503                 /// of cloning the buffer and autosaving it in another thread. It
3504                 /// is still here to allow (QT_VERSION < 0x040400).
3505                 AutoSaveBuffer autosave(*this, fname);
3506                 autosave.start();
3507                 return true;
3508         }
3509 }
3510
3511
3512 // helper class, to guarantee this gets reset properly
3513 class Buffer::MarkAsExporting {
3514 public:
3515         MarkAsExporting(Buffer const * buf) : buf_(buf)
3516         {
3517                 LASSERT(buf_, /* */);
3518                 buf_->setExportStatus(true);
3519         }
3520         ~MarkAsExporting()
3521         {
3522                 buf_->setExportStatus(false);
3523         }
3524 private:
3525         Buffer const * const buf_;
3526 };
3527
3528
3529
3530 void Buffer::setExportStatus(bool e) const
3531 {
3532         d->doing_export = e;    
3533         ListOfBuffers clist = getDescendents();
3534         ListOfBuffers::const_iterator cit = clist.begin();
3535         ListOfBuffers::const_iterator const cen = clist.end();
3536         for (; cit != cen; ++cit)
3537                 (*cit)->d->doing_export = e;
3538 }
3539
3540
3541 bool Buffer::isExporting() const
3542 {
3543         return d->doing_export;
3544 }
3545
3546
3547 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
3548         const
3549 {
3550         string result_file;
3551         return doExport(target, put_in_tempdir, result_file);
3552 }
3553
3554 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3555         string & result_file) const
3556 {
3557         bool const update_unincluded =
3558                         params().maintain_unincluded_children
3559                         && !params().getIncludedChildren().empty();
3560
3561         // (1) export with all included children (omit \includeonly)
3562         if (update_unincluded) { 
3563                 ExportStatus const status = 
3564                         doExport(target, put_in_tempdir, true, result_file);
3565                 if (status != ExportSuccess)
3566                         return status;
3567         }
3568         // (2) export with included children only
3569         return doExport(target, put_in_tempdir, false, result_file);
3570 }
3571
3572
3573 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3574         bool includeall, string & result_file) const
3575 {
3576         LYXERR(Debug::FILES, "target=" << target);
3577         OutputParams runparams(&params().encoding());
3578         string format = target;
3579         string dest_filename;
3580         size_t pos = target.find(' ');
3581         if (pos != string::npos) {
3582                 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
3583                 format = target.substr(0, pos);
3584                 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
3585                 FileName(dest_filename).onlyPath().createPath();
3586                 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
3587         }
3588         MarkAsExporting exporting(this);
3589         string backend_format;
3590         runparams.flavor = OutputParams::LATEX;
3591         runparams.linelen = lyxrc.plaintext_linelen;
3592         runparams.includeall = includeall;
3593         vector<string> backs = params().backends();
3594         Converters converters = theConverters();
3595         if (find(backs.begin(), backs.end(), format) == backs.end()) {
3596                 // Get shortest path to format
3597                 converters.buildGraph();
3598                 Graph::EdgePath path;
3599                 for (vector<string>::const_iterator it = backs.begin();
3600                      it != backs.end(); ++it) {
3601                         Graph::EdgePath p = converters.getPath(*it, format);
3602                         if (!p.empty() && (path.empty() || p.size() < path.size())) {
3603                                 backend_format = *it;
3604                                 path = p;
3605                         }
3606                 }
3607                 if (path.empty()) {
3608                         if (!put_in_tempdir) {
3609                                 // Only show this alert if this is an export to a non-temporary
3610                                 // file (not for previewing).
3611                                 Alert::error(_("Couldn't export file"), bformat(
3612                                         _("No information for exporting the format %1$s."),
3613                                         formats.prettyName(format)));
3614                         }
3615                         return ExportNoPathToFormat;
3616                 }
3617                 runparams.flavor = converters.getFlavor(path);
3618
3619         } else {
3620                 backend_format = format;
3621                 LYXERR(Debug::FILES, "backend_format=" << backend_format);
3622                 // FIXME: Don't hardcode format names here, but use a flag
3623                 if (backend_format == "pdflatex")
3624                         runparams.flavor = OutputParams::PDFLATEX;
3625                 else if (backend_format == "luatex")
3626                         runparams.flavor = OutputParams::LUATEX;
3627                 else if (backend_format == "dviluatex")
3628                         runparams.flavor = OutputParams::DVILUATEX;
3629                 else if (backend_format == "xetex")
3630                         runparams.flavor = OutputParams::XETEX;
3631         }
3632
3633         string filename = latexName(false);
3634         filename = addName(temppath(), filename);
3635         filename = changeExtension(filename,
3636                                    formats.extension(backend_format));
3637         LYXERR(Debug::FILES, "filename=" << filename);
3638
3639         // Plain text backend
3640         if (backend_format == "text") {
3641                 runparams.flavor = OutputParams::TEXT;
3642                 writePlaintextFile(*this, FileName(filename), runparams);
3643         }
3644         // HTML backend
3645         else if (backend_format == "xhtml") {
3646                 runparams.flavor = OutputParams::HTML;
3647                 switch (params().html_math_output) {
3648                 case BufferParams::MathML: 
3649                         runparams.math_flavor = OutputParams::MathAsMathML; 
3650                         break;
3651                 case BufferParams::HTML: 
3652                         runparams.math_flavor = OutputParams::MathAsHTML; 
3653                         break;
3654                 case BufferParams::Images:
3655                         runparams.math_flavor = OutputParams::MathAsImages; 
3656                         break;
3657                 case BufferParams::LaTeX:
3658                         runparams.math_flavor = OutputParams::MathAsLaTeX; 
3659                         break;
3660                 }
3661                 makeLyXHTMLFile(FileName(filename), runparams);
3662         } else if (backend_format == "lyx")
3663                 writeFile(FileName(filename));
3664         // Docbook backend
3665         else if (params().isDocBook()) {
3666                 runparams.nice = !put_in_tempdir;
3667                 makeDocBookFile(FileName(filename), runparams);
3668         }
3669         // LaTeX backend
3670         else if (backend_format == format) {
3671                 runparams.nice = true;
3672                 if (!makeLaTeXFile(FileName(filename), string(), runparams)) {
3673                         if (d->cloned_buffer_) {
3674                                 d->cloned_buffer_->d->errorLists["Export"] =
3675                                         d->errorLists["Export"];
3676                         }
3677                         return ExportError;
3678                 }
3679         } else if (!lyxrc.tex_allows_spaces
3680                    && contains(filePath(), ' ')) {
3681                 Alert::error(_("File name error"),
3682                            _("The directory path to the document cannot contain spaces."));
3683                 return ExportTexPathHasSpaces;
3684         } else {
3685                 runparams.nice = false;
3686                 if (!makeLaTeXFile(FileName(filename), filePath(), runparams)) {
3687                         if (d->cloned_buffer_) {
3688                                 d->cloned_buffer_->d->errorLists["Export"] =
3689                                         d->errorLists["Export"];
3690                         }
3691                         return ExportError;
3692                 }
3693         }
3694
3695         string const error_type = (format == "program")
3696                 ? "Build" : params().bufferFormat();
3697         ErrorList & error_list = d->errorLists[error_type];
3698         string const ext = formats.extension(format);
3699         FileName const tmp_result_file(changeExtension(filename, ext));
3700         bool const success = converters.convert(this, FileName(filename),
3701                 tmp_result_file, FileName(absFileName()), backend_format, format,
3702                 error_list);
3703
3704         // Emit the signal to show the error list or copy it back to the
3705         // cloned Buffer so that it can be emitted afterwards.
3706         if (format != backend_format) {
3707                 if (d->cloned_buffer_) {
3708                         d->cloned_buffer_->d->errorLists[error_type] = 
3709                                 d->errorLists[error_type];
3710                 } else 
3711                         errors(error_type);
3712                 // also to the children, in case of master-buffer-view
3713                 ListOfBuffers clist = getDescendents();
3714                 ListOfBuffers::const_iterator cit = clist.begin();
3715                 ListOfBuffers::const_iterator const cen = clist.end();
3716                 for (; cit != cen; ++cit) {
3717                         if (d->cloned_buffer_) {
3718                                 // Enable reverse search by copying back the
3719                                 // texrow object to the cloned buffer.
3720                                 // FIXME: this is not thread safe.
3721                                 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
3722                                 (*cit)->d->cloned_buffer_->d->errorLists[error_type] = 
3723                                         (*cit)->d->errorLists[error_type];
3724                         } else
3725                                 (*cit)->errors(error_type, true);
3726                 }
3727         }
3728
3729         if (d->cloned_buffer_) {
3730                 // Enable reverse dvi or pdf to work by copying back the texrow
3731                 // object to the cloned buffer.
3732                 // FIXME: There is a possibility of concurrent access to texrow
3733                 // here from the main GUI thread that should be securized.
3734                 d->cloned_buffer_->d->texrow = d->texrow;
3735                 string const error_type = params().bufferFormat();
3736                 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
3737         }
3738
3739         if (!success)
3740                 return ExportConverterError;
3741
3742         if (put_in_tempdir) {
3743                 result_file = tmp_result_file.absFileName();
3744                 return ExportSuccess;
3745         }
3746
3747         if (dest_filename.empty())
3748                 result_file = changeExtension(d->exportFileName().absFileName(), ext);
3749         else
3750                 result_file = dest_filename;
3751         // We need to copy referenced files (e. g. included graphics
3752         // if format == "dvi") to the result dir.
3753         vector<ExportedFile> const files =
3754                 runparams.exportdata->externalFiles(format);
3755         string const dest = runparams.export_folder.empty() ?
3756                 onlyPath(result_file) : runparams.export_folder;
3757         bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
3758                                  : force_overwrite == ALL_FILES;
3759         CopyStatus status = use_force ? FORCE : SUCCESS;
3760         
3761         vector<ExportedFile>::const_iterator it = files.begin();
3762         vector<ExportedFile>::const_iterator const en = files.end();
3763         for (; it != en && status != CANCEL; ++it) {
3764                 string const fmt = formats.getFormatFromFile(it->sourceName);
3765                 string fixedName = it->exportName;
3766                 if (!runparams.export_folder.empty()) {
3767                         // Relative pathnames starting with ../ will be sanitized
3768                         // if exporting to a different folder
3769                         while (fixedName.substr(0, 3) == "../")
3770                                 fixedName = fixedName.substr(3, fixedName.length() - 3);
3771                 }
3772                 FileName fixedFileName = makeAbsPath(fixedName, dest);
3773                 fixedFileName.onlyPath().createPath();
3774                 status = copyFile(fmt, it->sourceName,
3775                         fixedFileName,
3776                         it->exportName, status == FORCE,
3777                         runparams.export_folder.empty());
3778         }
3779
3780         if (status == CANCEL) {
3781                 message(_("Document export cancelled."));
3782                 return ExportCancel;
3783         } 
3784         
3785         if (tmp_result_file.exists()) {
3786                 // Finally copy the main file
3787                 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
3788                                     : force_overwrite != NO_FILES;
3789                 if (status == SUCCESS && use_force)
3790                         status = FORCE;
3791                 status = copyFile(format, tmp_result_file,
3792                         FileName(result_file), result_file,
3793                         status == FORCE);
3794                 if (status == CANCEL) {
3795                         message(_("Document export cancelled."));
3796                         return ExportCancel;
3797                 } else {
3798                         message(bformat(_("Document exported as %1$s "
3799                                 "to file `%2$s'"),
3800                                 formats.prettyName(format),
3801                                 makeDisplayPath(result_file)));
3802                 }
3803         } else {
3804                 // This must be a dummy converter like fax (bug 1888)
3805                 message(bformat(_("Document exported as %1$s"),
3806                         formats.prettyName(format)));
3807         }
3808
3809         return ExportSuccess;
3810 }
3811
3812
3813 Buffer::ExportStatus Buffer::preview(string const & format) const
3814 {
3815         bool const update_unincluded =
3816                         params().maintain_unincluded_children
3817                         && !params().getIncludedChildren().empty();
3818         return preview(format, update_unincluded);
3819 }
3820
3821 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
3822 {
3823         MarkAsExporting exporting(this);
3824         string result_file;
3825         // (1) export with all included children (omit \includeonly)
3826         if (includeall) { 
3827                 ExportStatus const status = doExport(format, true, true, result_file);
3828                 if (status != ExportSuccess)
3829                         return status;
3830         }
3831         // (2) export with included children only
3832         ExportStatus const status = doExport(format, true, false, result_file);
3833         if (status != ExportSuccess)
3834                 return status;
3835         if (!formats.view(*this, FileName(result_file), format))
3836                 return PreviewError;
3837         return PreviewSuccess;
3838 }
3839
3840
3841 Buffer::ReadStatus Buffer::extractFromVC()
3842 {
3843         bool const found = LyXVC::file_not_found_hook(d->filename);
3844         if (!found)
3845                 return ReadFileNotFound;
3846         if (!d->filename.isReadableFile())
3847                 return ReadVCError;
3848         return ReadSuccess;
3849 }
3850
3851
3852 Buffer::ReadStatus Buffer::loadEmergency()
3853 {
3854         FileName const emergencyFile = getEmergencyFileName();
3855         if (!emergencyFile.exists() 
3856                   || emergencyFile.lastModified() <= d->filename.lastModified())
3857                 return ReadFileNotFound;
3858
3859         docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
3860         docstring const text = bformat(_("An emergency save of the document "
3861                 "%1$s exists.\n\nRecover emergency save?"), file);
3862         
3863         int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
3864                 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
3865
3866         switch (load_emerg)
3867         {
3868         case 0: {
3869                 docstring str;
3870                 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
3871                 bool const success = (ret_llf == ReadSuccess);
3872                 if (success) {
3873                         if (isReadonly()) {
3874                                 Alert::warning(_("File is read-only"),
3875                                         bformat(_("An emergency file is successfully loaded, "
3876                                         "but the original file %1$s is marked read-only. "
3877                                         "Please make sure to save the document as a different "
3878                                         "file."), from_utf8(d->filename.absFileName())));
3879                         }
3880                         markDirty();
3881                         str = _("Document was successfully recovered.");
3882                 } else
3883                         str = _("Document was NOT successfully recovered.");
3884                 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3885                         makeDisplayPath(emergencyFile.absFileName()));
3886
3887                 int const del_emerg = 
3888                         Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3889                                 _("&Remove"), _("&Keep"));
3890                 if (del_emerg == 0) {
3891                         emergencyFile.removeFile();
3892                         if (success)
3893                                 Alert::warning(_("Emergency file deleted"),
3894                                         _("Do not forget to save your file now!"), true);
3895                         }
3896                 return success ? ReadSuccess : ReadEmergencyFailure;
3897         }
3898         case 1: {
3899                 int const del_emerg =
3900                         Alert::prompt(_("Delete emergency file?"),
3901                                 _("Remove emergency file now?"), 1, 1,
3902                                 _("&Remove"), _("&Keep"));
3903                 if (del_emerg == 0)
3904                         emergencyFile.removeFile();
3905                 return ReadOriginal;
3906         }
3907
3908         default:
3909                 break;
3910         }
3911         return ReadCancel;
3912 }
3913
3914
3915 Buffer::ReadStatus Buffer::loadAutosave()
3916 {
3917         // Now check if autosave file is newer.
3918         FileName const autosaveFile = getAutosaveFileName();
3919         if (!autosaveFile.exists() 
3920                   || autosaveFile.lastModified() <= d->filename.lastModified()) 
3921                 return ReadFileNotFound;
3922
3923         docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
3924         docstring const text = bformat(_("The backup of the document %1$s " 
3925                 "is newer.\n\nLoad the backup instead?"), file);
3926         int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
3927                 _("&Load backup"), _("Load &original"), _("&Cancel"));
3928         
3929         switch (ret)
3930         {
3931         case 0: {
3932                 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
3933                 // the file is not saved if we load the autosave file.
3934                 if (ret_llf == ReadSuccess) {
3935                         if (isReadonly()) {
3936                                 Alert::warning(_("File is read-only"),
3937                                         bformat(_("A backup file is successfully loaded, "
3938                                         "but the original file %1$s is marked read-only. "
3939                                         "Please make sure to save the document as a "
3940                                         "different file."), 
3941                                         from_utf8(d->filename.absFileName())));
3942                         }
3943                         markDirty();
3944                         return ReadSuccess;
3945                 }
3946                 return ReadAutosaveFailure;
3947         }
3948         case 1:
3949                 // Here we delete the autosave
3950                 autosaveFile.removeFile();
3951                 return ReadOriginal;
3952         default:
3953                 break;
3954         }
3955         return ReadCancel;
3956 }
3957
3958
3959 Buffer::ReadStatus Buffer::loadLyXFile()
3960 {
3961         if (!d->filename.isReadableFile()) {
3962                 ReadStatus const ret_rvc = extractFromVC();
3963                 if (ret_rvc != ReadSuccess)
3964                         return ret_rvc;
3965         }
3966
3967         ReadStatus const ret_re = loadEmergency();
3968         if (ret_re == ReadSuccess || ret_re == ReadCancel)
3969                 return ret_re;
3970         
3971         ReadStatus const ret_ra = loadAutosave();
3972         if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
3973                 return ret_ra;
3974
3975         return loadThisLyXFile(d->filename);
3976 }
3977
3978
3979 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
3980 {
3981         return readFile(fn);
3982 }
3983
3984
3985 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3986 {
3987         TeXErrors::Errors::const_iterator it = terr.begin();
3988         TeXErrors::Errors::const_iterator end = terr.end();
3989         ListOfBuffers clist = getDescendents();
3990         ListOfBuffers::const_iterator cen = clist.end();
3991
3992         for (; it != end; ++it) {
3993                 int id_start = -1;
3994                 int pos_start = -1;
3995                 int errorRow = it->error_in_line;
3996                 Buffer const * buf = 0;
3997                 Impl const * p = d;
3998                 if (it->child_name.empty())
3999                     p->texrow.getIdFromRow(errorRow, id_start, pos_start);
4000                 else {
4001                         // The error occurred in a child
4002                         ListOfBuffers::const_iterator cit = clist.begin();
4003                         for (; cit != cen; ++cit) {
4004                                 string const child_name =
4005                                         DocFileName(changeExtension(
4006                                                 (*cit)->absFileName(), "tex")).
4007                                                         mangledFileName();
4008                                 if (it->child_name != child_name)
4009                                         continue;
4010                                 (*cit)->d->texrow.getIdFromRow(errorRow,
4011                                                         id_start, pos_start);
4012                                 if (id_start != -1) {
4013                                         buf = d->cloned_buffer_
4014                                                 ? (*cit)->d->cloned_buffer_->d->owner_
4015                                                 : (*cit)->d->owner_;
4016                                         p = (*cit)->d;
4017                                         break;
4018                                 }
4019                         }
4020                 }
4021                 int id_end = -1;
4022                 int pos_end = -1;
4023                 bool found;
4024                 do {
4025                         ++errorRow;
4026                         found = p->texrow.getIdFromRow(errorRow, id_end, pos_end);
4027                 } while (found && id_start == id_end && pos_start == pos_end);
4028
4029                 if (id_start != id_end) {
4030                         // Next registered position is outside the inset where
4031                         // the error occurred, so signal end-of-paragraph
4032                         pos_end = 0;
4033                 }
4034
4035                 errorList.push_back(ErrorItem(it->error_desc,
4036                         it->error_text, id_start, pos_start, pos_end, buf));
4037         }
4038 }
4039
4040
4041 void Buffer::setBuffersForInsets() const
4042 {
4043         inset().setBuffer(const_cast<Buffer &>(*this)); 
4044 }
4045
4046
4047 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4048 {
4049         // Use the master text class also for child documents
4050         Buffer const * const master = masterBuffer();
4051         DocumentClass const & textclass = master->params().documentClass();
4052         
4053         // do this only if we are the top-level Buffer
4054         if (master == this)
4055                 reloadBibInfoCache();
4056
4057         // keep the buffers to be children in this set. If the call from the
4058         // master comes back we can see which of them were actually seen (i.e.
4059         // via an InsetInclude). The remaining ones in the set need still be updated.
4060         static std::set<Buffer const *> bufToUpdate;
4061         if (scope == UpdateMaster) {
4062                 // If this is a child document start with the master
4063                 if (master != this) {
4064                         bufToUpdate.insert(this);
4065                         master->updateBuffer(UpdateMaster, utype);
4066                         // Do this here in case the master has no gui associated with it. Then, 
4067                         // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
4068                         if (!master->d->gui_)
4069                                 structureChanged();
4070
4071                         // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4072                         if (bufToUpdate.find(this) == bufToUpdate.end())
4073                                 return;
4074                 }
4075
4076                 // start over the counters in the master
4077                 textclass.counters().reset();
4078         }
4079
4080         // update will be done below for this buffer
4081         bufToUpdate.erase(this);
4082
4083         // update all caches
4084         clearReferenceCache();
4085         updateMacros();
4086
4087         Buffer & cbuf = const_cast<Buffer &>(*this);
4088
4089         LASSERT(!text().paragraphs().empty(), /**/);
4090
4091         // do the real work
4092         ParIterator parit = cbuf.par_iterator_begin();
4093         updateBuffer(parit, utype);
4094
4095         if (master != this)
4096                 // TocBackend update will be done later.
4097                 return;
4098
4099         d->bibinfo_cache_valid_ = true;
4100         d->cite_labels_valid_ = true;
4101         cbuf.tocBackend().update();
4102         if (scope == UpdateMaster)
4103                 cbuf.structureChanged();
4104 }
4105
4106
4107 static depth_type getDepth(DocIterator const & it)
4108 {
4109         depth_type depth = 0;
4110         for (size_t i = 0 ; i < it.depth() ; ++i)
4111                 if (!it[i].inset().inMathed())
4112                         depth += it[i].paragraph().getDepth() + 1;
4113         // remove 1 since the outer inset does not count
4114         return depth - 1;
4115 }
4116
4117 static depth_type getItemDepth(ParIterator const & it)
4118 {
4119         Paragraph const & par = *it;
4120         LabelType const labeltype = par.layout().labeltype;
4121
4122         if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4123                 return 0;
4124
4125         // this will hold the lowest depth encountered up to now.
4126         depth_type min_depth = getDepth(it);
4127         ParIterator prev_it = it;
4128         while (true) {
4129                 if (prev_it.pit())
4130                         --prev_it.top().pit();
4131                 else {
4132                         // start of nested inset: go to outer par
4133                         prev_it.pop_back();
4134                         if (prev_it.empty()) {
4135                                 // start of document: nothing to do
4136                                 return 0;
4137                         }
4138                 }
4139
4140                 // We search for the first paragraph with same label
4141                 // that is not more deeply nested.
4142                 Paragraph & prev_par = *prev_it;
4143                 depth_type const prev_depth = getDepth(prev_it);
4144                 if (labeltype == prev_par.layout().labeltype) {
4145                         if (prev_depth < min_depth)
4146                                 return prev_par.itemdepth + 1;
4147                         if (prev_depth == min_depth)
4148                                 return prev_par.itemdepth;
4149                 }
4150                 min_depth = min(min_depth, prev_depth);
4151                 // small optimization: if we are at depth 0, we won't
4152                 // find anything else
4153                 if (prev_depth == 0)
4154                         return 0;
4155         }
4156 }
4157
4158
4159 static bool needEnumCounterReset(ParIterator const & it)
4160 {
4161         Paragraph const & par = *it;
4162         LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
4163         depth_type const cur_depth = par.getDepth();
4164         ParIterator prev_it = it;
4165         while (prev_it.pit()) {
4166                 --prev_it.top().pit();
4167                 Paragraph const & prev_par = *prev_it;
4168                 if (prev_par.getDepth() <= cur_depth)
4169                         return  prev_par.layout().labeltype != LABEL_ENUMERATE;
4170         }
4171         // start of nested inset: reset
4172         return true;
4173 }
4174
4175
4176 // set the label of a paragraph. This includes the counters.
4177 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4178 {
4179         BufferParams const & bp = owner_->masterBuffer()->params();
4180         DocumentClass const & textclass = bp.documentClass();
4181         Paragraph & par = it.paragraph();
4182         Layout const & layout = par.layout();
4183         Counters & counters = textclass.counters();
4184
4185         if (par.params().startOfAppendix()) {
4186                 // FIXME: only the counter corresponding to toplevel
4187                 // sectioning should be reset
4188                 counters.reset();
4189                 counters.appendix(true);
4190         }
4191         par.params().appendix(counters.appendix());
4192
4193         // Compute the item depth of the paragraph
4194         par.itemdepth = getItemDepth(it);
4195
4196         if (layout.margintype == MARGIN_MANUAL) {
4197                 if (par.params().labelWidthString().empty())
4198                         par.params().labelWidthString(par.expandLabel(layout, bp));
4199         } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4200                 // we do not need to do anything here, since the empty case is
4201                 // handled during export.
4202         } else {
4203                 par.params().labelWidthString(docstring());
4204         }
4205
4206         switch(layout.labeltype) {
4207         case LABEL_COUNTER:
4208                 if (layout.toclevel <= bp.secnumdepth
4209                       && (layout.latextype != LATEX_ENVIRONMENT
4210                           || it.text()->isFirstInSequence(it.pit()))) {
4211                         if (counters.hasCounter(layout.counter))
4212                                 counters.step(layout.counter, utype);
4213                         par.params().labelString(par.expandLabel(layout, bp));
4214                 } else
4215                         par.params().labelString(docstring());
4216                 break;
4217
4218         case LABEL_ITEMIZE: {
4219                 // At some point of time we should do something more
4220                 // clever here, like:
4221                 //   par.params().labelString(
4222                 //    bp.user_defined_bullet(par.itemdepth).getText());
4223                 // for now, use a simple hardcoded label
4224                 docstring itemlabel;
4225                 switch (par.itemdepth) {
4226                 case 0:
4227                         itemlabel = char_type(0x2022);
4228                         break;
4229                 case 1:
4230                         itemlabel = char_type(0x2013);
4231                         break;
4232                 case 2:
4233                         itemlabel = char_type(0x2217);
4234                         break;
4235                 case 3:
4236                         itemlabel = char_type(0x2219); // or 0x00b7
4237                         break;
4238                 }
4239                 par.params().labelString(itemlabel);
4240                 break;
4241         }
4242
4243         case LABEL_ENUMERATE: {
4244                 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4245
4246                 switch (par.itemdepth) {
4247                 case 2:
4248                         enumcounter += 'i';
4249                 case 1:
4250                         enumcounter += 'i';
4251                 case 0:
4252                         enumcounter += 'i';
4253                         break;
4254                 case 3:
4255                         enumcounter += "iv";
4256                         break;
4257                 default:
4258                         // not a valid enumdepth...
4259                         break;
4260                 }
4261
4262                 // Maybe we have to reset the enumeration counter.
4263                 if (needEnumCounterReset(it))
4264                         counters.reset(enumcounter);
4265                 counters.step(enumcounter, utype);
4266
4267                 string const & lang = par.getParLanguage(bp)->code();
4268                 par.params().labelString(counters.theCounter(enumcounter, lang));
4269
4270                 break;
4271         }
4272
4273         case LABEL_SENSITIVE: {
4274                 string const & type = counters.current_float();
4275                 docstring full_label;
4276                 if (type.empty())
4277                         full_label = owner_->B_("Senseless!!! ");
4278                 else {
4279                         docstring name = owner_->B_(textclass.floats().getType(type).name());
4280                         if (counters.hasCounter(from_utf8(type))) {
4281                                 string const & lang = par.getParLanguage(bp)->code();
4282                                 counters.step(from_utf8(type), utype);
4283                                 full_label = bformat(from_ascii("%1$s %2$s:"), 
4284                                                      name, 
4285                                                      counters.theCounter(from_utf8(type), lang));
4286                         } else
4287                                 full_label = bformat(from_ascii("%1$s #:"), name);      
4288                 }
4289                 par.params().labelString(full_label);   
4290                 break;
4291         }
4292
4293         case LABEL_NO_LABEL:
4294                 par.params().labelString(docstring());
4295                 break;
4296
4297         case LABEL_MANUAL:
4298         case LABEL_TOP_ENVIRONMENT:
4299         case LABEL_CENTERED_TOP_ENVIRONMENT:
4300         case LABEL_STATIC:      
4301         case LABEL_BIBLIO:
4302                 par.params().labelString(par.expandLabel(layout, bp));
4303                 break;
4304         }
4305 }
4306
4307
4308 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4309 {
4310         LASSERT(parit.pit() == 0, /**/);
4311
4312         // Set the position of the text in the buffer to be able
4313         // to resolve macros in it.
4314         parit.text()->setMacrocontextPosition(parit);
4315
4316         depth_type maxdepth = 0;
4317         pit_type const lastpit = parit.lastpit();
4318         for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4319                 // reduce depth if necessary
4320                 parit->params().depth(min(parit->params().depth(), maxdepth));
4321                 maxdepth = parit->getMaxDepthAfter();
4322
4323                 if (utype == OutputUpdate) {
4324                         // track the active counters
4325                         // we have to do this for the master buffer, since the local
4326                         // buffer isn't tracking anything.
4327                         masterBuffer()->params().documentClass().counters().
4328                                         setActiveLayout(parit->layout());
4329                 }
4330                 
4331                 // set the counter for this paragraph
4332                 d->setLabel(parit, utype);
4333
4334                 // now the insets
4335                 InsetList::const_iterator iit = parit->insetList().begin();
4336                 InsetList::const_iterator end = parit->insetList().end();
4337                 for (; iit != end; ++iit) {
4338                         parit.pos() = iit->pos;
4339                         iit->inset->updateBuffer(parit, utype);
4340                 }
4341         }
4342 }
4343
4344
4345 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4346         WordLangTuple & word_lang, docstring_list & suggestions) const
4347 {
4348         int progress = 0;
4349         WordLangTuple wl;
4350         suggestions.clear();
4351         word_lang = WordLangTuple();
4352         bool const to_end = to.empty();
4353         DocIterator const end = to_end ? doc_iterator_end(this) : to;
4354         // OK, we start from here.
4355         for (; from != end; from.forwardPos()) {
4356                 // We are only interested in text so remove the math CursorSlice.
4357                 while (from.inMathed()) {
4358                         from.pop_back();
4359                         from.pos()++;
4360                 }
4361                 // If from is at the end of the document (which is possible
4362                 // when leaving the mathed) LyX will crash later otherwise.
4363                 if (from.atEnd() || (!to_end && from >= end))
4364                         break;
4365                 to = from;
4366                 from.paragraph().spellCheck();
4367                 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4368                 if (SpellChecker::misspelled(res)) {
4369                         word_lang = wl;
4370                         break;
4371                 }
4372
4373                 // Do not increase progress when from == to, otherwise the word
4374                 // count will be wrong.
4375                 if (from != to) {
4376                         from = to;
4377                         ++progress;
4378                 }
4379         }
4380         return progress;
4381 }
4382
4383
4384 Buffer::ReadStatus Buffer::reload()
4385 {
4386         setBusy(true);
4387         // c.f. bug http://www.lyx.org/trac/ticket/6587
4388         removeAutosaveFile();
4389         // e.g., read-only status could have changed due to version control
4390         d->filename.refresh();
4391         docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4392
4393         ReadStatus const status = loadLyXFile();
4394         if (status == ReadSuccess) {
4395                 updateBuffer();
4396                 changed(true);
4397                 updateTitles();
4398                 markClean();
4399                 message(bformat(_("Document %1$s reloaded."), disp_fn));
4400                 d->undo_.clear();
4401         } else {
4402                 message(bformat(_("Could not reload document %1$s."), disp_fn));
4403         }       
4404         setBusy(false);
4405         removePreviews();
4406         updatePreviews();
4407         errors("Parse");
4408         return status;
4409 }
4410
4411
4412 bool Buffer::saveAs(FileName const & fn)
4413 {
4414         FileName const old_name = fileName();
4415         FileName const old_auto = getAutosaveFileName();
4416         bool const old_unnamed = isUnnamed();
4417
4418         setFileName(fn);
4419         markDirty();
4420         setUnnamed(false);
4421
4422         if (save()) {
4423                 // bring the autosave file with us, just in case.
4424                 moveAutosaveFile(old_auto);
4425                 // validate version control data and
4426                 // correct buffer title
4427                 lyxvc().file_found_hook(fileName());
4428                 updateTitles();
4429                 // the file has now been saved to the new location.
4430                 // we need to check that the locations of child buffers
4431                 // are still valid.
4432                 checkChildBuffers();
4433                 return true;
4434         } else {
4435                 // save failed
4436                 // reset the old filename and unnamed state
4437                 setFileName(old_name);
4438                 setUnnamed(old_unnamed);
4439                 return false;
4440         }
4441 }
4442
4443
4444 // FIXME We could do better here, but it is complicated. What would be
4445 // nice is to offer either (a) to save the child buffer to an appropriate
4446 // location, so that it would "move with the master", or else (b) to update
4447 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4448 // complicated, because the code for this lives in GuiView.
4449 void Buffer::checkChildBuffers()
4450 {
4451         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4452         Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4453         for (; it != en; ++it) {
4454                 DocIterator dit = it->second;
4455                 Buffer * cbuf = const_cast<Buffer *>(it->first);
4456                 if (!cbuf || !theBufferList().isLoaded(cbuf))
4457                         continue;
4458                 Inset * inset = dit.nextInset();
4459                 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4460                 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4461                 docstring const & incfile = inset_inc->getParam("filename");
4462                 string oldloc = cbuf->absFileName();
4463                 string newloc = makeAbsPath(to_utf8(incfile),
4464                                 onlyPath(absFileName())).absFileName();
4465                 if (oldloc == newloc)
4466                         continue;
4467                 // the location of the child file is incorrect.
4468                 Alert::warning(_("Included File Invalid"),
4469                                 bformat(_("Saving this document to a new location has made the file:\n"
4470                                 "  %1$s\n"
4471                                 "inaccessible. You will need to update the included filename."),
4472                                 from_utf8(oldloc)));
4473                 cbuf->setParent(0);
4474                 inset_inc->setChildBuffer(0);
4475         }
4476         // invalidate cache of children
4477         d->children_positions.clear();
4478         d->position_to_children.clear();
4479 }
4480
4481 } // namespace lyx