]> git.lyx.org Git - lyx.git/blob - src/Buffer.cpp
Remove unused optional variable.
[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::PositionScopeBufferMap::iterator it = d->position_to_children.begin();
453         Impl::PositionScopeBufferMap::iterator end = d->position_to_children.end();
454         for (; it != end; ++it) {
455                 DocIterator dit = it->first.clone(buffer_clone);
456                 dit.setBuffer(buffer_clone);
457                 Buffer * child = const_cast<Buffer *>(it->second.second);
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                 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
470                 buffer_clone->setChild(dit, child_clone);
471         }
472         buffer_clone->d->macro_lock = false;
473         return;
474 }
475
476
477 bool Buffer::isClone() const
478 {
479         return d->cloned_buffer_;
480 }
481
482
483 void Buffer::changed(bool update_metrics) const
484 {
485         if (d->wa_)
486                 d->wa_->redrawAll(update_metrics);
487 }
488
489
490 frontend::WorkAreaManager & Buffer::workAreaManager() const
491 {
492         LASSERT(d->wa_, /**/);
493         return *d->wa_;
494 }
495
496
497 Text & Buffer::text() const
498 {
499         return d->inset->text();
500 }
501
502
503 Inset & Buffer::inset() const
504 {
505         return *d->inset;
506 }
507
508
509 BufferParams & Buffer::params()
510 {
511         return d->params;
512 }
513
514
515 BufferParams const & Buffer::params() const
516 {
517         return d->params;
518 }
519
520
521 ParagraphList & Buffer::paragraphs()
522 {
523         return text().paragraphs();
524 }
525
526
527 ParagraphList const & Buffer::paragraphs() const
528 {
529         return text().paragraphs();
530 }
531
532
533 LyXVC & Buffer::lyxvc()
534 {
535         return d->lyxvc;
536 }
537
538
539 LyXVC const & Buffer::lyxvc() const
540 {
541         return d->lyxvc;
542 }
543
544
545 string const Buffer::temppath() const
546 {
547         return d->temppath.absFileName();
548 }
549
550
551 TexRow & Buffer::texrow()
552 {
553         return d->texrow;
554 }
555
556
557 TexRow const & Buffer::texrow() const
558 {
559         return d->texrow;
560 }
561
562
563 TocBackend & Buffer::tocBackend() const
564 {
565         return d->toc_backend;
566 }
567
568
569 Undo & Buffer::undo()
570 {
571         return d->undo_;
572 }
573
574
575 void Buffer::setChild(DocIterator const & dit, Buffer * child)
576 {
577         d->children_positions[child] = dit;
578 }
579
580
581 string Buffer::latexName(bool const no_path) const
582 {
583         FileName latex_name =
584                 makeLatexName(d->exportFileName());
585         return no_path ? latex_name.onlyFileName()
586                 : latex_name.absFileName();
587 }
588
589
590 FileName Buffer::Impl::exportFileName() const
591 {
592         docstring const branch_suffix =
593                 params.branchlist().getFileNameSuffix();
594         if (branch_suffix.empty())
595                 return filename;
596
597         string const name = filename.onlyFileNameWithoutExt()
598                 + to_utf8(branch_suffix);
599         FileName res(filename.onlyPath().absFileName() + "/" + name);
600         res.changeExtension(filename.extension());
601
602         return res;
603 }
604
605
606 string Buffer::logName(LogType * type) const
607 {
608         string const filename = latexName(false);
609
610         if (filename.empty()) {
611                 if (type)
612                         *type = latexlog;
613                 return string();
614         }
615
616         string const path = temppath();
617
618         FileName const fname(addName(temppath(),
619                                      onlyFileName(changeExtension(filename,
620                                                                   ".log"))));
621
622         // FIXME: how do we know this is the name of the build log?
623         FileName const bname(
624                 addName(path, onlyFileName(
625                         changeExtension(filename,
626                                         formats.extension(params().bufferFormat()) + ".out"))));
627
628         // Also consider the master buffer log file
629         FileName masterfname = fname;
630         LogType mtype;
631         if (masterBuffer() != this) {
632                 string const mlogfile = masterBuffer()->logName(&mtype);
633                 masterfname = FileName(mlogfile);
634         }
635
636         // If no Latex log or Build log is newer, show Build log
637         if (bname.exists() &&
638             ((!fname.exists() && !masterfname.exists())
639              || (fname.lastModified() < bname.lastModified()
640                  && masterfname.lastModified() < bname.lastModified()))) {
641                 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
642                 if (type)
643                         *type = buildlog;
644                 return bname.absFileName();
645         // If we have a newer master file log or only a master log, show this
646         } else if (fname != masterfname
647                    && (!fname.exists() && (masterfname.exists()
648                    || fname.lastModified() < masterfname.lastModified()))) {
649                 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
650                 if (type)
651                         *type = mtype;
652                 return masterfname.absFileName();
653         }
654         LYXERR(Debug::FILES, "Log name calculated as: " << fname);
655         if (type)
656                         *type = latexlog;
657         return fname.absFileName();
658 }
659
660
661 void Buffer::setReadonly(bool const flag)
662 {
663         if (d->read_only != flag) {
664                 d->read_only = flag;
665                 changed(false);
666         }
667 }
668
669
670 void Buffer::setFileName(FileName const & fname)
671 {
672         d->filename = fname;
673         setReadonly(d->filename.isReadOnly());
674         saveCheckSum();
675         updateTitles();
676 }
677
678
679 int Buffer::readHeader(Lexer & lex)
680 {
681         int unknown_tokens = 0;
682         int line = -1;
683         int begin_header_line = -1;
684
685         // Initialize parameters that may be/go lacking in header:
686         params().branchlist().clear();
687         params().preamble.erase();
688         params().options.erase();
689         params().master.erase();
690         params().float_placement.erase();
691         params().paperwidth.erase();
692         params().paperheight.erase();
693         params().leftmargin.erase();
694         params().rightmargin.erase();
695         params().topmargin.erase();
696         params().bottommargin.erase();
697         params().headheight.erase();
698         params().headsep.erase();
699         params().footskip.erase();
700         params().columnsep.erase();
701         params().fonts_cjk.erase();
702         params().listings_params.clear();
703         params().clearLayoutModules();
704         params().clearRemovedModules();
705         params().clearIncludedChildren();
706         params().pdfoptions().clear();
707         params().indiceslist().clear();
708         params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
709         params().isbackgroundcolor = false;
710         params().fontcolor = lyx::rgbFromHexName("#000000");
711         params().isfontcolor = false;
712         params().notefontcolor = lyx::rgbFromHexName("#cccccc");
713         params().boxbgcolor = lyx::rgbFromHexName("#ff0000");
714         params().html_latex_start.clear();
715         params().html_latex_end.clear();
716         params().html_math_img_scale = 1.0;
717         params().output_sync_macro.erase();
718
719         for (int i = 0; i < 4; ++i) {
720                 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
721                 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
722         }
723
724         ErrorList & errorList = d->errorLists["Parse"];
725
726         while (lex.isOK()) {
727                 string token;
728                 lex >> token;
729
730                 if (token.empty())
731                         continue;
732
733                 if (token == "\\end_header")
734                         break;
735
736                 ++line;
737                 if (token == "\\begin_header") {
738                         begin_header_line = line;
739                         continue;
740                 }
741
742                 LYXERR(Debug::PARSER, "Handling document header token: `"
743                                       << token << '\'');
744
745                 string unknown = params().readToken(lex, token, d->filename.onlyPath());
746                 if (!unknown.empty()) {
747                         if (unknown[0] != '\\' && token == "\\textclass") {
748                                 Alert::warning(_("Unknown document class"),
749                        bformat(_("Using the default document class, because the "
750                                               "class %1$s is unknown."), from_utf8(unknown)));
751                         } else {
752                                 ++unknown_tokens;
753                                 docstring const s = bformat(_("Unknown token: "
754                                                                         "%1$s %2$s\n"),
755                                                          from_utf8(token),
756                                                          lex.getDocString());
757                                 errorList.push_back(ErrorItem(_("Document header error"),
758                                         s, -1, 0, 0));
759                         }
760                 }
761         }
762         if (begin_header_line) {
763                 docstring const s = _("\\begin_header is missing");
764                 errorList.push_back(ErrorItem(_("Document header error"),
765                         s, -1, 0, 0));
766         }
767
768         params().makeDocumentClass();
769
770         return unknown_tokens;
771 }
772
773
774 // Uwe C. Schroeder
775 // changed to be public and have one parameter
776 // Returns true if "\end_document" is not read (Asger)
777 bool Buffer::readDocument(Lexer & lex)
778 {
779         ErrorList & errorList = d->errorLists["Parse"];
780         errorList.clear();
781
782         // remove dummy empty par
783         paragraphs().clear();
784
785         if (!lex.checkFor("\\begin_document")) {
786                 docstring const s = _("\\begin_document is missing");
787                 errorList.push_back(ErrorItem(_("Document header error"),
788                         s, -1, 0, 0));
789         }
790
791         readHeader(lex);
792
793         if (params().outputChanges) {
794                 bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
795                 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
796                                   LaTeXFeatures::isAvailable("xcolor");
797
798                 if (!dvipost && !xcolorulem) {
799                         Alert::warning(_("Changes not shown in LaTeX output"),
800                                        _("Changes will not be highlighted in LaTeX output, "
801                                          "because neither dvipost nor xcolor/ulem are installed.\n"
802                                          "Please install these packages or redefine "
803                                          "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
804                 } else if (!xcolorulem) {
805                         Alert::warning(_("Changes not shown in LaTeX output"),
806                                        _("Changes will not be highlighted in LaTeX output "
807                                          "when using pdflatex, because xcolor and ulem are not installed.\n"
808                                          "Please install both packages or redefine "
809                                          "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
810                 }
811         }
812
813         if (!params().master.empty()) {
814                 FileName const master_file = makeAbsPath(params().master,
815                            onlyPath(absFileName()));
816                 if (isLyXFileName(master_file.absFileName())) {
817                         Buffer * master = 
818                                 checkAndLoadLyXFile(master_file, true);
819                         if (master) {
820                                 // necessary e.g. after a reload
821                                 // to re-register the child (bug 5873)
822                                 // FIXME: clean up updateMacros (here, only
823                                 // child registering is needed).
824                                 master->updateMacros();
825                                 // set master as master buffer, but only
826                                 // if we are a real child
827                                 if (master->isChild(this))
828                                         setParent(master);
829                                 // if the master is not fully loaded
830                                 // it is probably just loading this
831                                 // child. No warning needed then.
832                                 else if (master->isFullyLoaded())
833                                         LYXERR0("The master '"
834                                                 << params().master
835                                                 << "' assigned to this document ("
836                                                 << absFileName()
837                                                 << ") does not include "
838                                                 "this document. Ignoring the master assignment.");
839                         }
840                 }
841         }
842         
843         // assure we have a default index
844         params().indiceslist().addDefault(B_("Index"));
845
846         // read main text
847         bool const res = text().read(lex, errorList, d->inset);
848
849         // inform parent buffer about local macros
850         if (parent()) {
851                 Buffer const * pbuf = parent();
852                 UserMacroSet::const_iterator cit = usermacros.begin();
853                 UserMacroSet::const_iterator end = usermacros.end();
854                 for (; cit != end; ++cit)
855                         pbuf->usermacros.insert(*cit);
856         }
857         usermacros.clear();
858         updateMacros();
859         updateMacroInstances(InternalUpdate);
860         return res;
861 }
862
863
864 bool Buffer::readString(string const & s)
865 {
866         params().compressed = false;
867
868         Lexer lex;
869         istringstream is(s);
870         lex.setStream(is);
871         FileName const fn = FileName::tempName("Buffer_readString");
872
873         int file_format;
874         ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
875         if (ret_plf != ReadSuccess)
876                 return ret_plf;
877
878         if (file_format != LYX_FORMAT) {
879                 // We need to call lyx2lyx, so write the input to a file
880                 ofstream os(fn.toFilesystemEncoding().c_str());
881                 os << s;
882                 os.close();
883                 // lyxvc in readFile
884                 return readFile(fn) == ReadSuccess;
885         }
886
887         if (readDocument(lex))
888                 return false;
889         return true;
890 }
891
892
893 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
894 {
895         FileName fname(fn);
896         Lexer lex;
897         if (!lex.setFile(fname)) {
898                 Alert::error(_("File Not Found"),
899                         bformat(_("Unable to open file `%1$s'."), 
900                                 from_utf8(fn.absFileName())));
901                 return ReadFileNotFound;
902         }
903
904         int file_format;
905         ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
906         if (ret_plf != ReadSuccess)
907                 return ret_plf;
908
909         if (file_format != LYX_FORMAT) {
910                 FileName tmpFile;
911                 ReadStatus const ret_clf = convertLyXFormat(fn, tmpFile, file_format);
912                 if (ret_clf != ReadSuccess)
913                         return ret_clf;
914                 return readFile(tmpFile);
915         }
916
917         // FIXME: InsetInfo needs to know whether the file is under VCS 
918         // during the parse process, so this has to be done before.
919         lyxvc().file_found_hook(d->filename);
920
921         if (readDocument(lex)) {
922                 Alert::error(_("Document format failure"),
923                         bformat(_("%1$s ended unexpectedly, which means"
924                                 " that it is probably corrupted."),
925                                         from_utf8(fn.absFileName())));
926                 return ReadDocumentFailure;
927         }
928
929         d->file_fully_loaded = true;
930         d->read_only = !d->filename.isWritable();
931         params().compressed = d->filename.isZippedFile();
932         saveCheckSum();
933         return ReadSuccess;
934 }
935
936
937 bool Buffer::isFullyLoaded() const
938 {
939         return d->file_fully_loaded;
940 }
941
942
943 void Buffer::setFullyLoaded(bool value)
944 {
945         d->file_fully_loaded = value;
946 }
947
948
949 void Buffer::updatePreviews() const
950 {
951         if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
952                 thePreviews().generateBufferPreviews(*this);
953 }
954
955
956 void Buffer::removePreviews() const
957 {
958         thePreviews().removeLoader(*this);
959 }
960
961
962 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
963         FileName const & fn, int & file_format) const
964 {
965         if(!lex.checkFor("\\lyxformat")) {
966                 Alert::error(_("Document format failure"),
967                         bformat(_("%1$s is not a readable LyX document."),
968                                 from_utf8(fn.absFileName())));
969                 return ReadNoLyXFormat;
970         }       
971
972         string tmp_format;
973         lex >> tmp_format;
974
975         // LyX formats 217 and earlier were written as 2.17. This corresponds
976         // to files from LyX versions < 1.1.6.3. We just remove the dot in
977         // these cases. See also: www.lyx.org/trac/changeset/1313.
978         size_t dot = tmp_format.find_first_of(".,");
979         if (dot != string::npos)
980                 tmp_format.erase(dot, 1);
981
982         file_format = convert<int>(tmp_format);
983         return ReadSuccess;
984 }
985
986
987 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn, 
988         FileName & tmpfile, int from_format)
989 {
990         tmpfile = FileName::tempName("Buffer_convertLyXFormat");
991         if(tmpfile.empty()) {
992                 Alert::error(_("Conversion failed"),
993                         bformat(_("%1$s is from a different"
994                                 " version of LyX, but a temporary"
995                                 " file for converting it could"
996                                 " not be created."),
997                                 from_utf8(fn.absFileName())));
998                 return LyX2LyXNoTempFile;
999         }
1000
1001         FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1002         if (lyx2lyx.empty()) {
1003                 Alert::error(_("Conversion script not found"),
1004                      bformat(_("%1$s is from a different"
1005                                " version of LyX, but the"
1006                                " conversion script lyx2lyx"
1007                                " could not be found."),
1008                                from_utf8(fn.absFileName())));
1009                 return LyX2LyXNotFound;
1010         }
1011
1012         // Run lyx2lyx:
1013         //   $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1014         ostringstream command;
1015         command << os::python()
1016                 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1017                 << " -t " << convert<string>(LYX_FORMAT)
1018                 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
1019                 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1020         string const command_str = command.str();
1021
1022         LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1023
1024         cmd_ret const ret = runCommand(command_str);
1025         if (ret.first != 0) {
1026                 if (from_format < LYX_FORMAT) {
1027                         Alert::error(_("Conversion script failed"),
1028                                 bformat(_("%1$s is from an older version"
1029                                         " of LyX and the lyx2lyx script"
1030                                         " failed to convert it."),
1031                                         from_utf8(fn.absFileName())));
1032                         return LyX2LyXOlderFormat;
1033                 } else {
1034                         Alert::error(_("Conversion script failed"),
1035                                 bformat(_("%1$s is from a newer version"
1036                                         " of LyX and the lyx2lyx script"
1037                                         " failed to convert it."),
1038                                         from_utf8(fn.absFileName())));
1039                         return LyX2LyXNewerFormat;
1040                 }
1041         }
1042         return ReadSuccess;
1043 }
1044
1045
1046 // Should probably be moved to somewhere else: BufferView? GuiView?
1047 bool Buffer::save() const
1048 {
1049         docstring const file = makeDisplayPath(absFileName(), 20);
1050         d->filename.refresh();
1051
1052         // check the read-only status before moving the file as a backup
1053         if (d->filename.exists()) {
1054                 bool const read_only = !d->filename.isWritable();
1055                 if (read_only) {
1056                         Alert::warning(_("File is read-only"),
1057                                 bformat(_("The file %1$s cannot be written because it "
1058                                 "is marked as read-only."), file));
1059                         return false;
1060                 }
1061         }
1062
1063         // ask if the disk file has been externally modified (use checksum method)
1064         if (fileName().exists() && isExternallyModified(checksum_method)) {
1065                 docstring text = 
1066                         bformat(_("Document %1$s has been externally modified. "
1067                                 "Are you sure you want to overwrite this file?"), file);
1068                 int const ret = Alert::prompt(_("Overwrite modified file?"),
1069                         text, 1, 1, _("&Overwrite"), _("&Cancel"));
1070                 if (ret == 1)
1071                         return false;
1072         }
1073
1074         // We don't need autosaves in the immediate future. (Asger)
1075         resetAutosaveTimers();
1076
1077         FileName backupName;
1078         bool madeBackup = false;
1079
1080         // make a backup if the file already exists
1081         if (lyxrc.make_backup && fileName().exists()) {
1082                 backupName = FileName(absFileName() + '~');
1083                 if (!lyxrc.backupdir_path.empty()) {
1084                         string const mangledName =
1085                                 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1086                         backupName = FileName(addName(lyxrc.backupdir_path,
1087                                                       mangledName));
1088                 }
1089
1090                 // Except file is symlink do not copy because of #6587.
1091                 // Hard links have bad luck.
1092                 if (fileName().isSymLink())
1093                         madeBackup = fileName().copyTo(backupName);
1094                 else
1095                         madeBackup = fileName().moveTo(backupName);
1096
1097                 if (!madeBackup) {
1098                         Alert::error(_("Backup failure"),
1099                                      bformat(_("Cannot create backup file %1$s.\n"
1100                                                "Please check whether the directory exists and is writable."),
1101                                              from_utf8(backupName.absFileName())));
1102                         //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1103                 }
1104         }
1105
1106         if (writeFile(d->filename)) {
1107                 markClean();
1108                 return true;
1109         } else {
1110                 // Saving failed, so backup is not backup
1111                 if (madeBackup)
1112                         backupName.moveTo(d->filename);
1113                 return false;
1114         }
1115 }
1116
1117
1118 bool Buffer::writeFile(FileName const & fname) const
1119 {
1120         // FIXME Do we need to do these here? I don't think writing
1121         // the LyX file depends upon it. (RGH)
1122         // updateBuffer();
1123         // updateMacroInstances();
1124
1125         if (d->read_only && fname == d->filename)
1126                 return false;
1127
1128         bool retval = false;
1129
1130         docstring const str = bformat(_("Saving document %1$s..."),
1131                 makeDisplayPath(fname.absFileName()));
1132         message(str);
1133
1134         string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1135
1136         if (params().compressed) {
1137                 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1138                 retval = ofs && write(ofs);
1139         } else {
1140                 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1141                 retval = ofs && write(ofs);
1142         }
1143
1144         if (!retval) {
1145                 message(str + _(" could not write file!"));
1146                 return false;
1147         }
1148
1149         // see bug 6587
1150         // removeAutosaveFile();
1151
1152         saveCheckSum();
1153         message(str + _(" done."));
1154
1155         return true;
1156 }
1157
1158
1159 docstring Buffer::emergencyWrite()
1160 {
1161         // No need to save if the buffer has not changed.
1162         if (isClean())
1163                 return docstring();
1164
1165         string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1166
1167         docstring user_message = bformat(
1168                 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1169
1170         // We try to save three places:
1171         // 1) Same place as document. Unless it is an unnamed doc.
1172         if (!isUnnamed()) {
1173                 string s = absFileName();
1174                 s += ".emergency";
1175                 LYXERR0("  " << s);
1176                 if (writeFile(FileName(s))) {
1177                         markClean();
1178                         user_message += "  " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1179                         return user_message;
1180                 } else {
1181                         user_message += "  " + _("Save failed! Trying again...\n");
1182                 }
1183         }
1184
1185         // 2) In HOME directory.
1186         string s = addName(Package::get_home_dir().absFileName(), absFileName());
1187         s += ".emergency";
1188         lyxerr << ' ' << s << endl;
1189         if (writeFile(FileName(s))) {
1190                 markClean();
1191                 user_message += "  " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1192                 return user_message;
1193         }
1194
1195         user_message += "  " + _("Save failed! Trying yet again...\n");
1196
1197         // 3) In "/tmp" directory.
1198         // MakeAbsPath to prepend the current
1199         // drive letter on OS/2
1200         s = addName(package().temp_dir().absFileName(), absFileName());
1201         s += ".emergency";
1202         lyxerr << ' ' << s << endl;
1203         if (writeFile(FileName(s))) {
1204                 markClean();
1205                 user_message += "  " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1206                 return user_message;
1207         }
1208
1209         user_message += "  " + _("Save failed! Bummer. Document is lost.");
1210         // Don't try again.
1211         markClean();
1212         return user_message;
1213 }
1214
1215
1216 bool Buffer::write(ostream & ofs) const
1217 {
1218 #ifdef HAVE_LOCALE
1219         // Use the standard "C" locale for file output.
1220         ofs.imbue(locale::classic());
1221 #endif
1222
1223         // The top of the file should not be written by params().
1224
1225         // write out a comment in the top of the file
1226         ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1227             << " created this file. For more info see http://www.lyx.org/\n"
1228             << "\\lyxformat " << LYX_FORMAT << "\n"
1229             << "\\begin_document\n";
1230
1231         /// For each author, set 'used' to true if there is a change
1232         /// by this author in the document; otherwise set it to 'false'.
1233         AuthorList::Authors::const_iterator a_it = params().authors().begin();
1234         AuthorList::Authors::const_iterator a_end = params().authors().end();
1235         for (; a_it != a_end; ++a_it)
1236                 a_it->setUsed(false);
1237
1238         ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1239         ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1240         for ( ; it != end; ++it)
1241                 it->checkAuthors(params().authors());
1242
1243         // now write out the buffer parameters.
1244         ofs << "\\begin_header\n";
1245         params().writeFile(ofs);
1246         ofs << "\\end_header\n";
1247
1248         // write the text
1249         ofs << "\n\\begin_body\n";
1250         text().write(ofs);
1251         ofs << "\n\\end_body\n";
1252
1253         // Write marker that shows file is complete
1254         ofs << "\\end_document" << endl;
1255
1256         // Shouldn't really be needed....
1257         //ofs.close();
1258
1259         // how to check if close went ok?
1260         // Following is an attempt... (BE 20001011)
1261
1262         // good() returns false if any error occured, including some
1263         //        formatting error.
1264         // bad()  returns true if something bad happened in the buffer,
1265         //        which should include file system full errors.
1266
1267         bool status = true;
1268         if (!ofs) {
1269                 status = false;
1270                 lyxerr << "File was not closed properly." << endl;
1271         }
1272
1273         return status;
1274 }
1275
1276
1277 bool Buffer::makeLaTeXFile(FileName const & fname,
1278                            string const & original_path,
1279                            OutputParams const & runparams_in,
1280                            bool output_preamble, bool output_body) const
1281 {
1282         OutputParams runparams = runparams_in;
1283
1284         // This is necessary for LuaTeX/XeTeX with tex fonts.
1285         // See FIXME in BufferParams::encoding()
1286         if (runparams.isFullUnicode())
1287                 runparams.encoding = encodings.fromLyXName("utf8-plain");
1288
1289         string const encoding = runparams.encoding->iconvName();
1290         LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1291
1292         ofdocstream ofs;
1293         try { ofs.reset(encoding); }
1294         catch (iconv_codecvt_facet_exception & e) {
1295                 lyxerr << "Caught iconv exception: " << e.what() << endl;
1296                 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1297                         "verify that the support software for your encoding (%1$s) is "
1298                         "properly installed"), from_ascii(encoding)));
1299                 return false;
1300         }
1301         if (!openFileWrite(ofs, fname))
1302                 return false;
1303
1304         //TexStream ts(ofs.rdbuf(), &texrow());
1305         ErrorList & errorList = d->errorLists["Export"];
1306         errorList.clear();
1307         bool failed_export = false;
1308         otexstream os(ofs, d->texrow);
1309
1310         // make sure we are ready to export
1311         // this needs to be done before we validate
1312         // FIXME Do we need to do this all the time? I.e., in children
1313         // of a master we are exporting?
1314         updateBuffer();
1315         updateMacroInstances(OutputUpdate);
1316
1317         try {
1318                 os.texrow().reset();
1319                 writeLaTeXSource(os, original_path,
1320                       runparams, output_preamble, output_body);
1321         }
1322         catch (EncodingException & e) {
1323                 odocstringstream ods;
1324                 ods.put(e.failed_char);
1325                 ostringstream oss;
1326                 oss << "0x" << hex << e.failed_char << dec;
1327                 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1328                                           " (code point %2$s)"),
1329                                           ods.str(), from_utf8(oss.str()));
1330                 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1331                                 "representable in the chosen encoding.\n"
1332                                 "Changing the document encoding to utf8 could help."),
1333                                 e.par_id, e.pos, e.pos + 1));
1334                 failed_export = true;
1335         }
1336         catch (iconv_codecvt_facet_exception & e) {
1337                 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1338                         _(e.what()), -1, 0, 0));
1339                 failed_export = true;
1340         }
1341         catch (exception const & e) {
1342                 errorList.push_back(ErrorItem(_("conversion failed"),
1343                         _(e.what()), -1, 0, 0));
1344                 failed_export = true;
1345         }
1346         catch (...) {
1347                 lyxerr << "Caught some really weird exception..." << endl;
1348                 lyx_exit(1);
1349         }
1350
1351         ofs.close();
1352         if (ofs.fail()) {
1353                 failed_export = true;
1354                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1355         }
1356
1357         errors("Export");
1358         return !failed_export;
1359 }
1360
1361
1362 void Buffer::writeLaTeXSource(otexstream & os,
1363                            string const & original_path,
1364                            OutputParams const & runparams_in,
1365                            bool const output_preamble, bool const output_body) const
1366 {
1367         // The child documents, if any, shall be already loaded at this point.
1368
1369         OutputParams runparams = runparams_in;
1370
1371         // Classify the unicode characters appearing in math insets
1372         Encodings::initUnicodeMath(*this);
1373
1374         // validate the buffer.
1375         LYXERR(Debug::LATEX, "  Validating buffer...");
1376         LaTeXFeatures features(*this, params(), runparams);
1377         validate(features);
1378         LYXERR(Debug::LATEX, "  Buffer validation done.");
1379
1380         // The starting paragraph of the coming rows is the
1381         // first paragraph of the document. (Asger)
1382         if (output_preamble && runparams.nice) {
1383                 os << "%% LyX " << lyx_version << " created this file.  "
1384                         "For more info, see http://www.lyx.org/.\n"
1385                         "%% Do not edit unless you really know what "
1386                         "you are doing.\n";
1387         }
1388         LYXERR(Debug::INFO, "lyx document header finished");
1389
1390         // There are a few differences between nice LaTeX and usual files:
1391         // usual is \batchmode and has a
1392         // special input@path to allow the including of figures
1393         // with either \input or \includegraphics (what figinsets do).
1394         // input@path is set when the actual parameter
1395         // original_path is set. This is done for usual tex-file, but not
1396         // for nice-latex-file. (Matthias 250696)
1397         // Note that input@path is only needed for something the user does
1398         // in the preamble, included .tex files or ERT, files included by
1399         // LyX work without it.
1400         if (output_preamble) {
1401                 if (!runparams.nice) {
1402                         // code for usual, NOT nice-latex-file
1403                         os << "\\batchmode\n"; // changed from \nonstopmode
1404                 }
1405                 if (!original_path.empty()) {
1406                         // FIXME UNICODE
1407                         // We don't know the encoding of inputpath
1408                         docstring const inputpath = from_utf8(support::latex_path(original_path));
1409                         docstring uncodable_glyphs;
1410                         Encoding const * const enc = runparams.encoding;
1411                         if (enc) {
1412                                 for (size_t n = 0; n < inputpath.size(); ++n) {
1413                                         docstring const glyph =
1414                                                 docstring(1, inputpath[n]);
1415                                         if (enc->latexChar(inputpath[n], true) != glyph) {
1416                                                 LYXERR0("Uncodable character '"
1417                                                         << glyph
1418                                                         << "' in input path!");
1419                                                 uncodable_glyphs += glyph;
1420                                         }
1421                                 }
1422                         }
1423
1424                         // warn user if we found uncodable glyphs.
1425                         if (!uncodable_glyphs.empty()) {
1426                                 frontend::Alert::warning(_("Uncodable character in file path"),
1427                                                 support::bformat(_("The path of your document\n"
1428                                                   "(%1$s)\n"
1429                                                   "contains glyphs that are unknown in the\n"
1430                                                   "current document encoding (namely %2$s).\n"
1431                                                   "This will likely result in incomplete output.\n\n"
1432                                                   "Choose an appropriate document encoding (such as utf8)\n"
1433                                                   "or change the file path name."), inputpath, uncodable_glyphs));
1434                         } else {
1435                                 os << "\\makeatletter\n"
1436                                    << "\\def\\input@path{{"
1437                                    << inputpath << "/}}\n"
1438                                    << "\\makeatother\n";
1439                         }
1440                 }
1441
1442                 // get parent macros (if this buffer has a parent) which will be
1443                 // written at the document begin further down.
1444                 MacroSet parentMacros;
1445                 listParentMacros(parentMacros, features);
1446
1447                 runparams.use_polyglossia = features.usePolyglossia();
1448                 // Write the preamble
1449                 runparams.use_babel = params().writeLaTeX(os, features,
1450                                                           d->filename.onlyPath());
1451
1452                 runparams.use_japanese = features.isRequired("japanese");
1453
1454                 if (!output_body)
1455                         return;
1456
1457                 // make the body.
1458                 os << "\\begin{document}\n";
1459
1460                 // output the parent macros
1461                 MacroSet::iterator it = parentMacros.begin();
1462                 MacroSet::iterator end = parentMacros.end();
1463                 for (; it != end; ++it) {
1464                         int num_lines = (*it)->write(os.os(), true);
1465                         os.texrow().newlines(num_lines);
1466                 }
1467                 
1468         } // output_preamble
1469
1470         os.texrow().start(paragraphs().begin()->id(), 0);
1471
1472         LYXERR(Debug::INFO, "preamble finished, now the body.");
1473
1474         // if we are doing a real file with body, even if this is the
1475         // child of some other buffer, let's cut the link here.
1476         // This happens for example if only a child document is printed.
1477         Buffer const * save_parent = 0;
1478         if (output_preamble) {
1479                 save_parent = d->parent();
1480                 d->setParent(0);
1481         }
1482
1483         // the real stuff
1484         latexParagraphs(*this, text(), os, runparams);
1485
1486         // Restore the parenthood if needed
1487         if (output_preamble)
1488                 d->setParent(save_parent);
1489
1490         // add this just in case after all the paragraphs
1491         os << endl;
1492
1493         if (output_preamble) {
1494                 os << "\\end{document}\n";
1495                 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1496         } else {
1497                 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1498         }
1499         runparams_in.encoding = runparams.encoding;
1500
1501         // Just to be sure. (Asger)
1502         os.texrow().newline();
1503
1504         //for (int i = 0; i<d->texrow.rows(); i++) {
1505         // int id,pos;
1506         // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1507         //      lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1508         //}
1509
1510         LYXERR(Debug::INFO, "Finished making LaTeX file.");
1511         LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1512 }
1513
1514
1515 void Buffer::makeDocBookFile(FileName const & fname,
1516                               OutputParams const & runparams,
1517                               bool const body_only) const
1518 {
1519         LYXERR(Debug::LATEX, "makeDocBookFile...");
1520
1521         ofdocstream ofs;
1522         if (!openFileWrite(ofs, fname))
1523                 return;
1524
1525         // make sure we are ready to export
1526         // this needs to be done before we validate
1527         updateBuffer();
1528         updateMacroInstances(OutputUpdate);
1529
1530         writeDocBookSource(ofs, fname.absFileName(), runparams, body_only);
1531
1532         ofs.close();
1533         if (ofs.fail())
1534                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1535 }
1536
1537
1538 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1539                              OutputParams const & runparams,
1540                              bool const only_body) const
1541 {
1542         LaTeXFeatures features(*this, params(), runparams);
1543         validate(features);
1544
1545         d->texrow.reset();
1546
1547         DocumentClass const & tclass = params().documentClass();
1548         string const top_element = tclass.latexname();
1549
1550         if (!only_body) {
1551                 if (runparams.flavor == OutputParams::XML)
1552                         os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1553
1554                 // FIXME UNICODE
1555                 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1556
1557                 // FIXME UNICODE
1558                 if (! tclass.class_header().empty())
1559                         os << from_ascii(tclass.class_header());
1560                 else if (runparams.flavor == OutputParams::XML)
1561                         os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1562                             << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1563                 else
1564                         os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1565
1566                 docstring preamble = from_utf8(params().preamble);
1567                 if (runparams.flavor != OutputParams::XML ) {
1568                         preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1569                         preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1570                         preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1571                         preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1572                 }
1573
1574                 string const name = runparams.nice
1575                         ? changeExtension(absFileName(), ".sgml") : fname;
1576                 preamble += features.getIncludedFiles(name);
1577                 preamble += features.getLyXSGMLEntities();
1578
1579                 if (!preamble.empty()) {
1580                         os << "\n [ " << preamble << " ]";
1581                 }
1582                 os << ">\n\n";
1583         }
1584
1585         string top = top_element;
1586         top += " lang=\"";
1587         if (runparams.flavor == OutputParams::XML)
1588                 top += params().language->code();
1589         else
1590                 top += params().language->code().substr(0, 2);
1591         top += '"';
1592
1593         if (!params().options.empty()) {
1594                 top += ' ';
1595                 top += params().options;
1596         }
1597
1598         os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1599             << " file was created by LyX " << lyx_version
1600             << "\n  See http://www.lyx.org/ for more information -->\n";
1601
1602         params().documentClass().counters().reset();
1603
1604         sgml::openTag(os, top);
1605         os << '\n';
1606         docbookParagraphs(text(), *this, os, runparams);
1607         sgml::closeTag(os, top_element);
1608 }
1609
1610
1611 void Buffer::makeLyXHTMLFile(FileName const & fname,
1612                               OutputParams const & runparams) 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);
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         return d->errorLists[type];
3159 }
3160
3161
3162 void Buffer::updateTocItem(std::string const & type,
3163         DocIterator const & dit) const
3164 {
3165         if (d->gui_)
3166                 d->gui_->updateTocItem(type, dit);
3167 }
3168
3169
3170 void Buffer::structureChanged() const
3171 {
3172         if (d->gui_)
3173                 d->gui_->structureChanged();
3174 }
3175
3176
3177 void Buffer::errors(string const & err, bool from_master) const
3178 {
3179         if (d->gui_)
3180                 d->gui_->errors(err, from_master);
3181 }
3182
3183
3184 void Buffer::message(docstring const & msg) const
3185 {
3186         if (d->gui_)
3187                 d->gui_->message(msg);
3188 }
3189
3190
3191 void Buffer::setBusy(bool on) const
3192 {
3193         if (d->gui_)
3194                 d->gui_->setBusy(on);
3195 }
3196
3197
3198 void Buffer::updateTitles() const
3199 {
3200         if (d->wa_)
3201                 d->wa_->updateTitles();
3202 }
3203
3204
3205 void Buffer::resetAutosaveTimers() const
3206 {
3207         if (d->gui_)
3208                 d->gui_->resetAutosaveTimers();
3209 }
3210
3211
3212 bool Buffer::hasGuiDelegate() const
3213 {
3214         return d->gui_;
3215 }
3216
3217
3218 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3219 {
3220         d->gui_ = gui;
3221 }
3222
3223
3224
3225 namespace {
3226
3227 class AutoSaveBuffer : public ForkedProcess {
3228 public:
3229         ///
3230         AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3231                 : buffer_(buffer), fname_(fname) {}
3232         ///
3233         virtual shared_ptr<ForkedProcess> clone() const
3234         {
3235                 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3236         }
3237         ///
3238         int start()
3239         {
3240                 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3241                                                  from_utf8(fname_.absFileName())));
3242                 return run(DontWait);
3243         }
3244 private:
3245         ///
3246         virtual int generateChild();
3247         ///
3248         Buffer const & buffer_;
3249         FileName fname_;
3250 };
3251
3252
3253 int AutoSaveBuffer::generateChild()
3254 {
3255 #if defined(__APPLE__)
3256         /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard) 
3257          *   We should use something else like threads.
3258          *
3259          * Since I do not know how to determine at run time what is the OS X
3260          * version, I just disable forking altogether for now (JMarc)
3261          */
3262         pid_t const pid = -1;
3263 #else
3264         // tmp_ret will be located (usually) in /tmp
3265         // will that be a problem?
3266         // Note that this calls ForkedCalls::fork(), so it's
3267         // ok cross-platform.
3268         pid_t const pid = fork();
3269         // If you want to debug the autosave
3270         // you should set pid to -1, and comment out the fork.
3271         if (pid != 0 && pid != -1)
3272                 return pid;
3273 #endif
3274
3275         // pid = -1 signifies that lyx was unable
3276         // to fork. But we will do the save
3277         // anyway.
3278         bool failed = false;
3279         FileName const tmp_ret = FileName::tempName("lyxauto");
3280         if (!tmp_ret.empty()) {
3281                 buffer_.writeFile(tmp_ret);
3282                 // assume successful write of tmp_ret
3283                 if (!tmp_ret.moveTo(fname_))
3284                         failed = true;
3285         } else
3286                 failed = true;
3287
3288         if (failed) {
3289                 // failed to write/rename tmp_ret so try writing direct
3290                 if (!buffer_.writeFile(fname_)) {
3291                         // It is dangerous to do this in the child,
3292                         // but safe in the parent, so...
3293                         if (pid == -1) // emit message signal.
3294                                 buffer_.message(_("Autosave failed!"));
3295                 }
3296         }
3297
3298         if (pid == 0) // we are the child so...
3299                 _exit(0);
3300
3301         return pid;
3302 }
3303
3304 } // namespace anon
3305
3306
3307 FileName Buffer::getEmergencyFileName() const
3308 {
3309         return FileName(d->filename.absFileName() + ".emergency");
3310 }
3311
3312
3313 FileName Buffer::getAutosaveFileName() const
3314 {
3315         // if the document is unnamed try to save in the backup dir, else
3316         // in the default document path, and as a last try in the filePath, 
3317         // which will most often be the temporary directory
3318         string fpath;
3319         if (isUnnamed())
3320                 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3321                         : lyxrc.backupdir_path;
3322         if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3323                 fpath = filePath();
3324
3325         string const fname = "#" + d->filename.onlyFileName() + "#";
3326
3327         return makeAbsPath(fname, fpath);
3328 }
3329
3330
3331 void Buffer::removeAutosaveFile() const
3332 {
3333         FileName const f = getAutosaveFileName();
3334         if (f.exists())
3335                 f.removeFile();
3336 }
3337
3338
3339 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3340 {
3341         FileName const newauto = getAutosaveFileName();
3342         oldauto.refresh();
3343         if (newauto != oldauto && oldauto.exists())
3344                 if (!oldauto.moveTo(newauto))
3345                         LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3346 }
3347
3348
3349 bool Buffer::autoSave() const 
3350 {
3351         Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3352         if (buf->d->bak_clean || isReadonly())
3353                 return true;
3354
3355         message(_("Autosaving current document..."));
3356         buf->d->bak_clean = true;
3357         
3358         FileName const fname = getAutosaveFileName();
3359         if (d->cloned_buffer_) {
3360                 // If this buffer is cloned, we assume that
3361                 // we are running in a separate thread already.
3362                 FileName const tmp_ret = FileName::tempName("lyxauto");
3363                 if (!tmp_ret.empty()) {
3364                         writeFile(tmp_ret);
3365                         // assume successful write of tmp_ret
3366                         if (tmp_ret.moveTo(fname))
3367                                 return true;
3368                 }
3369                 // failed to write/rename tmp_ret so try writing direct
3370                 return writeFile(fname);
3371         } else {        
3372                 /// This function is deprecated as the frontend needs to take care
3373                 /// of cloning the buffer and autosaving it in another thread. It
3374                 /// is still here to allow (QT_VERSION < 0x040400).
3375                 AutoSaveBuffer autosave(*this, fname);
3376                 autosave.start();
3377                 return true;
3378         }
3379 }
3380
3381
3382 namespace {
3383         // helper class, to guarantee this gets reset properly
3384         class MarkAsExporting   {
3385         public:
3386                 MarkAsExporting(Buffer const * buf) : buf_(buf) 
3387                 {
3388                         LASSERT(buf_, /* */);
3389                         buf_->setExportStatus(true);
3390                 }
3391                 ~MarkAsExporting() 
3392                 {
3393                         buf_->setExportStatus(false);
3394                 }
3395         private:
3396                 Buffer const * const buf_;
3397         };
3398 }
3399
3400
3401 void Buffer::setExportStatus(bool e) const
3402 {
3403         d->doing_export = e;    
3404         ListOfBuffers clist = getDescendents();
3405         ListOfBuffers::const_iterator cit = clist.begin();
3406         ListOfBuffers::const_iterator const cen = clist.end();
3407         for (; cit != cen; ++cit)
3408                 (*cit)->d->doing_export = e;
3409 }
3410
3411
3412 bool Buffer::isExporting() const
3413 {
3414         return d->doing_export;
3415 }
3416
3417
3418 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3419         bool includeall, string & result_file) const
3420 {
3421         MarkAsExporting exporting(this);
3422         string backend_format;
3423         OutputParams runparams(&params().encoding());
3424         runparams.flavor = OutputParams::LATEX;
3425         runparams.linelen = lyxrc.plaintext_linelen;
3426         runparams.includeall = includeall;
3427         vector<string> backs = params().backends();
3428         Converters converters = theConverters();
3429         if (find(backs.begin(), backs.end(), format) == backs.end()) {
3430                 // Get shortest path to format
3431                 converters.buildGraph();
3432                 Graph::EdgePath path;
3433                 for (vector<string>::const_iterator it = backs.begin();
3434                      it != backs.end(); ++it) {
3435                         Graph::EdgePath p = converters.getPath(*it, format);
3436                         if (!p.empty() && (path.empty() || p.size() < path.size())) {
3437                                 backend_format = *it;
3438                                 path = p;
3439                         }
3440                 }
3441                 if (path.empty()) {
3442                         if (!put_in_tempdir) {
3443                                 // Only show this alert if this is an export to a non-temporary
3444                                 // file (not for previewing).
3445                                 Alert::error(_("Couldn't export file"), bformat(
3446                                         _("No information for exporting the format %1$s."),
3447                                         formats.prettyName(format)));
3448                         }
3449                         return false;
3450                 }
3451                 runparams.flavor = converters.getFlavor(path);
3452
3453         } else {
3454                 backend_format = format;
3455                 // FIXME: Don't hardcode format names here, but use a flag
3456                 if (backend_format == "pdflatex")
3457                         runparams.flavor = OutputParams::PDFLATEX;
3458                 else if (backend_format == "luatex")
3459                         runparams.flavor = OutputParams::LUATEX;
3460                 else if (backend_format == "xetex")
3461                         runparams.flavor = OutputParams::XETEX;
3462         }
3463
3464         string filename = latexName(false);
3465         filename = addName(temppath(), filename);
3466         filename = changeExtension(filename,
3467                                    formats.extension(backend_format));
3468
3469         // Plain text backend
3470         if (backend_format == "text") {
3471                 runparams.flavor = OutputParams::TEXT;
3472                 writePlaintextFile(*this, FileName(filename), runparams);
3473         }
3474         // HTML backend
3475         else if (backend_format == "xhtml") {
3476                 runparams.flavor = OutputParams::HTML;
3477                 switch (params().html_math_output) {
3478                 case BufferParams::MathML: 
3479                         runparams.math_flavor = OutputParams::MathAsMathML; 
3480                         break;
3481                 case BufferParams::HTML: 
3482                         runparams.math_flavor = OutputParams::MathAsHTML; 
3483                         break;
3484                 case BufferParams::Images:
3485                         runparams.math_flavor = OutputParams::MathAsImages; 
3486                         break;
3487                 case BufferParams::LaTeX:
3488                         runparams.math_flavor = OutputParams::MathAsLaTeX; 
3489                         break;
3490                 }
3491                 makeLyXHTMLFile(FileName(filename), runparams);
3492         } else if (backend_format == "lyx")
3493                 writeFile(FileName(filename));
3494         // Docbook backend
3495         else if (params().isDocBook()) {
3496                 runparams.nice = !put_in_tempdir;
3497                 makeDocBookFile(FileName(filename), runparams);
3498         }
3499         // LaTeX backend
3500         else if (backend_format == format) {
3501                 runparams.nice = true;
3502                 if (!makeLaTeXFile(FileName(filename), string(), runparams)) {
3503                         if (d->cloned_buffer_) {
3504                                 d->cloned_buffer_->d->errorLists["Export"] =
3505                                         d->errorLists["Export"];
3506                         }
3507                         return false;
3508                 }
3509         } else if (!lyxrc.tex_allows_spaces
3510                    && contains(filePath(), ' ')) {
3511                 Alert::error(_("File name error"),
3512                            _("The directory path to the document cannot contain spaces."));
3513                 return false;
3514         } else {
3515                 runparams.nice = false;
3516                 if (!makeLaTeXFile(FileName(filename), filePath(), runparams)) {
3517                         if (d->cloned_buffer_) {
3518                                 d->cloned_buffer_->d->errorLists["Export"] =
3519                                         d->errorLists["Export"];
3520                         }
3521                         return false;
3522                 }
3523         }
3524
3525         string const error_type = (format == "program")
3526                 ? "Build" : params().bufferFormat();
3527         ErrorList & error_list = d->errorLists[error_type];
3528         string const ext = formats.extension(format);
3529         FileName const tmp_result_file(changeExtension(filename, ext));
3530         bool const success = converters.convert(this, FileName(filename),
3531                 tmp_result_file, FileName(absFileName()), backend_format, format,
3532                 error_list);
3533
3534         // Emit the signal to show the error list or copy it back to the
3535         // cloned Buffer so that it can be emitted afterwards.
3536         if (format != backend_format) {
3537                 if (d->cloned_buffer_) {
3538                         d->cloned_buffer_->d->errorLists[error_type] = 
3539                                 d->errorLists[error_type];
3540                 } else 
3541                         errors(error_type);
3542                 // also to the children, in case of master-buffer-view
3543                 ListOfBuffers clist = getDescendents();
3544                 ListOfBuffers::const_iterator cit = clist.begin();
3545                 ListOfBuffers::const_iterator const cen = clist.end();
3546                 for (; cit != cen; ++cit) {
3547                         if (d->cloned_buffer_) {
3548                                 // Enable reverse search by copying back the
3549                                 // texrow object to the cloned buffer.
3550                                 // FIXME: this is not thread safe.
3551                                 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
3552                                 (*cit)->d->cloned_buffer_->d->errorLists[error_type] = 
3553                                         (*cit)->d->errorLists[error_type];
3554                         } else
3555                                 (*cit)->errors(error_type, true);
3556                 }
3557         }
3558
3559         if (d->cloned_buffer_) {
3560                 // Enable reverse dvi or pdf to work by copying back the texrow
3561                 // object to the cloned buffer.
3562                 // FIXME: There is a possibility of concurrent access to texrow
3563                 // here from the main GUI thread that should be securized.
3564                 d->cloned_buffer_->d->texrow = d->texrow;
3565                 string const error_type = params().bufferFormat();
3566                 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
3567         }
3568
3569         if (!success)
3570                 return false;
3571
3572         if (put_in_tempdir) {
3573                 result_file = tmp_result_file.absFileName();
3574                 return true;
3575         }
3576
3577         result_file = changeExtension(d->exportFileName().absFileName(), ext);
3578         // We need to copy referenced files (e. g. included graphics
3579         // if format == "dvi") to the result dir.
3580         vector<ExportedFile> const files =
3581                 runparams.exportdata->externalFiles(format);
3582         string const dest = onlyPath(result_file);
3583         bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
3584                                  : force_overwrite == ALL_FILES;
3585         CopyStatus status = use_force ? FORCE : SUCCESS;
3586         
3587         vector<ExportedFile>::const_iterator it = files.begin();
3588         vector<ExportedFile>::const_iterator const en = files.end();
3589         for (; it != en && status != CANCEL; ++it) {
3590                 string const fmt = formats.getFormatFromFile(it->sourceName);
3591                 status = copyFile(fmt, it->sourceName,
3592                         makeAbsPath(it->exportName, dest),
3593                         it->exportName, status == FORCE);
3594         }
3595
3596         if (status == CANCEL) {
3597                 message(_("Document export cancelled."));
3598         } else if (tmp_result_file.exists()) {
3599                 // Finally copy the main file
3600                 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
3601                                     : force_overwrite != NO_FILES;
3602                 if (status == SUCCESS && use_force)
3603                         status = FORCE;
3604                 status = copyFile(format, tmp_result_file,
3605                         FileName(result_file), result_file,
3606                         status == FORCE);
3607                 message(bformat(_("Document exported as %1$s "
3608                         "to file `%2$s'"),
3609                         formats.prettyName(format),
3610                         makeDisplayPath(result_file)));
3611         } else {
3612                 // This must be a dummy converter like fax (bug 1888)
3613                 message(bformat(_("Document exported as %1$s"),
3614                         formats.prettyName(format)));
3615         }
3616
3617         return true;
3618 }
3619
3620
3621 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3622                       bool includeall) const
3623 {
3624         string result_file;
3625         // (1) export with all included children (omit \includeonly)
3626         if (includeall && !doExport(format, put_in_tempdir, true, result_file))
3627                 return false;
3628         // (2) export with included children only
3629         return doExport(format, put_in_tempdir, false, result_file);
3630 }
3631
3632
3633 bool Buffer::preview(string const & format, bool includeall) const
3634 {
3635         MarkAsExporting exporting(this);
3636         string result_file;
3637         // (1) export with all included children (omit \includeonly)
3638         if (includeall && !doExport(format, true, true))
3639                 return false;
3640         // (2) export with included children only
3641         if (!doExport(format, true, false, result_file))
3642                 return false;
3643         return formats.view(*this, FileName(result_file), format);
3644 }
3645
3646
3647 Buffer::ReadStatus Buffer::extractFromVC()
3648 {
3649         bool const found = LyXVC::file_not_found_hook(d->filename);
3650         if (!found)
3651                 return ReadFileNotFound;
3652         if (!d->filename.isReadableFile())
3653                 return ReadVCError;
3654         return ReadSuccess;
3655 }
3656
3657
3658 Buffer::ReadStatus Buffer::loadEmergency()
3659 {
3660         FileName const emergencyFile = getEmergencyFileName();
3661         if (!emergencyFile.exists() 
3662                   || emergencyFile.lastModified() <= d->filename.lastModified())
3663                 return ReadFileNotFound;
3664
3665         docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
3666         docstring const text = bformat(_("An emergency save of the document "
3667                 "%1$s exists.\n\nRecover emergency save?"), file);
3668         
3669         int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
3670                 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
3671
3672         switch (load_emerg)
3673         {
3674         case 0: {
3675                 docstring str;
3676                 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
3677                 bool const success = (ret_llf == ReadSuccess);
3678                 if (success) {
3679                         if (isReadonly()) {
3680                                 Alert::warning(_("File is read-only"),
3681                                         bformat(_("An emergency file is successfully loaded, "
3682                                         "but the original file %1$s is marked read-only. "
3683                                         "Please make sure to save the document as a different "
3684                                         "file."), from_utf8(d->filename.absFileName())));
3685                         }
3686                         markDirty();
3687                         str = _("Document was successfully recovered.");
3688                 } else
3689                         str = _("Document was NOT successfully recovered.");
3690                 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3691                         makeDisplayPath(emergencyFile.absFileName()));
3692
3693                 int const del_emerg = 
3694                         Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3695                                 _("&Remove"), _("&Keep"));
3696                 if (del_emerg == 0) {
3697                         emergencyFile.removeFile();
3698                         if (success)
3699                                 Alert::warning(_("Emergency file deleted"),
3700                                         _("Do not forget to save your file now!"), true);
3701                         }
3702                 return success ? ReadSuccess : ReadEmergencyFailure;
3703         }
3704         case 1: {
3705                 int const del_emerg =
3706                         Alert::prompt(_("Delete emergency file?"),
3707                                 _("Remove emergency file now?"), 1, 1,
3708                                 _("&Remove"), _("&Keep"));
3709                 if (del_emerg == 0)
3710                         emergencyFile.removeFile();
3711                 return ReadOriginal;
3712         }
3713
3714         default:
3715                 break;
3716         }
3717         return ReadCancel;
3718 }
3719
3720
3721 Buffer::ReadStatus Buffer::loadAutosave()
3722 {
3723         // Now check if autosave file is newer.
3724         FileName const autosaveFile = getAutosaveFileName();
3725         if (!autosaveFile.exists() 
3726                   || autosaveFile.lastModified() <= d->filename.lastModified()) 
3727                 return ReadFileNotFound;
3728
3729         docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
3730         docstring const text = bformat(_("The backup of the document %1$s " 
3731                 "is newer.\n\nLoad the backup instead?"), file);
3732         int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
3733                 _("&Load backup"), _("Load &original"), _("&Cancel"));
3734         
3735         switch (ret)
3736         {
3737         case 0: {
3738                 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
3739                 // the file is not saved if we load the autosave file.
3740                 if (ret_llf == ReadSuccess) {
3741                         if (isReadonly()) {
3742                                 Alert::warning(_("File is read-only"),
3743                                         bformat(_("A backup file is successfully loaded, "
3744                                         "but the original file %1$s is marked read-only. "
3745                                         "Please make sure to save the document as a "
3746                                         "different file."), 
3747                                         from_utf8(d->filename.absFileName())));
3748                         }
3749                         markDirty();
3750                         return ReadSuccess;
3751                 }
3752                 return ReadAutosaveFailure;
3753         }
3754         case 1:
3755                 // Here we delete the autosave
3756                 autosaveFile.removeFile();
3757                 return ReadOriginal;
3758         default:
3759                 break;
3760         }
3761         return ReadCancel;
3762 }
3763
3764
3765 Buffer::ReadStatus Buffer::loadLyXFile()
3766 {
3767         if (!d->filename.isReadableFile()) {
3768                 ReadStatus const ret_rvc = extractFromVC();
3769                 if (ret_rvc != ReadSuccess)
3770                         return ret_rvc;
3771         }
3772
3773         ReadStatus const ret_re = loadEmergency();
3774         if (ret_re == ReadSuccess || ret_re == ReadCancel)
3775                 return ret_re;
3776         
3777         ReadStatus const ret_ra = loadAutosave();
3778         if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
3779                 return ret_ra;
3780
3781         return loadThisLyXFile(d->filename);
3782 }
3783
3784
3785 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
3786 {
3787         return readFile(fn);
3788 }
3789
3790
3791 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3792 {
3793         TeXErrors::Errors::const_iterator it = terr.begin();
3794         TeXErrors::Errors::const_iterator end = terr.end();
3795         ListOfBuffers clist = getDescendents();
3796         ListOfBuffers::const_iterator cen = clist.end();
3797
3798         for (; it != end; ++it) {
3799                 int id_start = -1;
3800                 int pos_start = -1;
3801                 int errorRow = it->error_in_line;
3802                 Buffer const * buf = 0;
3803                 Impl const * p = d;
3804                 if (it->child_name.empty())
3805                     p->texrow.getIdFromRow(errorRow, id_start, pos_start);
3806                 else {
3807                         // The error occurred in a child
3808                         ListOfBuffers::const_iterator cit = clist.begin();
3809                         for (; cit != cen; ++cit) {
3810                                 string const child_name =
3811                                         DocFileName(changeExtension(
3812                                                 (*cit)->absFileName(), "tex")).
3813                                                         mangledFileName();
3814                                 if (it->child_name != child_name)
3815                                         continue;
3816                                 (*cit)->d->texrow.getIdFromRow(errorRow,
3817                                                         id_start, pos_start);
3818                                 if (id_start != -1) {
3819                                         buf = d->cloned_buffer_
3820                                                 ? (*cit)->d->cloned_buffer_->d->owner_
3821                                                 : (*cit)->d->owner_;
3822                                         p = (*cit)->d;
3823                                         break;
3824                                 }
3825                         }
3826                 }
3827                 int id_end = -1;
3828                 int pos_end = -1;
3829                 bool found;
3830                 do {
3831                         ++errorRow;
3832                         found = p->texrow.getIdFromRow(errorRow, id_end, pos_end);
3833                 } while (found && id_start == id_end && pos_start == pos_end);
3834
3835                 if (id_start != id_end) {
3836                         // Next registered position is outside the inset where
3837                         // the error occurred, so signal end-of-paragraph
3838                         pos_end = 0;
3839                 }
3840
3841                 errorList.push_back(ErrorItem(it->error_desc,
3842                         it->error_text, id_start, pos_start, pos_end, buf));
3843         }
3844 }
3845
3846
3847 void Buffer::setBuffersForInsets() const
3848 {
3849         inset().setBuffer(const_cast<Buffer &>(*this)); 
3850 }
3851
3852
3853 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
3854 {
3855         // Use the master text class also for child documents
3856         Buffer const * const master = masterBuffer();
3857         DocumentClass const & textclass = master->params().documentClass();
3858         
3859         // do this only if we are the top-level Buffer
3860         if (master == this)
3861                 reloadBibInfoCache();
3862
3863         // keep the buffers to be children in this set. If the call from the
3864         // master comes back we can see which of them were actually seen (i.e.
3865         // via an InsetInclude). The remaining ones in the set need still be updated.
3866         static std::set<Buffer const *> bufToUpdate;
3867         if (scope == UpdateMaster) {
3868                 // If this is a child document start with the master
3869                 if (master != this) {
3870                         bufToUpdate.insert(this);
3871                         master->updateBuffer(UpdateMaster, utype);
3872                         // Do this here in case the master has no gui associated with it. Then, 
3873                         // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3874                         if (!master->d->gui_)
3875                                 structureChanged();
3876
3877                         // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3878                         if (bufToUpdate.find(this) == bufToUpdate.end())
3879                                 return;
3880                 }
3881
3882                 // start over the counters in the master
3883                 textclass.counters().reset();
3884         }
3885
3886         // update will be done below for this buffer
3887         bufToUpdate.erase(this);
3888
3889         // update all caches
3890         clearReferenceCache();
3891         updateMacros();
3892
3893         Buffer & cbuf = const_cast<Buffer &>(*this);
3894
3895         LASSERT(!text().paragraphs().empty(), /**/);
3896
3897         // do the real work
3898         ParIterator parit = cbuf.par_iterator_begin();
3899         updateBuffer(parit, utype);
3900
3901         if (master != this)
3902                 // TocBackend update will be done later.
3903                 return;
3904
3905         d->bibinfo_cache_valid_ = true;
3906         d->cite_labels_valid_ = true;
3907         cbuf.tocBackend().update();
3908         if (scope == UpdateMaster)
3909                 cbuf.structureChanged();
3910 }
3911
3912
3913 static depth_type getDepth(DocIterator const & it)
3914 {
3915         depth_type depth = 0;
3916         for (size_t i = 0 ; i < it.depth() ; ++i)
3917                 if (!it[i].inset().inMathed())
3918                         depth += it[i].paragraph().getDepth() + 1;
3919         // remove 1 since the outer inset does not count
3920         return depth - 1;
3921 }
3922
3923 static depth_type getItemDepth(ParIterator const & it)
3924 {
3925         Paragraph const & par = *it;
3926         LabelType const labeltype = par.layout().labeltype;
3927
3928         if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3929                 return 0;
3930
3931         // this will hold the lowest depth encountered up to now.
3932         depth_type min_depth = getDepth(it);
3933         ParIterator prev_it = it;
3934         while (true) {
3935                 if (prev_it.pit())
3936                         --prev_it.top().pit();
3937                 else {
3938                         // start of nested inset: go to outer par
3939                         prev_it.pop_back();
3940                         if (prev_it.empty()) {
3941                                 // start of document: nothing to do
3942                                 return 0;
3943                         }
3944                 }
3945
3946                 // We search for the first paragraph with same label
3947                 // that is not more deeply nested.
3948                 Paragraph & prev_par = *prev_it;
3949                 depth_type const prev_depth = getDepth(prev_it);
3950                 if (labeltype == prev_par.layout().labeltype) {
3951                         if (prev_depth < min_depth)
3952                                 return prev_par.itemdepth + 1;
3953                         if (prev_depth == min_depth)
3954                                 return prev_par.itemdepth;
3955                 }
3956                 min_depth = min(min_depth, prev_depth);
3957                 // small optimization: if we are at depth 0, we won't
3958                 // find anything else
3959                 if (prev_depth == 0)
3960                         return 0;
3961         }
3962 }
3963
3964
3965 static bool needEnumCounterReset(ParIterator const & it)
3966 {
3967         Paragraph const & par = *it;
3968         LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3969         depth_type const cur_depth = par.getDepth();
3970         ParIterator prev_it = it;
3971         while (prev_it.pit()) {
3972                 --prev_it.top().pit();
3973                 Paragraph const & prev_par = *prev_it;
3974                 if (prev_par.getDepth() <= cur_depth)
3975                         return  prev_par.layout().labeltype != LABEL_ENUMERATE;
3976         }
3977         // start of nested inset: reset
3978         return true;
3979 }
3980
3981
3982 // set the label of a paragraph. This includes the counters.
3983 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
3984 {
3985         BufferParams const & bp = owner_->masterBuffer()->params();
3986         DocumentClass const & textclass = bp.documentClass();
3987         Paragraph & par = it.paragraph();
3988         Layout const & layout = par.layout();
3989         Counters & counters = textclass.counters();
3990
3991         if (par.params().startOfAppendix()) {
3992                 // FIXME: only the counter corresponding to toplevel
3993                 // sectioning should be reset
3994                 counters.reset();
3995                 counters.appendix(true);
3996         }
3997         par.params().appendix(counters.appendix());
3998
3999         // Compute the item depth of the paragraph
4000         par.itemdepth = getItemDepth(it);
4001
4002         if (layout.margintype == MARGIN_MANUAL) {
4003                 if (par.params().labelWidthString().empty())
4004                         par.params().labelWidthString(par.expandLabel(layout, bp));
4005         } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4006                 // we do not need to do anything here, since the empty case is
4007                 // handled during export.
4008         } else {
4009                 par.params().labelWidthString(docstring());
4010         }
4011
4012         switch(layout.labeltype) {
4013         case LABEL_COUNTER:
4014                 if (layout.toclevel <= bp.secnumdepth
4015                       && (layout.latextype != LATEX_ENVIRONMENT
4016                           || it.text()->isFirstInSequence(it.pit()))) {
4017                         if (counters.hasCounter(layout.counter))
4018                                 counters.step(layout.counter, utype);
4019                         par.params().labelString(par.expandLabel(layout, bp));
4020                 } else
4021                         par.params().labelString(docstring());
4022                 break;
4023
4024         case LABEL_ITEMIZE: {
4025                 // At some point of time we should do something more
4026                 // clever here, like:
4027                 //   par.params().labelString(
4028                 //    bp.user_defined_bullet(par.itemdepth).getText());
4029                 // for now, use a simple hardcoded label
4030                 docstring itemlabel;
4031                 switch (par.itemdepth) {
4032                 case 0:
4033                         itemlabel = char_type(0x2022);
4034                         break;
4035                 case 1:
4036                         itemlabel = char_type(0x2013);
4037                         break;
4038                 case 2:
4039                         itemlabel = char_type(0x2217);
4040                         break;
4041                 case 3:
4042                         itemlabel = char_type(0x2219); // or 0x00b7
4043                         break;
4044                 }
4045                 par.params().labelString(itemlabel);
4046                 break;
4047         }
4048
4049         case LABEL_ENUMERATE: {
4050                 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4051
4052                 switch (par.itemdepth) {
4053                 case 2:
4054                         enumcounter += 'i';
4055                 case 1:
4056                         enumcounter += 'i';
4057                 case 0:
4058                         enumcounter += 'i';
4059                         break;
4060                 case 3:
4061                         enumcounter += "iv";
4062                         break;
4063                 default:
4064                         // not a valid enumdepth...
4065                         break;
4066                 }
4067
4068                 // Maybe we have to reset the enumeration counter.
4069                 if (needEnumCounterReset(it))
4070                         counters.reset(enumcounter);
4071                 counters.step(enumcounter, utype);
4072
4073                 string const & lang = par.getParLanguage(bp)->code();
4074                 par.params().labelString(counters.theCounter(enumcounter, lang));
4075
4076                 break;
4077         }
4078
4079         case LABEL_SENSITIVE: {
4080                 string const & type = counters.current_float();
4081                 docstring full_label;
4082                 if (type.empty())
4083                         full_label = owner_->B_("Senseless!!! ");
4084                 else {
4085                         docstring name = owner_->B_(textclass.floats().getType(type).name());
4086                         if (counters.hasCounter(from_utf8(type))) {
4087                                 string const & lang = par.getParLanguage(bp)->code();
4088                                 counters.step(from_utf8(type), utype);
4089                                 full_label = bformat(from_ascii("%1$s %2$s:"), 
4090                                                      name, 
4091                                                      counters.theCounter(from_utf8(type), lang));
4092                         } else
4093                                 full_label = bformat(from_ascii("%1$s #:"), name);      
4094                 }
4095                 par.params().labelString(full_label);   
4096                 break;
4097         }
4098
4099         case LABEL_NO_LABEL:
4100                 par.params().labelString(docstring());
4101                 break;
4102
4103         case LABEL_MANUAL:
4104         case LABEL_TOP_ENVIRONMENT:
4105         case LABEL_CENTERED_TOP_ENVIRONMENT:
4106         case LABEL_STATIC:      
4107         case LABEL_BIBLIO:
4108                 par.params().labelString(par.expandLabel(layout, bp));
4109                 break;
4110         }
4111 }
4112
4113
4114 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4115 {
4116         LASSERT(parit.pit() == 0, /**/);
4117
4118         // Set the position of the text in the buffer to be able
4119         // to resolve macros in it.
4120         parit.text()->setMacrocontextPosition(parit);
4121
4122         depth_type maxdepth = 0;
4123         pit_type const lastpit = parit.lastpit();
4124         for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4125                 // reduce depth if necessary
4126                 parit->params().depth(min(parit->params().depth(), maxdepth));
4127                 maxdepth = parit->getMaxDepthAfter();
4128
4129                 if (utype == OutputUpdate) {
4130                         // track the active counters
4131                         // we have to do this for the master buffer, since the local
4132                         // buffer isn't tracking anything.
4133                         masterBuffer()->params().documentClass().counters().
4134                                         setActiveLayout(parit->layout());
4135                 }
4136                 
4137                 // set the counter for this paragraph
4138                 d->setLabel(parit, utype);
4139
4140                 // now the insets
4141                 InsetList::const_iterator iit = parit->insetList().begin();
4142                 InsetList::const_iterator end = parit->insetList().end();
4143                 for (; iit != end; ++iit) {
4144                         parit.pos() = iit->pos;
4145                         iit->inset->updateBuffer(parit, utype);
4146                 }
4147         }
4148 }
4149
4150
4151 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4152         WordLangTuple & word_lang, docstring_list & suggestions) const
4153 {
4154         int progress = 0;
4155         WordLangTuple wl;
4156         suggestions.clear();
4157         word_lang = WordLangTuple();
4158         // OK, we start from here.
4159         DocIterator const end = doc_iterator_end(this);
4160         for (; from != end; from.forwardPos()) {
4161                 // We are only interested in text so remove the math CursorSlice.
4162                 while (from.inMathed()) {
4163                         from.pop_back();
4164                         from.pos()++;
4165                 }
4166                 // If from is at the end of the document (which is possible
4167                 // when leaving the mathed) LyX will crash later.
4168                 if (from == end)
4169                         break;
4170                 to = from;
4171                 from.paragraph().spellCheck();
4172                 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4173                 if (SpellChecker::misspelled(res)) {
4174                         word_lang = wl;
4175                         break;
4176                 }
4177
4178                 // Do not increase progress when from == to, otherwise the word
4179                 // count will be wrong.
4180                 if (from != to) {
4181                         from = to;
4182                         ++progress;
4183                 }
4184         }
4185         return progress;
4186 }
4187
4188
4189 Buffer::ReadStatus Buffer::reload()
4190 {
4191         setBusy(true);
4192         // c.f. bug http://www.lyx.org/trac/ticket/6587
4193         removeAutosaveFile();
4194         // e.g., read-only status could have changed due to version control
4195         d->filename.refresh();
4196         docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4197
4198         ReadStatus const status = loadLyXFile();
4199         if (status == ReadSuccess) {
4200                 updateBuffer();
4201                 changed(true);
4202                 updateTitles();
4203                 markClean();
4204                 message(bformat(_("Document %1$s reloaded."), disp_fn));
4205                 d->undo_.clear();
4206         } else {
4207                 message(bformat(_("Could not reload document %1$s."), disp_fn));
4208         }       
4209         setBusy(false);
4210         removePreviews();
4211         updatePreviews();
4212         errors("Parse");
4213         return status;
4214 }
4215
4216
4217 bool Buffer::saveAs(FileName const & fn)
4218 {
4219         FileName const old_name = fileName();
4220         FileName const old_auto = getAutosaveFileName();
4221         bool const old_unnamed = isUnnamed();
4222
4223         setFileName(fn);
4224         markDirty();
4225         setUnnamed(false);
4226
4227         if (save()) {
4228                 // bring the autosave file with us, just in case.
4229                 moveAutosaveFile(old_auto);
4230                 // validate version control data and
4231                 // correct buffer title
4232                 lyxvc().file_found_hook(fileName());
4233                 updateTitles();
4234                 // the file has now been saved to the new location.
4235                 // we need to check that the locations of child buffers
4236                 // are still valid.
4237                 checkChildBuffers();
4238                 return true;
4239         } else {
4240                 // save failed
4241                 // reset the old filename and unnamed state
4242                 setFileName(old_name);
4243                 setUnnamed(old_unnamed);
4244                 return false;
4245         }
4246 }
4247
4248
4249 // FIXME We could do better here, but it is complicated. What would be
4250 // nice is to offer either (a) to save the child buffer to an appropriate
4251 // location, so that it would "move with the master", or else (b) to update
4252 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4253 // complicated, because the code for this lives in GuiView.
4254 void Buffer::checkChildBuffers()
4255 {
4256         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4257         Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4258         for (; it != en; ++it) {
4259                 DocIterator dit = it->second;
4260                 Buffer * cbuf = const_cast<Buffer *>(it->first);
4261                 if (!cbuf || !theBufferList().isLoaded(cbuf))
4262                         continue;
4263                 Inset * inset = dit.nextInset();
4264                 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4265                 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4266                 docstring const & incfile = inset_inc->getParam("filename");
4267                 string oldloc = cbuf->absFileName();
4268                 string newloc = makeAbsPath(to_utf8(incfile),
4269                                 onlyPath(absFileName())).absFileName();
4270                 if (oldloc == newloc)
4271                         continue;
4272                 // the location of the child file is incorrect.
4273                 Alert::warning(_("Included File Invalid"),
4274                                 bformat(_("Saving this document to a new location has made the file:\n"
4275                                 "  %1$s\n"
4276                                 "inaccessible. You will need to update the included filename."),
4277                                 from_utf8(oldloc)));
4278                 cbuf->setParent(0);
4279                 inset_inc->setChildBuffer(0);
4280         }
4281         // invalidate cache of children
4282         d->children_positions.clear();
4283         d->position_to_children.clear();
4284 }
4285
4286 } // namespace lyx