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