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