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