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