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