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