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