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