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