]> git.lyx.org Git - lyx.git/blob - src/Buffer.cpp
cmake: move intl config file into source
[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(params().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 void Buffer::makeDocBookFile(FileName const & fname,
1490                               OutputParams const & runparams,
1491                               bool const body_only) const
1492 {
1493         LYXERR(Debug::LATEX, "makeDocBookFile...");
1494
1495         ofdocstream ofs;
1496         if (!openFileWrite(ofs, fname))
1497                 return;
1498
1499         // make sure we are ready to export
1500         // this needs to be done before we validate
1501         updateBuffer();
1502         updateMacroInstances(OutputUpdate);
1503
1504         writeDocBookSource(ofs, fname.absFileName(), runparams, body_only);
1505
1506         ofs.close();
1507         if (ofs.fail())
1508                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1509 }
1510
1511
1512 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1513                              OutputParams const & runparams,
1514                              bool const only_body) const
1515 {
1516         LaTeXFeatures features(*this, params(), runparams);
1517         validate(features);
1518
1519         d->texrow.reset();
1520
1521         DocumentClass const & tclass = params().documentClass();
1522         string const top_element = tclass.latexname();
1523
1524         if (!only_body) {
1525                 if (runparams.flavor == OutputParams::XML)
1526                         os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1527
1528                 // FIXME UNICODE
1529                 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1530
1531                 // FIXME UNICODE
1532                 if (! tclass.class_header().empty())
1533                         os << from_ascii(tclass.class_header());
1534                 else if (runparams.flavor == OutputParams::XML)
1535                         os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1536                             << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1537                 else
1538                         os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1539
1540                 docstring preamble = from_utf8(params().preamble);
1541                 if (runparams.flavor != OutputParams::XML ) {
1542                         preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1543                         preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1544                         preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1545                         preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1546                 }
1547
1548                 string const name = runparams.nice
1549                         ? changeExtension(absFileName(), ".sgml") : fname;
1550                 preamble += features.getIncludedFiles(name);
1551                 preamble += features.getLyXSGMLEntities();
1552
1553                 if (!preamble.empty()) {
1554                         os << "\n [ " << preamble << " ]";
1555                 }
1556                 os << ">\n\n";
1557         }
1558
1559         string top = top_element;
1560         top += " lang=\"";
1561         if (runparams.flavor == OutputParams::XML)
1562                 top += params().language->code();
1563         else
1564                 top += params().language->code().substr(0, 2);
1565         top += '"';
1566
1567         if (!params().options.empty()) {
1568                 top += ' ';
1569                 top += params().options;
1570         }
1571
1572         os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1573             << " file was created by LyX " << lyx_version
1574             << "\n  See http://www.lyx.org/ for more information -->\n";
1575
1576         params().documentClass().counters().reset();
1577
1578         sgml::openTag(os, top);
1579         os << '\n';
1580         docbookParagraphs(text(), *this, os, runparams);
1581         sgml::closeTag(os, top_element);
1582 }
1583
1584
1585 void Buffer::makeLyXHTMLFile(FileName const & fname,
1586                               OutputParams const & runparams,
1587                               bool const body_only) const
1588 {
1589         LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1590
1591         ofdocstream ofs;
1592         if (!openFileWrite(ofs, fname))
1593                 return;
1594
1595         // make sure we are ready to export
1596         // this has to be done before we validate
1597         updateBuffer(UpdateMaster, OutputUpdate);
1598         updateMacroInstances(OutputUpdate);
1599
1600         writeLyXHTMLSource(ofs, runparams, body_only);
1601
1602         ofs.close();
1603         if (ofs.fail())
1604                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1605 }
1606
1607
1608 void Buffer::writeLyXHTMLSource(odocstream & os,
1609                              OutputParams const & runparams,
1610                              bool const only_body) const
1611 {
1612         LaTeXFeatures features(*this, params(), runparams);
1613         validate(features);
1614         d->bibinfo_.makeCitationLabels(*this);
1615
1616         if (!only_body) {
1617                 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1618                    << "<!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"
1619                    // FIXME Language should be set properly.
1620                    << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1621                    << "<head>\n"
1622                    << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1623                    // FIXME Presumably need to set this right
1624                    << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1625
1626                 docstring const & doctitle = features.htmlTitle();
1627                 os << "<title>"
1628                    << (doctitle.empty() ? from_ascii("LyX Document") : doctitle)
1629                    << "</title>\n";
1630
1631                 os << "\n<!-- Text Class Preamble -->\n"
1632                    << features.getTClassHTMLPreamble()
1633                    << "\n<!-- Preamble Snippets -->\n"
1634                    << from_utf8(features.getPreambleSnippets());
1635
1636                 os << "\n<!-- Layout-provided Styles -->\n";
1637                 docstring const styleinfo = features.getTClassHTMLStyles();
1638                 if (!styleinfo.empty()) {
1639                         os << "<style type='text/css'>\n"
1640                                 << styleinfo
1641                                 << "</style>\n";
1642                 }
1643                 os << "</head>\n<body>\n";
1644         }
1645
1646         XHTMLStream xs(os);
1647         params().documentClass().counters().reset();
1648         xhtmlParagraphs(text(), *this, xs, runparams);
1649         if (!only_body)
1650                 os << "</body>\n</html>\n";
1651 }
1652
1653
1654 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1655 // Other flags: -wall -v0 -x
1656 int Buffer::runChktex()
1657 {
1658         setBusy(true);
1659
1660         // get LaTeX-Filename
1661         FileName const path(temppath());
1662         string const name = addName(path.absFileName(), latexName());
1663         string const org_path = filePath();
1664
1665         PathChanger p(path); // path to LaTeX file
1666         message(_("Running chktex..."));
1667
1668         // Generate the LaTeX file if neccessary
1669         OutputParams runparams(&params().encoding());
1670         runparams.flavor = OutputParams::LATEX;
1671         runparams.nice = false;
1672         runparams.linelen = lyxrc.plaintext_linelen;
1673         makeLaTeXFile(FileName(name), org_path, runparams);
1674
1675         TeXErrors terr;
1676         Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
1677         int const res = chktex.run(terr); // run chktex
1678
1679         if (res == -1) {
1680                 Alert::error(_("chktex failure"),
1681                              _("Could not run chktex successfully."));
1682         } else if (res > 0) {
1683                 ErrorList & errlist = d->errorLists["ChkTeX"];
1684                 errlist.clear();
1685                 bufferErrors(terr, errlist);
1686         }
1687
1688         setBusy(false);
1689
1690         errors("ChkTeX");
1691
1692         return res;
1693 }
1694
1695
1696 void Buffer::validate(LaTeXFeatures & features) const
1697 {
1698         params().validate(features);
1699
1700         for_each(paragraphs().begin(), paragraphs().end(),
1701                  bind(&Paragraph::validate, _1, ref(features)));
1702
1703         if (lyxerr.debugging(Debug::LATEX)) {
1704                 features.showStruct();
1705         }
1706 }
1707
1708
1709 void Buffer::getLabelList(vector<docstring> & list) const
1710 {
1711         // If this is a child document, use the master's list instead.
1712         if (parent()) {
1713                 masterBuffer()->getLabelList(list);
1714                 return;
1715         }
1716
1717         list.clear();
1718         Toc & toc = d->toc_backend.toc("label");
1719         TocIterator toc_it = toc.begin();
1720         TocIterator end = toc.end();
1721         for (; toc_it != end; ++toc_it) {
1722                 if (toc_it->depth() == 0)
1723                         list.push_back(toc_it->str());
1724         }
1725 }
1726
1727
1728 void Buffer::updateBibfilesCache(UpdateScope scope) const
1729 {
1730         // FIXME This is probably unnecssary, given where we call this.
1731         // If this is a child document, use the parent's cache instead.
1732         if (parent() && scope != UpdateChildOnly) {
1733                 masterBuffer()->updateBibfilesCache();
1734                 return;
1735         }
1736
1737         d->bibfiles_cache_.clear();
1738         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1739                 if (it->lyxCode() == BIBTEX_CODE) {
1740                         InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
1741                         support::FileNameList const bibfiles = inset.getBibFiles();
1742                         d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1743                                 bibfiles.begin(),
1744                                 bibfiles.end());
1745                 } else if (it->lyxCode() == INCLUDE_CODE) {
1746                         InsetInclude & inset = static_cast<InsetInclude &>(*it);
1747                         Buffer const * const incbuf = inset.getChildBuffer();
1748                         if (!incbuf)
1749                                 continue;
1750                         support::FileNameList const & bibfiles =
1751                                         incbuf->getBibfilesCache(UpdateChildOnly);
1752                         if (!bibfiles.empty()) {
1753                                 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1754                                         bibfiles.begin(),
1755                                         bibfiles.end());
1756                         }
1757                 }
1758         }
1759         d->bibfile_cache_valid_ = true;
1760         d->bibinfo_cache_valid_ = false;
1761         d->cite_labels_valid_ = false;
1762 }
1763
1764
1765 void Buffer::invalidateBibinfoCache() const
1766 {
1767         d->bibinfo_cache_valid_ = false;
1768         d->cite_labels_valid_ = false;
1769         // also invalidate the cache for the parent buffer
1770         Buffer const * const pbuf = d->parent();
1771         if (pbuf)
1772                 pbuf->invalidateBibinfoCache();
1773 }
1774
1775
1776 void Buffer::invalidateBibfileCache() const
1777 {
1778         d->bibfile_cache_valid_ = false;
1779         d->bibinfo_cache_valid_ = false;
1780         d->cite_labels_valid_ = false;
1781         // also invalidate the cache for the parent buffer
1782         Buffer const * const pbuf = d->parent();
1783         if (pbuf)
1784                 pbuf->invalidateBibfileCache();
1785 }
1786
1787
1788 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1789 {
1790         // FIXME This is probably unnecessary, given where we call this.
1791         // If this is a child document, use the master's cache instead.
1792         Buffer const * const pbuf = masterBuffer();
1793         if (pbuf != this && scope != UpdateChildOnly)
1794                 return pbuf->getBibfilesCache();
1795
1796         if (!d->bibfile_cache_valid_)
1797                 this->updateBibfilesCache(scope);
1798
1799         return d->bibfiles_cache_;
1800 }
1801
1802
1803 BiblioInfo const & Buffer::masterBibInfo() const
1804 {
1805         Buffer const * const tmp = masterBuffer();
1806         if (tmp != this)
1807                 return tmp->masterBibInfo();
1808         return d->bibinfo_;
1809 }
1810
1811
1812 void Buffer::checkIfBibInfoCacheIsValid() const
1813 {
1814         // use the master's cache
1815         Buffer const * const tmp = masterBuffer();
1816         if (tmp != this) {
1817                 tmp->checkIfBibInfoCacheIsValid();
1818                 return;
1819         }
1820
1821         // compare the cached timestamps with the actual ones.
1822         FileNameList const & bibfiles_cache = getBibfilesCache();
1823         FileNameList::const_iterator ei = bibfiles_cache.begin();
1824         FileNameList::const_iterator en = bibfiles_cache.end();
1825         for (; ei != en; ++ ei) {
1826                 time_t lastw = ei->lastModified();
1827                 time_t prevw = d->bibfile_status_[*ei];
1828                 if (lastw != prevw) {
1829                         d->bibinfo_cache_valid_ = false;
1830                         d->cite_labels_valid_ = false;
1831                         d->bibfile_status_[*ei] = lastw;
1832                 }
1833         }
1834 }
1835
1836
1837 void Buffer::reloadBibInfoCache() const
1838 {
1839         // use the master's cache
1840         Buffer const * const tmp = masterBuffer();
1841         if (tmp != this) {
1842                 tmp->reloadBibInfoCache();
1843                 return;
1844         }
1845
1846         checkIfBibInfoCacheIsValid();
1847         if (d->bibinfo_cache_valid_)
1848                 return;
1849
1850         d->bibinfo_.clear();
1851         collectBibKeys();
1852         d->bibinfo_cache_valid_ = true;
1853 }
1854
1855
1856 void Buffer::collectBibKeys() const
1857 {
1858         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1859                 it->collectBibKeys(it);
1860 }
1861
1862
1863 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
1864 {
1865         Buffer const * tmp = masterBuffer();
1866         BiblioInfo & masterbi = (tmp == this) ?
1867                 d->bibinfo_ : tmp->d->bibinfo_;
1868         masterbi.mergeBiblioInfo(bi);
1869 }
1870
1871
1872 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
1873 {
1874         Buffer const * tmp = masterBuffer();
1875         BiblioInfo & masterbi = (tmp == this) ?
1876                 d->bibinfo_ : tmp->d->bibinfo_;
1877         masterbi[key] = bi;
1878 }
1879
1880
1881 bool Buffer::citeLabelsValid() const
1882 {
1883         return masterBuffer()->d->cite_labels_valid_;
1884 }
1885
1886
1887 bool Buffer::isDepClean(string const & name) const
1888 {
1889         DepClean::const_iterator const it = d->dep_clean.find(name);
1890         if (it == d->dep_clean.end())
1891                 return true;
1892         return it->second;
1893 }
1894
1895
1896 void Buffer::markDepClean(string const & name)
1897 {
1898         d->dep_clean[name] = true;
1899 }
1900
1901
1902 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1903 {
1904         if (isInternal()) {
1905                 // FIXME? if there is an Buffer LFUN that can be dispatched even
1906                 // if internal, put a switch '(cmd.action)' here.
1907                 return false;
1908         }
1909
1910         bool enable = true;
1911
1912         switch (cmd.action()) {
1913
1914                 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1915                         flag.setOnOff(isReadonly());
1916                         break;
1917
1918                 // FIXME: There is need for a command-line import.
1919                 //case LFUN_BUFFER_IMPORT:
1920
1921                 case LFUN_BUFFER_AUTO_SAVE:
1922                         break;
1923
1924                 case LFUN_BUFFER_EXPORT_CUSTOM:
1925                         // FIXME: Nothing to check here?
1926                         break;
1927
1928                 case LFUN_BUFFER_EXPORT: {
1929                         docstring const arg = cmd.argument();
1930                         enable = arg == "custom" || params().isExportable(to_utf8(arg));
1931                         if (!enable)
1932                                 flag.message(bformat(
1933                                         _("Don't know how to export to format: %1$s"), arg));
1934                         break;
1935                 }
1936
1937                 case LFUN_BUFFER_CHKTEX:
1938                         enable = params().isLatex() && !lyxrc.chktex_command.empty();
1939                         break;
1940
1941                 case LFUN_BUILD_PROGRAM:
1942                         enable = params().isExportable("program");
1943                         break;
1944
1945                 case LFUN_BRANCH_ACTIVATE: 
1946                 case LFUN_BRANCH_DEACTIVATE: {
1947                         BranchList const & branchList = params().branchlist();
1948                         docstring const branchName = cmd.argument();
1949                         enable = !branchName.empty() && branchList.find(branchName);
1950                         break;
1951                 }
1952
1953                 case LFUN_BRANCH_ADD:
1954                 case LFUN_BRANCHES_RENAME:
1955                 case LFUN_BUFFER_PRINT:
1956                         // if no Buffer is present, then of course we won't be called!
1957                         break;
1958
1959                 case LFUN_BUFFER_LANGUAGE:
1960                         enable = !isReadonly();
1961                         break;
1962
1963                 default:
1964                         return false;
1965         }
1966         flag.setEnabled(enable);
1967         return true;
1968 }
1969
1970
1971 void Buffer::dispatch(string const & command, DispatchResult & result)
1972 {
1973         return dispatch(lyxaction.lookupFunc(command), result);
1974 }
1975
1976
1977 // NOTE We can end up here even if we have no GUI, because we are called
1978 // by LyX::exec to handled command-line requests. So we may need to check 
1979 // whether we have a GUI or not. The boolean use_gui holds this information.
1980 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1981 {
1982         if (isInternal()) {
1983                 // FIXME? if there is an Buffer LFUN that can be dispatched even
1984                 // if internal, put a switch '(cmd.action())' here.
1985                 dr.dispatched(false);
1986                 return;
1987         }
1988         string const argument = to_utf8(func.argument());
1989         // We'll set this back to false if need be.
1990         bool dispatched = true;
1991         undo().beginUndoGroup();
1992
1993         switch (func.action()) {
1994         case LFUN_BUFFER_TOGGLE_READ_ONLY:
1995                 if (lyxvc().inUse())
1996                         lyxvc().toggleReadOnly();
1997                 else
1998                         setReadonly(!isReadonly());
1999                 break;
2000
2001         case LFUN_BUFFER_EXPORT: {
2002                 bool success = doExport(argument, false, false);
2003                 dr.setError(!success);
2004                 if (!success)
2005                         dr.setMessage(bformat(_("Error exporting to format: %1$s."), 
2006                                               func.argument()));
2007                 break;
2008         }
2009
2010         case LFUN_BUILD_PROGRAM:
2011                 doExport("program", true, false);
2012                 break;
2013
2014         case LFUN_BUFFER_CHKTEX:
2015                 runChktex();
2016                 break;
2017
2018         case LFUN_BUFFER_EXPORT_CUSTOM: {
2019                 string format_name;
2020                 string command = split(argument, format_name, ' ');
2021                 Format const * format = formats.getFormat(format_name);
2022                 if (!format) {
2023                         lyxerr << "Format \"" << format_name
2024                                 << "\" not recognized!"
2025                                 << endl;
2026                         break;
2027                 }
2028
2029                 // The name of the file created by the conversion process
2030                 string filename;
2031
2032                 // Output to filename
2033                 if (format->name() == "lyx") {
2034                         string const latexname = latexName(false);
2035                         filename = changeExtension(latexname,
2036                                 format->extension());
2037                         filename = addName(temppath(), filename);
2038
2039                         if (!writeFile(FileName(filename)))
2040                                 break;
2041
2042                 } else {
2043                         doExport(format_name, true, false, filename);
2044                 }
2045
2046                 // Substitute $$FName for filename
2047                 if (!contains(command, "$$FName"))
2048                         command = "( " + command + " ) < $$FName";
2049                 command = subst(command, "$$FName", filename);
2050
2051                 // Execute the command in the background
2052                 Systemcall call;
2053                 call.startscript(Systemcall::DontWait, command, filePath());
2054                 break;
2055         }
2056
2057         // FIXME: There is need for a command-line import.
2058         /*
2059         case LFUN_BUFFER_IMPORT:
2060                 doImport(argument);
2061                 break;
2062         */
2063
2064         case LFUN_BUFFER_AUTO_SAVE:
2065                 autoSave();
2066                 resetAutosaveTimers();
2067                 break;
2068
2069         case LFUN_BRANCH_ADD: {
2070                 docstring branch_name = func.argument();
2071                 if (branch_name.empty()) {
2072                         dispatched = false;
2073                         break;
2074                 }
2075                 BranchList & branch_list = params().branchlist();
2076                 vector<docstring> const branches =
2077                         getVectorFromString(branch_name, branch_list.separator());
2078                 docstring msg;
2079                 for (vector<docstring>::const_iterator it = branches.begin();
2080                      it != branches.end(); ++it) {
2081                         branch_name = *it;
2082                         Branch * branch = branch_list.find(branch_name);
2083                         if (branch) {
2084                                 LYXERR0("Branch " << branch_name << " already exists.");
2085                                 dr.setError(true);
2086                                 if (!msg.empty())
2087                                         msg += ("\n");
2088                                 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2089                         } else {
2090                                 branch_list.add(branch_name);
2091                                 branch = branch_list.find(branch_name);
2092                                 string const x11hexname = X11hexname(branch->color());
2093                                 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2094                                 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2095                                 dr.setError(false);
2096                                 dr.screenUpdate(Update::Force);
2097                         }
2098                 }
2099                 if (!msg.empty())
2100                         dr.setMessage(msg);
2101                 break;
2102         }
2103
2104         case LFUN_BRANCH_ACTIVATE:
2105         case LFUN_BRANCH_DEACTIVATE: {
2106                 BranchList & branchList = params().branchlist();
2107                 docstring const branchName = func.argument();
2108                 // the case without a branch name is handled elsewhere
2109                 if (branchName.empty()) {
2110                         dispatched = false;
2111                         break;
2112                 }
2113                 Branch * branch = branchList.find(branchName);
2114                 if (!branch) {
2115                         LYXERR0("Branch " << branchName << " does not exist.");
2116                         dr.setError(true);
2117                         docstring const msg = 
2118                                 bformat(_("Branch \"%1$s\" does not exist."), branchName);
2119                         dr.setMessage(msg);
2120                 } else {
2121                         branch->setSelected(func.action() == LFUN_BRANCH_ACTIVATE);
2122                         dr.setError(false);
2123                         dr.screenUpdate(Update::Force);
2124                         dr.forceBufferUpdate();
2125                 }
2126                 break;
2127         }
2128
2129         case LFUN_BRANCHES_RENAME: {
2130                 if (func.argument().empty())
2131                         break;
2132
2133                 docstring const oldname = from_utf8(func.getArg(0));
2134                 docstring const newname = from_utf8(func.getArg(1));
2135                 InsetIterator it  = inset_iterator_begin(inset());
2136                 InsetIterator const end = inset_iterator_end(inset());
2137                 bool success = false;
2138                 for (; it != end; ++it) {
2139                         if (it->lyxCode() == BRANCH_CODE) {
2140                                 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2141                                 if (ins.branch() == oldname) {
2142                                         undo().recordUndo(it);
2143                                         ins.rename(newname);
2144                                         success = true;
2145                                         continue;
2146                                 }
2147                         }
2148                         if (it->lyxCode() == INCLUDE_CODE) {
2149                                 // get buffer of external file
2150                                 InsetInclude const & ins =
2151                                         static_cast<InsetInclude const &>(*it);
2152                                 Buffer * child = ins.getChildBuffer();
2153                                 if (!child)
2154                                         continue;
2155                                 child->dispatch(func, dr);
2156                         }
2157                 }
2158
2159                 if (success) {
2160                         dr.screenUpdate(Update::Force);
2161                         dr.forceBufferUpdate();
2162                 }
2163                 break;
2164         }
2165
2166         case LFUN_BUFFER_PRINT: {
2167                 // we'll assume there's a problem until we succeed
2168                 dr.setError(true); 
2169                 string target = func.getArg(0);
2170                 string target_name = func.getArg(1);
2171                 string command = func.getArg(2);
2172
2173                 if (target.empty()
2174                     || target_name.empty()
2175                     || command.empty()) {
2176                         LYXERR0("Unable to parse " << func.argument());
2177                         docstring const msg = 
2178                                 bformat(_("Unable to parse \"%1$s\""), func.argument());
2179                         dr.setMessage(msg);
2180                         break;
2181                 }
2182                 if (target != "printer" && target != "file") {
2183                         LYXERR0("Unrecognized target \"" << target << '"');
2184                         docstring const msg = 
2185                                 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2186                         dr.setMessage(msg);
2187                         break;
2188                 }
2189
2190                 bool const update_unincluded =
2191                                 params().maintain_unincluded_children
2192                                 && !params().getIncludedChildren().empty();
2193                 if (!doExport("dvi", true, update_unincluded)) {
2194                         showPrintError(absFileName());
2195                         dr.setMessage(_("Error exporting to DVI."));
2196                         break;
2197                 }
2198
2199                 // Push directory path.
2200                 string const path = temppath();
2201                 // Prevent the compiler from optimizing away p
2202                 FileName pp(path);
2203                 PathChanger p(pp);
2204
2205                 // there are three cases here:
2206                 // 1. we print to a file
2207                 // 2. we print directly to a printer
2208                 // 3. we print using a spool command (print to file first)
2209                 Systemcall one;
2210                 int res = 0;
2211                 string const dviname = changeExtension(latexName(true), "dvi");
2212
2213                 if (target == "printer") {
2214                         if (!lyxrc.print_spool_command.empty()) {
2215                                 // case 3: print using a spool
2216                                 string const psname = changeExtension(dviname,".ps");
2217                                 command += ' ' + lyxrc.print_to_file
2218                                         + quoteName(psname)
2219                                         + ' '
2220                                         + quoteName(dviname);
2221
2222                                 string command2 = lyxrc.print_spool_command + ' ';
2223                                 if (target_name != "default") {
2224                                         command2 += lyxrc.print_spool_printerprefix
2225                                                 + target_name
2226                                                 + ' ';
2227                                 }
2228                                 command2 += quoteName(psname);
2229                                 // First run dvips.
2230                                 // If successful, then spool command
2231                                 res = one.startscript(Systemcall::Wait, command,
2232                                                       filePath());
2233
2234                                 if (res == 0) {
2235                                         // If there's no GUI, we have to wait on this command. Otherwise,
2236                                         // LyX deletes the temporary directory, and with it the spooled
2237                                         // file, before it can be printed!!
2238                                         Systemcall::Starttype stype = use_gui ?
2239                                                 Systemcall::DontWait : Systemcall::Wait;
2240                                         res = one.startscript(stype, command2,
2241                                                               filePath());
2242                                 }
2243                         } else {
2244                                 // case 2: print directly to a printer
2245                                 if (target_name != "default")
2246                                         command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2247                                 // as above....
2248                                 Systemcall::Starttype stype = use_gui ?
2249                                         Systemcall::DontWait : Systemcall::Wait;
2250                                 res = one.startscript(stype, command +
2251                                                 quoteName(dviname), filePath());
2252                         }
2253
2254                 } else {
2255                         // case 1: print to a file
2256                         FileName const filename(makeAbsPath(target_name, filePath()));
2257                         FileName const dvifile(makeAbsPath(dviname, path));
2258                         if (filename.exists()) {
2259                                 docstring text = bformat(
2260                                         _("The file %1$s already exists.\n\n"
2261                                           "Do you want to overwrite that file?"),
2262                                         makeDisplayPath(filename.absFileName()));
2263                                 if (Alert::prompt(_("Overwrite file?"),
2264                                                   text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2265                                         break;
2266                         }
2267                         command += ' ' + lyxrc.print_to_file
2268                                 + quoteName(filename.toFilesystemEncoding())
2269                                 + ' '
2270                                 + quoteName(dvifile.toFilesystemEncoding());
2271                         // as above....
2272                         Systemcall::Starttype stype = use_gui ?
2273                                 Systemcall::DontWait : Systemcall::Wait;
2274                         res = one.startscript(stype, command, filePath());
2275                 }
2276
2277                 if (res == 0) 
2278                         dr.setError(false);
2279                 else {
2280                         dr.setMessage(_("Error running external commands."));
2281                         showPrintError(absFileName());
2282                 }
2283                 break;
2284         }
2285
2286         case LFUN_BUFFER_LANGUAGE: {
2287                 Language const * oldL = params().language;
2288                 Language const * newL = languages.getLanguage(argument);
2289                 if (!newL || oldL == newL)
2290                         break;
2291                 if (oldL->rightToLeft() == newL->rightToLeft() && !isMultiLingual()) {
2292                         changeLanguage(oldL, newL);
2293                         dr.forceBufferUpdate();
2294                 }
2295                 break;
2296         }
2297
2298         default:
2299                 dispatched = false;
2300                 break;
2301         }
2302         dr.dispatched(dispatched);
2303         undo().endUndoGroup();
2304 }
2305
2306
2307 void Buffer::changeLanguage(Language const * from, Language const * to)
2308 {
2309         LASSERT(from, /**/);
2310         LASSERT(to, /**/);
2311
2312         for_each(par_iterator_begin(),
2313                  par_iterator_end(),
2314                  bind(&Paragraph::changeLanguage, _1, params(), from, to));
2315 }
2316
2317
2318 bool Buffer::isMultiLingual() const
2319 {
2320         ParConstIterator end = par_iterator_end();
2321         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2322                 if (it->isMultiLingual(params()))
2323                         return true;
2324
2325         return false;
2326 }
2327
2328
2329 std::set<Language const *> Buffer::getLanguages() const
2330 {
2331         std::set<Language const *> languages;
2332         getLanguages(languages);
2333         return languages;
2334 }
2335
2336
2337 void Buffer::getLanguages(std::set<Language const *> & languages) const
2338 {
2339         ParConstIterator end = par_iterator_end();
2340         // add the buffer language, even if it's not actively used
2341         languages.insert(language());
2342         // iterate over the paragraphs
2343         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2344                 it->getLanguages(languages);
2345         // also children
2346         ListOfBuffers clist = getDescendents();
2347         ListOfBuffers::const_iterator cit = clist.begin();
2348         ListOfBuffers::const_iterator const cen = clist.end();
2349         for (; cit != cen; ++cit)
2350                 (*cit)->getLanguages(languages);
2351 }
2352
2353
2354 DocIterator Buffer::getParFromID(int const id) const
2355 {
2356         Buffer * buf = const_cast<Buffer *>(this);
2357         if (id < 0) {
2358                 // John says this is called with id == -1 from undo
2359                 lyxerr << "getParFromID(), id: " << id << endl;
2360                 return doc_iterator_end(buf);
2361         }
2362
2363         for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2364                 if (it.paragraph().id() == id)
2365                         return it;
2366
2367         return doc_iterator_end(buf);
2368 }
2369
2370
2371 bool Buffer::hasParWithID(int const id) const
2372 {
2373         return !getParFromID(id).atEnd();
2374 }
2375
2376
2377 ParIterator Buffer::par_iterator_begin()
2378 {
2379         return ParIterator(doc_iterator_begin(this));
2380 }
2381
2382
2383 ParIterator Buffer::par_iterator_end()
2384 {
2385         return ParIterator(doc_iterator_end(this));
2386 }
2387
2388
2389 ParConstIterator Buffer::par_iterator_begin() const
2390 {
2391         return ParConstIterator(doc_iterator_begin(this));
2392 }
2393
2394
2395 ParConstIterator Buffer::par_iterator_end() const
2396 {
2397         return ParConstIterator(doc_iterator_end(this));
2398 }
2399
2400
2401 Language const * Buffer::language() const
2402 {
2403         return params().language;
2404 }
2405
2406
2407 docstring const Buffer::B_(string const & l10n) const
2408 {
2409         return params().B_(l10n);
2410 }
2411
2412
2413 bool Buffer::isClean() const
2414 {
2415         return d->lyx_clean;
2416 }
2417
2418
2419 bool Buffer::isExternallyModified(CheckMethod method) const
2420 {
2421         LASSERT(d->filename.exists(), /**/);
2422         // if method == timestamp, check timestamp before checksum
2423         return (method == checksum_method
2424                 || d->timestamp_ != d->filename.lastModified())
2425                 && d->checksum_ != d->filename.checksum();
2426 }
2427
2428
2429 void Buffer::saveCheckSum() const
2430 {
2431         FileName const & file = d->filename;
2432
2433         file.refresh();
2434         if (file.exists()) {
2435                 d->timestamp_ = file.lastModified();
2436                 d->checksum_ = file.checksum();
2437         } else {
2438                 // in the case of save to a new file.
2439                 d->timestamp_ = 0;
2440                 d->checksum_ = 0;
2441         }
2442 }
2443
2444
2445 void Buffer::markClean() const
2446 {
2447         if (!d->lyx_clean) {
2448                 d->lyx_clean = true;
2449                 updateTitles();
2450         }
2451         // if the .lyx file has been saved, we don't need an
2452         // autosave
2453         d->bak_clean = true;
2454         d->undo_.markDirty();
2455 }
2456
2457
2458 void Buffer::setUnnamed(bool flag)
2459 {
2460         d->unnamed = flag;
2461 }
2462
2463
2464 bool Buffer::isUnnamed() const
2465 {
2466         return d->unnamed;
2467 }
2468
2469
2470 /// \note
2471 /// Don't check unnamed, here: isInternal() is used in
2472 /// newBuffer(), where the unnamed flag has not been set by anyone
2473 /// yet. Also, for an internal buffer, there should be no need for
2474 /// retrieving fileName() nor for checking if it is unnamed or not.
2475 bool Buffer::isInternal() const
2476 {
2477         return fileName().extension() == "internal";
2478 }
2479
2480
2481 void Buffer::markDirty()
2482 {
2483         if (d->lyx_clean) {
2484                 d->lyx_clean = false;
2485                 updateTitles();
2486         }
2487         d->bak_clean = false;
2488
2489         DepClean::iterator it = d->dep_clean.begin();
2490         DepClean::const_iterator const end = d->dep_clean.end();
2491
2492         for (; it != end; ++it)
2493                 it->second = false;
2494 }
2495
2496
2497 FileName Buffer::fileName() const
2498 {
2499         return d->filename;
2500 }
2501
2502
2503 string Buffer::absFileName() const
2504 {
2505         return d->filename.absFileName();
2506 }
2507
2508
2509 string Buffer::filePath() const
2510 {
2511         return d->filename.onlyPath().absFileName() + "/";
2512 }
2513
2514
2515 bool Buffer::isReadonly() const
2516 {
2517         return d->read_only;
2518 }
2519
2520
2521 void Buffer::setParent(Buffer const * buffer)
2522 {
2523         // Avoids recursive include.
2524         d->setParent(buffer == this ? 0 : buffer);
2525         updateMacros();
2526 }
2527
2528
2529 Buffer const * Buffer::parent() const
2530 {
2531         return d->parent();
2532 }
2533
2534
2535 ListOfBuffers Buffer::allRelatives() const
2536 {
2537         ListOfBuffers lb = masterBuffer()->getDescendents();
2538         lb.push_front(const_cast<Buffer *>(masterBuffer()));
2539         return lb;
2540 }
2541
2542
2543 Buffer const * Buffer::masterBuffer() const
2544 {
2545         // FIXME Should be make sure we are not in some kind
2546         // of recursive include? A -> B -> A will crash this.
2547         Buffer const * const pbuf = d->parent();
2548         if (!pbuf)
2549                 return this;
2550
2551         return pbuf->masterBuffer();
2552 }
2553
2554
2555 bool Buffer::isChild(Buffer * child) const
2556 {
2557         return d->children_positions.find(child) != d->children_positions.end();
2558 }
2559
2560
2561 DocIterator Buffer::firstChildPosition(Buffer const * child)
2562 {
2563         Impl::BufferPositionMap::iterator it;
2564         it = d->children_positions.find(child);
2565         if (it == d->children_positions.end())
2566                 return DocIterator(this);
2567         return it->second;
2568 }
2569
2570
2571 bool Buffer::hasChildren() const
2572 {
2573         return !d->children_positions.empty();  
2574 }
2575
2576
2577 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
2578 {
2579         // loop over children
2580         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2581         Impl::BufferPositionMap::iterator end = d->children_positions.end();
2582         for (; it != end; ++it) {
2583                 Buffer * child = const_cast<Buffer *>(it->first);
2584                 // No duplicates
2585                 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
2586                 if (bit != clist.end())
2587                         continue;
2588                 clist.push_back(child);
2589                 if (grand_children) 
2590                         // there might be grandchildren
2591                         child->collectChildren(clist, true);
2592         }
2593 }
2594
2595
2596 ListOfBuffers Buffer::getChildren() const
2597 {
2598         ListOfBuffers v;
2599         collectChildren(v, false);
2600         return v;
2601 }
2602
2603
2604 ListOfBuffers Buffer::getDescendents() const
2605 {
2606         ListOfBuffers v;
2607         collectChildren(v, true);
2608         return v;
2609 }
2610
2611
2612 template<typename M>
2613 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
2614 {
2615         if (m.empty())
2616                 return m.end();
2617
2618         typename M::const_iterator it = m.lower_bound(x);
2619         if (it == m.begin())
2620                 return m.end();
2621
2622         it--;
2623         return it;
2624 }
2625
2626
2627 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
2628                                          DocIterator const & pos) const
2629 {
2630         LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2631
2632         // if paragraphs have no macro context set, pos will be empty
2633         if (pos.empty())
2634                 return 0;
2635
2636         // we haven't found anything yet
2637         DocIterator bestPos = owner_->par_iterator_begin();
2638         MacroData const * bestData = 0;
2639
2640         // find macro definitions for name
2641         NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
2642         if (nameIt != macros.end()) {
2643                 // find last definition in front of pos or at pos itself
2644                 PositionScopeMacroMap::const_iterator it
2645                         = greatest_below(nameIt->second, pos);
2646                 if (it != nameIt->second.end()) {
2647                         while (true) {
2648                                 // scope ends behind pos?
2649                                 if (pos < it->second.first) {
2650                                         // Looks good, remember this. If there
2651                                         // is no external macro behind this,
2652                                         // we found the right one already.
2653                                         bestPos = it->first;
2654                                         bestData = &it->second.second;
2655                                         break;
2656                                 }
2657
2658                                 // try previous macro if there is one
2659                                 if (it == nameIt->second.begin())
2660                                         break;
2661                                 it--;
2662                         }
2663                 }
2664         }
2665
2666         // find macros in included files
2667         PositionScopeBufferMap::const_iterator it
2668                 = greatest_below(position_to_children, pos);
2669         if (it == position_to_children.end())
2670                 // no children before
2671                 return bestData;
2672
2673         while (true) {
2674                 // do we know something better (i.e. later) already?
2675                 if (it->first < bestPos )
2676                         break;
2677
2678                 // scope ends behind pos?
2679                 if (pos < it->second.first
2680                         && (cloned_buffer_ ||
2681                             theBufferList().isLoaded(it->second.second))) {
2682                         // look for macro in external file
2683                         macro_lock = true;
2684                         MacroData const * data
2685                                 = it->second.second->getMacro(name, false);
2686                         macro_lock = false;
2687                         if (data) {
2688                                 bestPos = it->first;
2689                                 bestData = data;
2690                                 break;
2691                         }
2692                 }
2693
2694                 // try previous file if there is one
2695                 if (it == position_to_children.begin())
2696                         break;
2697                 --it;
2698         }
2699
2700         // return the best macro we have found
2701         return bestData;
2702 }
2703
2704
2705 MacroData const * Buffer::getMacro(docstring const & name,
2706         DocIterator const & pos, bool global) const
2707 {
2708         if (d->macro_lock)
2709                 return 0;
2710
2711         // query buffer macros
2712         MacroData const * data = d->getBufferMacro(name, pos);
2713         if (data != 0)
2714                 return data;
2715
2716         // If there is a master buffer, query that
2717         Buffer const * const pbuf = d->parent();
2718         if (pbuf) {
2719                 d->macro_lock = true;
2720                 MacroData const * macro = pbuf->getMacro(
2721                         name, *this, false);
2722                 d->macro_lock = false;
2723                 if (macro)
2724                         return macro;
2725         }
2726
2727         if (global) {
2728                 data = MacroTable::globalMacros().get(name);
2729                 if (data != 0)
2730                         return data;
2731         }
2732
2733         return 0;
2734 }
2735
2736
2737 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2738 {
2739         // set scope end behind the last paragraph
2740         DocIterator scope = par_iterator_begin();
2741         scope.pit() = scope.lastpit() + 1;
2742
2743         return getMacro(name, scope, global);
2744 }
2745
2746
2747 MacroData const * Buffer::getMacro(docstring const & name,
2748         Buffer const & child, bool global) const
2749 {
2750         // look where the child buffer is included first
2751         Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2752         if (it == d->children_positions.end())
2753                 return 0;
2754
2755         // check for macros at the inclusion position
2756         return getMacro(name, it->second, global);
2757 }
2758
2759
2760 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
2761 {
2762         pit_type const lastpit = it.lastpit();
2763
2764         // look for macros in each paragraph
2765         while (it.pit() <= lastpit) {
2766                 Paragraph & par = it.paragraph();
2767
2768                 // iterate over the insets of the current paragraph
2769                 InsetList const & insets = par.insetList();
2770                 InsetList::const_iterator iit = insets.begin();
2771                 InsetList::const_iterator end = insets.end();
2772                 for (; iit != end; ++iit) {
2773                         it.pos() = iit->pos;
2774
2775                         // is it a nested text inset?
2776                         if (iit->inset->asInsetText()) {
2777                                 // Inset needs its own scope?
2778                                 InsetText const * itext = iit->inset->asInsetText();
2779                                 bool newScope = itext->isMacroScope();
2780
2781                                 // scope which ends just behind the inset
2782                                 DocIterator insetScope = it;
2783                                 ++insetScope.pos();
2784
2785                                 // collect macros in inset
2786                                 it.push_back(CursorSlice(*iit->inset));
2787                                 updateMacros(it, newScope ? insetScope : scope);
2788                                 it.pop_back();
2789                                 continue;
2790                         }
2791                         
2792                         if (iit->inset->asInsetTabular()) {
2793                                 CursorSlice slice(*iit->inset);
2794                                 size_t const numcells = slice.nargs();
2795                                 for (; slice.idx() < numcells; slice.forwardIdx()) {
2796                                         it.push_back(slice);
2797                                         updateMacros(it, scope);
2798                                         it.pop_back();
2799                                 }
2800                                 continue;
2801                         }
2802
2803                         // is it an external file?
2804                         if (iit->inset->lyxCode() == INCLUDE_CODE) {
2805                                 // get buffer of external file
2806                                 InsetInclude const & inset =
2807                                         static_cast<InsetInclude const &>(*iit->inset);
2808                                 macro_lock = true;
2809                                 Buffer * child = inset.getChildBuffer();
2810                                 macro_lock = false;
2811                                 if (!child)
2812                                         continue;
2813
2814                                 // register its position, but only when it is
2815                                 // included first in the buffer
2816                                 if (children_positions.find(child) ==
2817                                         children_positions.end())
2818                                                 children_positions[child] = it;
2819
2820                                 // register child with its scope
2821                                 position_to_children[it] = Impl::ScopeBuffer(scope, child);
2822                                 continue;
2823                         }
2824
2825                         InsetMath * im = iit->inset->asInsetMath();
2826                         if (doing_export && im)  {
2827                                 InsetMathHull * hull = im->asHullInset();
2828                                 if (hull)
2829                                         hull->recordLocation(it);
2830                         }
2831
2832                         if (iit->inset->lyxCode() != MATHMACRO_CODE)
2833                                 continue;
2834
2835                         // get macro data
2836                         MathMacroTemplate & macroTemplate =
2837                                 *iit->inset->asInsetMath()->asMacroTemplate();
2838                         MacroContext mc(owner_, it);
2839                         macroTemplate.updateToContext(mc);
2840
2841                         // valid?
2842                         bool valid = macroTemplate.validMacro();
2843                         // FIXME: Should be fixNameAndCheckIfValid() in fact,
2844                         // then the BufferView's cursor will be invalid in
2845                         // some cases which leads to crashes.
2846                         if (!valid)
2847                                 continue;
2848
2849                         // register macro
2850                         // FIXME (Abdel), I don't understandt why we pass 'it' here
2851                         // instead of 'macroTemplate' defined above... is this correct?
2852                         macros[macroTemplate.name()][it] =
2853                                 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
2854                 }
2855
2856                 // next paragraph
2857                 it.pit()++;
2858                 it.pos() = 0;
2859         }
2860 }
2861
2862
2863 void Buffer::updateMacros() const
2864 {
2865         if (d->macro_lock)
2866                 return;
2867
2868         LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2869
2870         // start with empty table
2871         d->macros.clear();
2872         d->children_positions.clear();
2873         d->position_to_children.clear();
2874
2875         // Iterate over buffer, starting with first paragraph
2876         // The scope must be bigger than any lookup DocIterator
2877         // later. For the global lookup, lastpit+1 is used, hence
2878         // we use lastpit+2 here.
2879         DocIterator it = par_iterator_begin();
2880         DocIterator outerScope = it;
2881         outerScope.pit() = outerScope.lastpit() + 2;
2882         d->updateMacros(it, outerScope);
2883 }
2884
2885
2886 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2887 {
2888         InsetIterator it  = inset_iterator_begin(inset());
2889         InsetIterator const end = inset_iterator_end(inset());
2890         for (; it != end; ++it) {
2891                 if (it->lyxCode() == BRANCH_CODE) {
2892                         InsetBranch & br = static_cast<InsetBranch &>(*it);
2893                         docstring const name = br.branch();
2894                         if (!from_master && !params().branchlist().find(name))
2895                                 result.push_back(name);
2896                         else if (from_master && !masterBuffer()->params().branchlist().find(name))
2897                                 result.push_back(name);
2898                         continue;
2899                 }
2900                 if (it->lyxCode() == INCLUDE_CODE) {
2901                         // get buffer of external file
2902                         InsetInclude const & ins =
2903                                 static_cast<InsetInclude const &>(*it);
2904                         Buffer * child = ins.getChildBuffer();
2905                         if (!child)
2906                                 continue;
2907                         child->getUsedBranches(result, true);
2908                 }
2909         }
2910         // remove duplicates
2911         result.unique();
2912 }
2913
2914
2915 void Buffer::updateMacroInstances(UpdateType utype) const
2916 {
2917         LYXERR(Debug::MACROS, "updateMacroInstances for "
2918                 << d->filename.onlyFileName());
2919         DocIterator it = doc_iterator_begin(this);
2920         it.forwardInset();
2921         DocIterator const end = doc_iterator_end(this);
2922         for (; it != end; it.forwardInset()) {
2923                 // look for MathData cells in InsetMathNest insets
2924                 InsetMath * minset = it.nextInset()->asInsetMath();
2925                 if (!minset)
2926                         continue;
2927
2928                 // update macro in all cells of the InsetMathNest
2929                 DocIterator::idx_type n = minset->nargs();
2930                 MacroContext mc = MacroContext(this, it);
2931                 for (DocIterator::idx_type i = 0; i < n; ++i) {
2932                         MathData & data = minset->cell(i);
2933                         data.updateMacros(0, mc, utype);
2934                 }
2935         }
2936 }
2937
2938
2939 void Buffer::listMacroNames(MacroNameSet & macros) const
2940 {
2941         if (d->macro_lock)
2942                 return;
2943
2944         d->macro_lock = true;
2945
2946         // loop over macro names
2947         Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2948         Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2949         for (; nameIt != nameEnd; ++nameIt)
2950                 macros.insert(nameIt->first);
2951
2952         // loop over children
2953         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2954         Impl::BufferPositionMap::iterator end = d->children_positions.end();
2955         for (; it != end; ++it)
2956                 it->first->listMacroNames(macros);
2957
2958         // call parent
2959         Buffer const * const pbuf = d->parent();
2960         if (pbuf)
2961                 pbuf->listMacroNames(macros);
2962
2963         d->macro_lock = false;
2964 }
2965
2966
2967 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2968 {
2969         Buffer const * const pbuf = d->parent();
2970         if (!pbuf)
2971                 return;
2972
2973         MacroNameSet names;
2974         pbuf->listMacroNames(names);
2975
2976         // resolve macros
2977         MacroNameSet::iterator it = names.begin();
2978         MacroNameSet::iterator end = names.end();
2979         for (; it != end; ++it) {
2980                 // defined?
2981                 MacroData const * data =
2982                 pbuf->getMacro(*it, *this, false);
2983                 if (data) {
2984                         macros.insert(data);
2985
2986                         // we cannot access the original MathMacroTemplate anymore
2987                         // here to calls validate method. So we do its work here manually.
2988                         // FIXME: somehow make the template accessible here.
2989                         if (data->optionals() > 0)
2990                                 features.require("xargs");
2991                 }
2992         }
2993 }
2994
2995
2996 Buffer::References & Buffer::references(docstring const & label)
2997 {
2998         if (d->parent())
2999                 return const_cast<Buffer *>(masterBuffer())->references(label);
3000
3001         RefCache::iterator it = d->ref_cache_.find(label);
3002         if (it != d->ref_cache_.end())
3003                 return it->second.second;
3004
3005         static InsetLabel const * dummy_il = 0;
3006         static References const dummy_refs;
3007         it = d->ref_cache_.insert(
3008                 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3009         return it->second.second;
3010 }
3011
3012
3013 Buffer::References const & Buffer::references(docstring const & label) const
3014 {
3015         return const_cast<Buffer *>(this)->references(label);
3016 }
3017
3018
3019 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3020 {
3021         masterBuffer()->d->ref_cache_[label].first = il;
3022 }
3023
3024
3025 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3026 {
3027         return masterBuffer()->d->ref_cache_[label].first;
3028 }
3029
3030
3031 void Buffer::clearReferenceCache() const
3032 {
3033         if (!d->parent())
3034                 d->ref_cache_.clear();
3035 }
3036
3037
3038 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
3039         InsetCode code)
3040 {
3041         //FIXME: This does not work for child documents yet.
3042         LASSERT(code == CITE_CODE, /**/);
3043
3044         reloadBibInfoCache();
3045
3046         // Check if the label 'from' appears more than once
3047         BiblioInfo const & keys = masterBibInfo();
3048         BiblioInfo::const_iterator bit  = keys.begin();
3049         BiblioInfo::const_iterator bend = keys.end();
3050         vector<docstring> labels;
3051
3052         for (; bit != bend; ++bit)
3053                 // FIXME UNICODE
3054                 labels.push_back(bit->first);
3055
3056         if (count(labels.begin(), labels.end(), from) > 1)
3057                 return;
3058
3059         string const paramName = "key";
3060         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3061                 if (it->lyxCode() == code) {
3062                         InsetCommand * inset = it->asInsetCommand();
3063                         if (!inset)
3064                                 continue;
3065                         docstring const oldValue = inset->getParam(paramName);
3066                         if (oldValue == from)
3067                                 inset->setParam(paramName, to);
3068                 }
3069         }
3070 }
3071
3072
3073 void Buffer::getSourceCode(odocstream & os, string const format,
3074                            pit_type par_begin, pit_type par_end,
3075                            bool full_source) const
3076 {
3077         OutputParams runparams(&params().encoding());
3078         runparams.nice = true;
3079         runparams.flavor = params().getOutputFlavor(format);
3080         runparams.linelen = lyxrc.plaintext_linelen;
3081         // No side effect of file copying and image conversion
3082         runparams.dryrun = true;
3083
3084         if (full_source) {
3085                 os << "% " << _("Preview source code") << "\n\n";
3086                 d->texrow.reset();
3087                 d->texrow.newline();
3088                 d->texrow.newline();
3089                 if (params().isDocBook())
3090                         writeDocBookSource(os, absFileName(), runparams, false);
3091                 else if (runparams.flavor == OutputParams::HTML)
3092                         writeLyXHTMLSource(os, runparams, false);
3093                 else {
3094                         // latex or literate
3095                         otexstream ots(os, d->texrow);
3096                         writeLaTeXSource(ots, string(), runparams, true, true);
3097                 }
3098         } else {
3099                 runparams.par_begin = par_begin;
3100                 runparams.par_end = par_end;
3101                 if (par_begin + 1 == par_end) {
3102                         os << "% "
3103                            << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3104                            << "\n\n";
3105                 } else {
3106                         os << "% "
3107                            << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3108                                         convert<docstring>(par_begin),
3109                                         convert<docstring>(par_end - 1))
3110                            << "\n\n";
3111                 }
3112                 TexRow texrow;
3113                 texrow.reset();
3114                 texrow.newline();
3115                 texrow.newline();
3116                 // output paragraphs
3117                 if (params().isDocBook())
3118                         docbookParagraphs(text(), *this, os, runparams);
3119                 else if (runparams.flavor == OutputParams::HTML) {
3120                         XHTMLStream xs(os);
3121                         xhtmlParagraphs(text(), *this, xs, runparams);
3122                 } else {
3123                         // latex or literate
3124                         otexstream ots(os, texrow);
3125                         latexParagraphs(*this, text(), ots, runparams);
3126                 }
3127         }
3128 }
3129
3130
3131 ErrorList & Buffer::errorList(string const & type) const
3132 {
3133         static ErrorList emptyErrorList;
3134         map<string, ErrorList>::iterator it = d->errorLists.find(type);
3135         if (it == d->errorLists.end())
3136                 return emptyErrorList;
3137
3138         return it->second;
3139 }
3140
3141
3142 void Buffer::updateTocItem(std::string const & type,
3143         DocIterator const & dit) const
3144 {
3145         if (d->gui_)
3146                 d->gui_->updateTocItem(type, dit);
3147 }
3148
3149
3150 void Buffer::structureChanged() const
3151 {
3152         if (d->gui_)
3153                 d->gui_->structureChanged();
3154 }
3155
3156
3157 void Buffer::errors(string const & err, bool from_master) const
3158 {
3159         if (d->gui_)
3160                 d->gui_->errors(err, from_master);
3161 }
3162
3163
3164 void Buffer::message(docstring const & msg) const
3165 {
3166         if (d->gui_)
3167                 d->gui_->message(msg);
3168 }
3169
3170
3171 void Buffer::setBusy(bool on) const
3172 {
3173         if (d->gui_)
3174                 d->gui_->setBusy(on);
3175 }
3176
3177
3178 void Buffer::updateTitles() const
3179 {
3180         if (d->wa_)
3181                 d->wa_->updateTitles();
3182 }
3183
3184
3185 void Buffer::resetAutosaveTimers() const
3186 {
3187         if (d->gui_)
3188                 d->gui_->resetAutosaveTimers();
3189 }
3190
3191
3192 bool Buffer::hasGuiDelegate() const
3193 {
3194         return d->gui_;
3195 }
3196
3197
3198 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3199 {
3200         d->gui_ = gui;
3201 }
3202
3203
3204
3205 namespace {
3206
3207 class AutoSaveBuffer : public ForkedProcess {
3208 public:
3209         ///
3210         AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3211                 : buffer_(buffer), fname_(fname) {}
3212         ///
3213         virtual shared_ptr<ForkedProcess> clone() const
3214         {
3215                 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3216         }
3217         ///
3218         int start()
3219         {
3220                 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3221                                                  from_utf8(fname_.absFileName())));
3222                 return run(DontWait);
3223         }
3224 private:
3225         ///
3226         virtual int generateChild();
3227         ///
3228         Buffer const & buffer_;
3229         FileName fname_;
3230 };
3231
3232
3233 int AutoSaveBuffer::generateChild()
3234 {
3235 #if defined(__APPLE__)
3236         /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard) 
3237          *   We should use something else like threads.
3238          *
3239          * Since I do not know how to determine at run time what is the OS X
3240          * version, I just disable forking altogether for now (JMarc)
3241          */
3242         pid_t const pid = -1;
3243 #else
3244         // tmp_ret will be located (usually) in /tmp
3245         // will that be a problem?
3246         // Note that this calls ForkedCalls::fork(), so it's
3247         // ok cross-platform.
3248         pid_t const pid = fork();
3249         // If you want to debug the autosave
3250         // you should set pid to -1, and comment out the fork.
3251         if (pid != 0 && pid != -1)
3252                 return pid;
3253 #endif
3254
3255         // pid = -1 signifies that lyx was unable
3256         // to fork. But we will do the save
3257         // anyway.
3258         bool failed = false;
3259         FileName const tmp_ret = FileName::tempName("lyxauto");
3260         if (!tmp_ret.empty()) {
3261                 buffer_.writeFile(tmp_ret);
3262                 // assume successful write of tmp_ret
3263                 if (!tmp_ret.moveTo(fname_))
3264                         failed = true;
3265         } else
3266                 failed = true;
3267
3268         if (failed) {
3269                 // failed to write/rename tmp_ret so try writing direct
3270                 if (!buffer_.writeFile(fname_)) {
3271                         // It is dangerous to do this in the child,
3272                         // but safe in the parent, so...
3273                         if (pid == -1) // emit message signal.
3274                                 buffer_.message(_("Autosave failed!"));
3275                 }
3276         }
3277
3278         if (pid == 0) // we are the child so...
3279                 _exit(0);
3280
3281         return pid;
3282 }
3283
3284 } // namespace anon
3285
3286
3287 FileName Buffer::getEmergencyFileName() const
3288 {
3289         return FileName(d->filename.absFileName() + ".emergency");
3290 }
3291
3292
3293 FileName Buffer::getAutosaveFileName() const
3294 {
3295         // if the document is unnamed try to save in the backup dir, else
3296         // in the default document path, and as a last try in the filePath, 
3297         // which will most often be the temporary directory
3298         string fpath;
3299         if (isUnnamed())
3300                 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3301                         : lyxrc.backupdir_path;
3302         if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3303                 fpath = filePath();
3304
3305         string const fname = "#" + d->filename.onlyFileName() + "#";
3306
3307         return makeAbsPath(fname, fpath);
3308 }
3309
3310
3311 void Buffer::removeAutosaveFile() const
3312 {
3313         FileName const f = getAutosaveFileName();
3314         if (f.exists())
3315                 f.removeFile();
3316 }
3317
3318
3319 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3320 {
3321         FileName const newauto = getAutosaveFileName();
3322         oldauto.refresh();
3323         if (newauto != oldauto && oldauto.exists())
3324                 if (!oldauto.moveTo(newauto))
3325                         LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3326 }
3327
3328
3329 bool Buffer::autoSave() const 
3330 {
3331         Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3332         if (buf->d->bak_clean || isReadonly())
3333                 return true;
3334
3335         message(_("Autosaving current document..."));
3336         buf->d->bak_clean = true;
3337         
3338         FileName const fname = getAutosaveFileName();
3339         if (d->cloned_buffer_) {
3340                 // If this buffer is cloned, we assume that
3341                 // we are running in a separate thread already.
3342                 FileName const tmp_ret = FileName::tempName("lyxauto");
3343                 if (!tmp_ret.empty()) {
3344                         writeFile(tmp_ret);
3345                         // assume successful write of tmp_ret
3346                         if (tmp_ret.moveTo(fname))
3347                                 return true;
3348                 }
3349                 // failed to write/rename tmp_ret so try writing direct
3350                 return writeFile(fname);
3351         } else {        
3352                 /// This function is deprecated as the frontend needs to take care
3353                 /// of cloning the buffer and autosaving it in another thread. It
3354                 /// is still here to allow (QT_VERSION < 0x040400).
3355                 AutoSaveBuffer autosave(*this, fname);
3356                 autosave.start();
3357                 return true;
3358         }
3359 }
3360
3361
3362 namespace {
3363         // helper class, to guarantee this gets reset properly
3364         class MarkAsExporting   {
3365         public:
3366                 MarkAsExporting(Buffer const * buf) : buf_(buf) 
3367                 {
3368                         LASSERT(buf_, /* */);
3369                         buf_->setExportStatus(true);
3370                 }
3371                 ~MarkAsExporting() 
3372                 {
3373                         buf_->setExportStatus(false);
3374                 }
3375         private:
3376                 Buffer const * const buf_;
3377         };
3378 }
3379
3380
3381 void Buffer::setExportStatus(bool e) const
3382 {
3383         d->doing_export = e;    
3384         ListOfBuffers clist = getDescendents();
3385         ListOfBuffers::const_iterator cit = clist.begin();
3386         ListOfBuffers::const_iterator const cen = clist.end();
3387         for (; cit != cen; ++cit)
3388                 (*cit)->d->doing_export = e;
3389 }
3390
3391
3392 bool Buffer::isExporting() const
3393 {
3394         return d->doing_export;
3395 }
3396
3397
3398 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3399         bool includeall, string & result_file) const
3400 {
3401         MarkAsExporting exporting(this);
3402         string backend_format;
3403         OutputParams runparams(&params().encoding());
3404         runparams.flavor = OutputParams::LATEX;
3405         runparams.linelen = lyxrc.plaintext_linelen;
3406         runparams.includeall = includeall;
3407         vector<string> backs = params().backends();
3408         Converters converters = theConverters();
3409         if (find(backs.begin(), backs.end(), format) == backs.end()) {
3410                 // Get shortest path to format
3411                 converters.buildGraph();
3412                 Graph::EdgePath path;
3413                 for (vector<string>::const_iterator it = backs.begin();
3414                      it != backs.end(); ++it) {
3415                         Graph::EdgePath p = converters.getPath(*it, format);
3416                         if (!p.empty() && (path.empty() || p.size() < path.size())) {
3417                                 backend_format = *it;
3418                                 path = p;
3419                         }
3420                 }
3421                 if (path.empty()) {
3422                         if (!put_in_tempdir) {
3423                                 // Only show this alert if this is an export to a non-temporary
3424                                 // file (not for previewing).
3425                                 Alert::error(_("Couldn't export file"), bformat(
3426                                         _("No information for exporting the format %1$s."),
3427                                         formats.prettyName(format)));
3428                         }
3429                         return false;
3430                 }
3431                 runparams.flavor = converters.getFlavor(path);
3432
3433         } else {
3434                 backend_format = format;
3435                 // FIXME: Don't hardcode format names here, but use a flag
3436                 if (backend_format == "pdflatex")
3437                         runparams.flavor = OutputParams::PDFLATEX;
3438                 else if (backend_format == "luatex")
3439                         runparams.flavor = OutputParams::LUATEX;
3440                 else if (backend_format == "xetex")
3441                         runparams.flavor = OutputParams::XETEX;
3442         }
3443
3444         string filename = latexName(false);
3445         filename = addName(temppath(), filename);
3446         filename = changeExtension(filename,
3447                                    formats.extension(backend_format));
3448
3449         // Plain text backend
3450         if (backend_format == "text") {
3451                 runparams.flavor = OutputParams::TEXT;
3452                 writePlaintextFile(*this, FileName(filename), runparams);
3453         }
3454         // HTML backend
3455         else if (backend_format == "xhtml") {
3456                 runparams.flavor = OutputParams::HTML;
3457                 switch (params().html_math_output) {
3458                 case BufferParams::MathML: 
3459                         runparams.math_flavor = OutputParams::MathAsMathML; 
3460                         break;
3461                 case BufferParams::HTML: 
3462                         runparams.math_flavor = OutputParams::MathAsHTML; 
3463                         break;
3464                 case BufferParams::Images:
3465                         runparams.math_flavor = OutputParams::MathAsImages; 
3466                         break;
3467                 case BufferParams::LaTeX:
3468                         runparams.math_flavor = OutputParams::MathAsLaTeX; 
3469                         break;
3470                 }
3471                 makeLyXHTMLFile(FileName(filename), runparams);
3472         } else if (backend_format == "lyx")
3473                 writeFile(FileName(filename));
3474         // Docbook backend
3475         else if (params().isDocBook()) {
3476                 runparams.nice = !put_in_tempdir;
3477                 makeDocBookFile(FileName(filename), runparams);
3478         }
3479         // LaTeX backend
3480         else if (backend_format == format) {
3481                 runparams.nice = true;
3482                 if (!makeLaTeXFile(FileName(filename), string(), runparams)) {
3483                         if (d->cloned_buffer_) {
3484                                 d->cloned_buffer_->d->errorLists["Export"] =
3485                                         d->errorLists["Export"];
3486                         }
3487                         return false;
3488                 }
3489         } else if (!lyxrc.tex_allows_spaces
3490                    && contains(filePath(), ' ')) {
3491                 Alert::error(_("File name error"),
3492                            _("The directory path to the document cannot contain spaces."));
3493                 return false;
3494         } else {
3495                 runparams.nice = false;
3496                 if (!makeLaTeXFile(FileName(filename), filePath(), runparams)) {
3497                         if (d->cloned_buffer_) {
3498                                 d->cloned_buffer_->d->errorLists["Export"] =
3499                                         d->errorLists["Export"];
3500                         }
3501                         return false;
3502                 }
3503         }
3504
3505         string const error_type = (format == "program")
3506                 ? "Build" : params().bufferFormat();
3507         ErrorList & error_list = d->errorLists[error_type];
3508         string const ext = formats.extension(format);
3509         FileName const tmp_result_file(changeExtension(filename, ext));
3510         bool const success = converters.convert(this, FileName(filename),
3511                 tmp_result_file, FileName(absFileName()), backend_format, format,
3512                 error_list);
3513
3514         // Emit the signal to show the error list or copy it back to the
3515         // cloned Buffer so that it can be emitted afterwards.
3516         if (format != backend_format) {
3517                 if (d->cloned_buffer_) {
3518                         d->cloned_buffer_->d->errorLists[error_type] = 
3519                                 d->errorLists[error_type];
3520                 } else 
3521                         errors(error_type);
3522                 // also to the children, in case of master-buffer-view
3523                 ListOfBuffers clist = getDescendents();
3524                 ListOfBuffers::const_iterator cit = clist.begin();
3525                 ListOfBuffers::const_iterator const cen = clist.end();
3526                 for (; cit != cen; ++cit) {
3527                         if (d->cloned_buffer_) {
3528                                 // Enable reverse search by copying back the
3529                                 // texrow object to the cloned buffer.
3530                                 // FIXME: this is not thread safe.
3531                                 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
3532                                 (*cit)->d->cloned_buffer_->d->errorLists[error_type] = 
3533                                         (*cit)->d->errorLists[error_type];
3534                         } else
3535                                 (*cit)->errors(error_type, true);
3536                 }
3537         }
3538
3539         if (d->cloned_buffer_) {
3540                 // Enable reverse dvi or pdf to work by copying back the texrow
3541                 // object to the cloned buffer.
3542                 // FIXME: There is a possibility of concurrent access to texrow
3543                 // here from the main GUI thread that should be securized.
3544                 d->cloned_buffer_->d->texrow = d->texrow;
3545                 string const error_type = params().bufferFormat();
3546                 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
3547         }
3548
3549         if (!success)
3550                 return false;
3551
3552         if (put_in_tempdir) {
3553                 result_file = tmp_result_file.absFileName();
3554                 return true;
3555         }
3556
3557         result_file = changeExtension(d->exportFileName().absFileName(), ext);
3558         // We need to copy referenced files (e. g. included graphics
3559         // if format == "dvi") to the result dir.
3560         vector<ExportedFile> const files =
3561                 runparams.exportdata->externalFiles(format);
3562         string const dest = onlyPath(result_file);
3563         bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
3564                                  : force_overwrite == ALL_FILES;
3565         CopyStatus status = use_force ? FORCE : SUCCESS;
3566         
3567         vector<ExportedFile>::const_iterator it = files.begin();
3568         vector<ExportedFile>::const_iterator const en = files.end();
3569         for (; it != en && status != CANCEL; ++it) {
3570                 string const fmt = formats.getFormatFromFile(it->sourceName);
3571                 status = copyFile(fmt, it->sourceName,
3572                         makeAbsPath(it->exportName, dest),
3573                         it->exportName, status == FORCE);
3574         }
3575
3576         if (status == CANCEL) {
3577                 message(_("Document export cancelled."));
3578         } else if (tmp_result_file.exists()) {
3579                 // Finally copy the main file
3580                 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
3581                                     : force_overwrite != NO_FILES;
3582                 if (status == SUCCESS && use_force)
3583                         status = FORCE;
3584                 status = copyFile(format, tmp_result_file,
3585                         FileName(result_file), result_file,
3586                         status == FORCE);
3587                 message(bformat(_("Document exported as %1$s "
3588                         "to file `%2$s'"),
3589                         formats.prettyName(format),
3590                         makeDisplayPath(result_file)));
3591         } else {
3592                 // This must be a dummy converter like fax (bug 1888)
3593                 message(bformat(_("Document exported as %1$s"),
3594                         formats.prettyName(format)));
3595         }
3596
3597         return true;
3598 }
3599
3600
3601 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3602                       bool includeall) const
3603 {
3604         string result_file;
3605         // (1) export with all included children (omit \includeonly)
3606         if (includeall && !doExport(format, put_in_tempdir, true, result_file))
3607                 return false;
3608         // (2) export with included children only
3609         return doExport(format, put_in_tempdir, false, result_file);
3610 }
3611
3612
3613 bool Buffer::preview(string const & format, bool includeall) const
3614 {
3615         MarkAsExporting exporting(this);
3616         string result_file;
3617         // (1) export with all included children (omit \includeonly)
3618         if (includeall && !doExport(format, true, true))
3619                 return false;
3620         // (2) export with included children only
3621         if (!doExport(format, true, false, result_file))
3622                 return false;
3623         return formats.view(*this, FileName(result_file), format);
3624 }
3625
3626
3627 Buffer::ReadStatus Buffer::extractFromVC()
3628 {
3629         bool const found = LyXVC::file_not_found_hook(d->filename);
3630         if (!found)
3631                 return ReadFileNotFound;
3632         if (!d->filename.isReadableFile())
3633                 return ReadVCError;
3634         return ReadSuccess;
3635 }
3636
3637
3638 Buffer::ReadStatus Buffer::loadEmergency()
3639 {
3640         FileName const emergencyFile = getEmergencyFileName();
3641         if (!emergencyFile.exists() 
3642                   || emergencyFile.lastModified() <= d->filename.lastModified())
3643                 return ReadFileNotFound;
3644
3645         docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
3646         docstring const text = bformat(_("An emergency save of the document "
3647                 "%1$s exists.\n\nRecover emergency save?"), file);
3648         
3649         int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
3650                 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
3651
3652         switch (load_emerg)
3653         {
3654         case 0: {
3655                 docstring str;
3656                 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
3657                 bool const success = (ret_llf == ReadSuccess);
3658                 if (success) {
3659                         if (isReadonly()) {
3660                                 Alert::warning(_("File is read-only"),
3661                                         bformat(_("An emergency file is successfully loaded, "
3662                                         "but the original file %1$s is marked read-only. "
3663                                         "Please make sure to save the document as a different "
3664                                         "file."), from_utf8(d->filename.absFileName())));
3665                         }
3666                         markDirty();
3667                         str = _("Document was successfully recovered.");
3668                 } else
3669                         str = _("Document was NOT successfully recovered.");
3670                 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3671                         makeDisplayPath(emergencyFile.absFileName()));
3672
3673                 int const del_emerg = 
3674                         Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3675                                 _("&Remove"), _("&Keep"));
3676                 if (del_emerg == 0) {
3677                         emergencyFile.removeFile();
3678                         if (success)
3679                                 Alert::warning(_("Emergency file deleted"),
3680                                         _("Do not forget to save your file now!"), true);
3681                         }
3682                 return success ? ReadSuccess : ReadEmergencyFailure;
3683         }
3684         case 1: {
3685                 int const del_emerg =
3686                         Alert::prompt(_("Delete emergency file?"),
3687                                 _("Remove emergency file now?"), 1, 1,
3688                                 _("&Remove"), _("&Keep"));
3689                 if (del_emerg == 0)
3690                         emergencyFile.removeFile();
3691                 return ReadOriginal;
3692         }
3693
3694         default:
3695                 break;
3696         }
3697         return ReadCancel;
3698 }
3699
3700
3701 Buffer::ReadStatus Buffer::loadAutosave()
3702 {
3703         // Now check if autosave file is newer.
3704         FileName const autosaveFile = getAutosaveFileName();
3705         if (!autosaveFile.exists() 
3706                   || autosaveFile.lastModified() <= d->filename.lastModified()) 
3707                 return ReadFileNotFound;
3708
3709         docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
3710         docstring const text = bformat(_("The backup of the document %1$s " 
3711                 "is newer.\n\nLoad the backup instead?"), file);
3712         int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
3713                 _("&Load backup"), _("Load &original"), _("&Cancel"));
3714         
3715         switch (ret)
3716         {
3717         case 0: {
3718                 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
3719                 // the file is not saved if we load the autosave file.
3720                 if (ret_llf == ReadSuccess) {
3721                         if (isReadonly()) {
3722                                 Alert::warning(_("File is read-only"),
3723                                         bformat(_("A backup file is successfully loaded, "
3724                                         "but the original file %1$s is marked read-only. "
3725                                         "Please make sure to save the document as a "
3726                                         "different file."), 
3727                                         from_utf8(d->filename.absFileName())));
3728                         }
3729                         markDirty();
3730                         return ReadSuccess;
3731                 }
3732                 return ReadAutosaveFailure;
3733         }
3734         case 1:
3735                 // Here we delete the autosave
3736                 autosaveFile.removeFile();
3737                 return ReadOriginal;
3738         default:
3739                 break;
3740         }
3741         return ReadCancel;
3742 }
3743
3744
3745 Buffer::ReadStatus Buffer::loadLyXFile()
3746 {
3747         if (!d->filename.isReadableFile()) {
3748                 ReadStatus const ret_rvc = extractFromVC();
3749                 if (ret_rvc != ReadSuccess)
3750                         return ret_rvc;
3751         }
3752
3753         ReadStatus const ret_re = loadEmergency();
3754         if (ret_re == ReadSuccess || ret_re == ReadCancel)
3755                 return ret_re;
3756         
3757         ReadStatus const ret_ra = loadAutosave();
3758         if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
3759                 return ret_ra;
3760
3761         return loadThisLyXFile(d->filename);
3762 }
3763
3764
3765 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
3766 {
3767         return readFile(fn);
3768 }
3769
3770
3771 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3772 {
3773         TeXErrors::Errors::const_iterator it = terr.begin();
3774         TeXErrors::Errors::const_iterator end = terr.end();
3775         ListOfBuffers clist = getDescendents();
3776         ListOfBuffers::const_iterator cen = clist.end();
3777
3778         for (; it != end; ++it) {
3779                 int id_start = -1;
3780                 int pos_start = -1;
3781                 int errorRow = it->error_in_line;
3782                 Buffer const * buf = 0;
3783                 Impl const * p = d;
3784                 if (it->child_name.empty())
3785                     p->texrow.getIdFromRow(errorRow, id_start, pos_start);
3786                 else {
3787                         // The error occurred in a child
3788                         ListOfBuffers::const_iterator cit = clist.begin();
3789                         for (; cit != cen; ++cit) {
3790                                 string const child_name =
3791                                         DocFileName(changeExtension(
3792                                                 (*cit)->absFileName(), "tex")).
3793                                                         mangledFileName();
3794                                 if (it->child_name != child_name)
3795                                         continue;
3796                                 (*cit)->d->texrow.getIdFromRow(errorRow,
3797                                                         id_start, pos_start);
3798                                 if (id_start != -1) {
3799                                         buf = d->cloned_buffer_
3800                                                 ? (*cit)->d->cloned_buffer_->d->owner_
3801                                                 : (*cit)->d->owner_;
3802                                         p = (*cit)->d;
3803                                         break;
3804                                 }
3805                         }
3806                 }
3807                 int id_end = -1;
3808                 int pos_end = -1;
3809                 bool found;
3810                 do {
3811                         ++errorRow;
3812                         found = p->texrow.getIdFromRow(errorRow, id_end, pos_end);
3813                 } while (found && id_start == id_end && pos_start == pos_end);
3814
3815                 if (id_start != id_end) {
3816                         // Next registered position is outside the inset where
3817                         // the error occurred, so signal end-of-paragraph
3818                         pos_end = 0;
3819                 }
3820
3821                 errorList.push_back(ErrorItem(it->error_desc,
3822                         it->error_text, id_start, pos_start, pos_end, buf));
3823         }
3824 }
3825
3826
3827 void Buffer::setBuffersForInsets() const
3828 {
3829         inset().setBuffer(const_cast<Buffer &>(*this)); 
3830 }
3831
3832
3833 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
3834 {
3835         // Use the master text class also for child documents
3836         Buffer const * const master = masterBuffer();
3837         DocumentClass const & textclass = master->params().documentClass();
3838         
3839         // do this only if we are the top-level Buffer
3840         if (master == this)
3841                 reloadBibInfoCache();
3842
3843         // keep the buffers to be children in this set. If the call from the
3844         // master comes back we can see which of them were actually seen (i.e.
3845         // via an InsetInclude). The remaining ones in the set need still be updated.
3846         static std::set<Buffer const *> bufToUpdate;
3847         if (scope == UpdateMaster) {
3848                 // If this is a child document start with the master
3849                 if (master != this) {
3850                         bufToUpdate.insert(this);
3851                         master->updateBuffer(UpdateMaster, utype);
3852                         // Do this here in case the master has no gui associated with it. Then, 
3853                         // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3854                         if (!master->d->gui_)
3855                                 structureChanged();
3856
3857                         // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3858                         if (bufToUpdate.find(this) == bufToUpdate.end())
3859                                 return;
3860                 }
3861
3862                 // start over the counters in the master
3863                 textclass.counters().reset();
3864         }
3865
3866         // update will be done below for this buffer
3867         bufToUpdate.erase(this);
3868
3869         // update all caches
3870         clearReferenceCache();
3871         updateMacros();
3872
3873         Buffer & cbuf = const_cast<Buffer &>(*this);
3874
3875         LASSERT(!text().paragraphs().empty(), /**/);
3876
3877         // do the real work
3878         ParIterator parit = cbuf.par_iterator_begin();
3879         updateBuffer(parit, utype);
3880
3881         if (master != this)
3882                 // TocBackend update will be done later.
3883                 return;
3884
3885         d->bibinfo_cache_valid_ = true;
3886         d->cite_labels_valid_ = true;
3887         cbuf.tocBackend().update();
3888         if (scope == UpdateMaster)
3889                 cbuf.structureChanged();
3890 }
3891
3892
3893 static depth_type getDepth(DocIterator const & it)
3894 {
3895         depth_type depth = 0;
3896         for (size_t i = 0 ; i < it.depth() ; ++i)
3897                 if (!it[i].inset().inMathed())
3898                         depth += it[i].paragraph().getDepth() + 1;
3899         // remove 1 since the outer inset does not count
3900         return depth - 1;
3901 }
3902
3903 static depth_type getItemDepth(ParIterator const & it)
3904 {
3905         Paragraph const & par = *it;
3906         LabelType const labeltype = par.layout().labeltype;
3907
3908         if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3909                 return 0;
3910
3911         // this will hold the lowest depth encountered up to now.
3912         depth_type min_depth = getDepth(it);
3913         ParIterator prev_it = it;
3914         while (true) {
3915                 if (prev_it.pit())
3916                         --prev_it.top().pit();
3917                 else {
3918                         // start of nested inset: go to outer par
3919                         prev_it.pop_back();
3920                         if (prev_it.empty()) {
3921                                 // start of document: nothing to do
3922                                 return 0;
3923                         }
3924                 }
3925
3926                 // We search for the first paragraph with same label
3927                 // that is not more deeply nested.
3928                 Paragraph & prev_par = *prev_it;
3929                 depth_type const prev_depth = getDepth(prev_it);
3930                 if (labeltype == prev_par.layout().labeltype) {
3931                         if (prev_depth < min_depth)
3932                                 return prev_par.itemdepth + 1;
3933                         if (prev_depth == min_depth)
3934                                 return prev_par.itemdepth;
3935                 }
3936                 min_depth = min(min_depth, prev_depth);
3937                 // small optimization: if we are at depth 0, we won't
3938                 // find anything else
3939                 if (prev_depth == 0)
3940                         return 0;
3941         }
3942 }
3943
3944
3945 static bool needEnumCounterReset(ParIterator const & it)
3946 {
3947         Paragraph const & par = *it;
3948         LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3949         depth_type const cur_depth = par.getDepth();
3950         ParIterator prev_it = it;
3951         while (prev_it.pit()) {
3952                 --prev_it.top().pit();
3953                 Paragraph const & prev_par = *prev_it;
3954                 if (prev_par.getDepth() <= cur_depth)
3955                         return  prev_par.layout().labeltype != LABEL_ENUMERATE;
3956         }
3957         // start of nested inset: reset
3958         return true;
3959 }
3960
3961
3962 // set the label of a paragraph. This includes the counters.
3963 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
3964 {
3965         BufferParams const & bp = owner_->masterBuffer()->params();
3966         DocumentClass const & textclass = bp.documentClass();
3967         Paragraph & par = it.paragraph();
3968         Layout const & layout = par.layout();
3969         Counters & counters = textclass.counters();
3970
3971         if (par.params().startOfAppendix()) {
3972                 // FIXME: only the counter corresponding to toplevel
3973                 // sectioning should be reset
3974                 counters.reset();
3975                 counters.appendix(true);
3976         }
3977         par.params().appendix(counters.appendix());
3978
3979         // Compute the item depth of the paragraph
3980         par.itemdepth = getItemDepth(it);
3981
3982         if (layout.margintype == MARGIN_MANUAL
3983             || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3984                 if (par.params().labelWidthString().empty())
3985                         par.params().labelWidthString(par.expandLabel(layout, bp));
3986         } else {
3987                 par.params().labelWidthString(docstring());
3988         }
3989
3990         switch(layout.labeltype) {
3991         case LABEL_COUNTER:
3992                 if (layout.toclevel <= bp.secnumdepth
3993                       && (layout.latextype != LATEX_ENVIRONMENT
3994                           || it.text()->isFirstInSequence(it.pit()))) {
3995                         if (counters.hasCounter(layout.counter))
3996                                 counters.step(layout.counter, utype);
3997                         par.params().labelString(par.expandLabel(layout, bp));
3998                 } else
3999                         par.params().labelString(docstring());
4000                 break;
4001
4002         case LABEL_ITEMIZE: {
4003                 // At some point of time we should do something more
4004                 // clever here, like:
4005                 //   par.params().labelString(
4006                 //    bp.user_defined_bullet(par.itemdepth).getText());
4007                 // for now, use a simple hardcoded label
4008                 docstring itemlabel;
4009                 switch (par.itemdepth) {
4010                 case 0:
4011                         itemlabel = char_type(0x2022);
4012                         break;
4013                 case 1:
4014                         itemlabel = char_type(0x2013);
4015                         break;
4016                 case 2:
4017                         itemlabel = char_type(0x2217);
4018                         break;
4019                 case 3:
4020                         itemlabel = char_type(0x2219); // or 0x00b7
4021                         break;
4022                 }
4023                 par.params().labelString(itemlabel);
4024                 break;
4025         }
4026
4027         case LABEL_ENUMERATE: {
4028                 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4029
4030                 switch (par.itemdepth) {
4031                 case 2:
4032                         enumcounter += 'i';
4033                 case 1:
4034                         enumcounter += 'i';
4035                 case 0:
4036                         enumcounter += 'i';
4037                         break;
4038                 case 3:
4039                         enumcounter += "iv";
4040                         break;
4041                 default:
4042                         // not a valid enumdepth...
4043                         break;
4044                 }
4045
4046                 // Maybe we have to reset the enumeration counter.
4047                 if (needEnumCounterReset(it))
4048                         counters.reset(enumcounter);
4049                 counters.step(enumcounter, utype);
4050
4051                 string const & lang = par.getParLanguage(bp)->code();
4052                 par.params().labelString(counters.theCounter(enumcounter, lang));
4053
4054                 break;
4055         }
4056
4057         case LABEL_SENSITIVE: {
4058                 string const & type = counters.current_float();
4059                 docstring full_label;
4060                 if (type.empty())
4061                         full_label = owner_->B_("Senseless!!! ");
4062                 else {
4063                         docstring name = owner_->B_(textclass.floats().getType(type).name());
4064                         if (counters.hasCounter(from_utf8(type))) {
4065                                 string const & lang = par.getParLanguage(bp)->code();
4066                                 counters.step(from_utf8(type), utype);
4067                                 full_label = bformat(from_ascii("%1$s %2$s:"), 
4068                                                      name, 
4069                                                      counters.theCounter(from_utf8(type), lang));
4070                         } else
4071                                 full_label = bformat(from_ascii("%1$s #:"), name);      
4072                 }
4073                 par.params().labelString(full_label);   
4074                 break;
4075         }
4076
4077         case LABEL_NO_LABEL:
4078                 par.params().labelString(docstring());
4079                 break;
4080
4081         case LABEL_MANUAL:
4082         case LABEL_TOP_ENVIRONMENT:
4083         case LABEL_CENTERED_TOP_ENVIRONMENT:
4084         case LABEL_STATIC:      
4085         case LABEL_BIBLIO:
4086                 par.params().labelString(par.expandLabel(layout, bp));
4087                 break;
4088         }
4089 }
4090
4091
4092 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4093 {
4094         LASSERT(parit.pit() == 0, /**/);
4095
4096         // Set the position of the text in the buffer to be able
4097         // to resolve macros in it.
4098         parit.text()->setMacrocontextPosition(parit);
4099
4100         depth_type maxdepth = 0;
4101         pit_type const lastpit = parit.lastpit();
4102         for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4103                 // reduce depth if necessary
4104                 parit->params().depth(min(parit->params().depth(), maxdepth));
4105                 maxdepth = parit->getMaxDepthAfter();
4106
4107                 if (utype == OutputUpdate) {
4108                         // track the active counters
4109                         // we have to do this for the master buffer, since the local
4110                         // buffer isn't tracking anything.
4111                         masterBuffer()->params().documentClass().counters().
4112                                         setActiveLayout(parit->layout());
4113                 }
4114                 
4115                 // set the counter for this paragraph
4116                 d->setLabel(parit, utype);
4117
4118                 // now the insets
4119                 InsetList::const_iterator iit = parit->insetList().begin();
4120                 InsetList::const_iterator end = parit->insetList().end();
4121                 for (; iit != end; ++iit) {
4122                         parit.pos() = iit->pos;
4123                         iit->inset->updateBuffer(parit, utype);
4124                 }
4125         }
4126 }
4127
4128
4129 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4130         WordLangTuple & word_lang, docstring_list & suggestions) const
4131 {
4132         int progress = 0;
4133         WordLangTuple wl;
4134         suggestions.clear();
4135         word_lang = WordLangTuple();
4136         // OK, we start from here.
4137         DocIterator const end = doc_iterator_end(this);
4138         for (; from != end; from.forwardPos()) {
4139                 // We are only interested in text so remove the math CursorSlice.
4140                 while (from.inMathed()) {
4141                         from.pop_back();
4142                         from.pos()++;
4143                 }
4144                 // If from is at the end of the document (which is possible
4145                 // when leaving the mathed) LyX will crash later.
4146                 if (from == end)
4147                         break;
4148                 to = from;
4149                 from.paragraph().spellCheck();
4150                 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4151                 if (SpellChecker::misspelled(res)) {
4152                         word_lang = wl;
4153                         break;
4154                 }
4155
4156                 // Do not increase progress when from == to, otherwise the word
4157                 // count will be wrong.
4158                 if (from != to) {
4159                         from = to;
4160                         ++progress;
4161                 }
4162         }
4163         return progress;
4164 }
4165
4166
4167 Buffer::ReadStatus Buffer::reload()
4168 {
4169         setBusy(true);
4170         // c.f. bug http://www.lyx.org/trac/ticket/6587
4171         removeAutosaveFile();
4172         // e.g., read-only status could have changed due to version control
4173         d->filename.refresh();
4174         docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4175
4176         ReadStatus const status = loadLyXFile();
4177         if (status == ReadSuccess) {
4178                 updateBuffer();
4179                 changed(true);
4180                 updateTitles();
4181                 markClean();
4182                 message(bformat(_("Document %1$s reloaded."), disp_fn));
4183                 d->undo_.clear();
4184         } else {
4185                 message(bformat(_("Could not reload document %1$s."), disp_fn));
4186         }       
4187         setBusy(false);
4188         removePreviews();
4189         updatePreviews();
4190         errors("Parse");
4191         return status;
4192 }
4193
4194
4195 bool Buffer::saveAs(FileName const & fn)
4196 {
4197         FileName const old_name = fileName();
4198         FileName const old_auto = getAutosaveFileName();
4199         bool const old_unnamed = isUnnamed();
4200
4201         setFileName(fn);
4202         markDirty();
4203         setUnnamed(false);
4204
4205         if (save()) {
4206                 // bring the autosave file with us, just in case.
4207                 moveAutosaveFile(old_auto);
4208                 // validate version control data and
4209                 // correct buffer title
4210                 lyxvc().file_found_hook(fileName());
4211                 updateTitles();
4212                 // the file has now been saved to the new location.
4213                 // we need to check that the locations of child buffers
4214                 // are still valid.
4215                 checkChildBuffers();
4216                 return true;
4217         } else {
4218                 // save failed
4219                 // reset the old filename and unnamed state
4220                 setFileName(old_name);
4221                 setUnnamed(old_unnamed);
4222                 return false;
4223         }
4224 }
4225
4226
4227 // FIXME We could do better here, but it is complicated. What would be
4228 // nice is to offer either (a) to save the child buffer to an appropriate
4229 // location, so that it would "move with the master", or else (b) to update
4230 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4231 // complicated, because the code for this lives in GuiView.
4232 void Buffer::checkChildBuffers()
4233 {
4234         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4235         Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4236         for (; it != en; ++it) {
4237                 DocIterator dit = it->second;
4238                 Buffer * cbuf = const_cast<Buffer *>(it->first);
4239                 if (!cbuf || !theBufferList().isLoaded(cbuf))
4240                         continue;
4241                 Inset * inset = dit.nextInset();
4242                 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4243                 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4244                 docstring const & incfile = inset_inc->getParam("filename");
4245                 string oldloc = cbuf->absFileName();
4246                 string newloc = makeAbsPath(to_utf8(incfile),
4247                                 onlyPath(absFileName())).absFileName();
4248                 if (oldloc == newloc)
4249                         continue;
4250                 // the location of the child file is incorrect.
4251                 Alert::warning(_("Included File Invalid"),
4252                                 bformat(_("Saving this document to a new location has made the file:\n"
4253                                 "  %1$s\n"
4254                                 "inaccessible. You will need to update the included filename."),
4255                                 from_utf8(oldloc)));
4256                 cbuf->setParent(0);
4257                 inset_inc->setChildBuffer(0);
4258         }
4259         // invalidate cache of children
4260         d->children_positions.clear();
4261         d->position_to_children.clear();
4262 }
4263
4264 } // namespace lyx