]> git.lyx.org Git - lyx.git/blob - src/Buffer.cpp
Small simplification and remove unneeded std::.
[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 = 378; // ps: rev insetinfo
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         // We don't need autosaves in the immediate future. (Asger)
979         resetAutosaveTimers();
980
981         FileName backupName;
982         bool madeBackup = false;
983
984         // make a backup if the file already exists
985         if (lyxrc.make_backup && fileName().exists()) {
986                 backupName = FileName(absFileName() + '~');
987                 if (!lyxrc.backupdir_path.empty()) {
988                         string const mangledName =
989                                 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
990                         backupName = FileName(addName(lyxrc.backupdir_path,
991                                                       mangledName));
992                 }
993                 if (fileName().copyTo(backupName)) {
994                         madeBackup = true;
995                 } else {
996                         Alert::error(_("Backup failure"),
997                                      bformat(_("Cannot create backup file %1$s.\n"
998                                                "Please check whether the directory exists and is writeable."),
999                                              from_utf8(backupName.absFilename())));
1000                         //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1001                 }
1002         }
1003
1004         // ask if the disk file has been externally modified (use checksum method)
1005         if (fileName().exists() && isExternallyModified(checksum_method)) {
1006                 docstring const file = makeDisplayPath(absFileName(), 20);
1007                 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
1008                                                              "you want to overwrite this file?"), file);
1009                 int const ret = Alert::prompt(_("Overwrite modified file?"),
1010                         text, 1, 1, _("&Overwrite"), _("&Cancel"));
1011                 if (ret == 1)
1012                         return false;
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         removeAutosaveFile();
1054
1055         saveCheckSum(d->filename);
1056         message(str + _(" done."));
1057
1058         return true;
1059 }
1060
1061
1062 docstring Buffer::emergencyWrite()
1063 {
1064         // No need to save if the buffer has not changed.
1065         if (isClean())
1066                 return docstring();
1067
1068         string const doc = isUnnamed() ? onlyFilename(absFileName()) : absFileName();
1069
1070         docstring user_message = bformat(
1071                 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1072
1073         // We try to save three places:
1074         // 1) Same place as document. Unless it is an unnamed doc.
1075         if (!isUnnamed()) {
1076                 string s = absFileName();
1077                 s += ".emergency";
1078                 LYXERR0("  " << s);
1079                 if (writeFile(FileName(s))) {
1080                         markClean();
1081                         user_message += bformat(_("  Saved to %1$s. Phew.\n"), from_utf8(s));
1082                         return user_message;
1083                 } else {
1084                         user_message += _("  Save failed! Trying again...\n");
1085                 }
1086         }
1087
1088         // 2) In HOME directory.
1089         string s = addName(package().home_dir().absFilename(), absFileName());
1090         s += ".emergency";
1091         lyxerr << ' ' << s << endl;
1092         if (writeFile(FileName(s))) {
1093                 markClean();
1094                 user_message += bformat(_("  Saved to %1$s. Phew.\n"), from_utf8(s));
1095                 return user_message;
1096         }
1097
1098         user_message += _("  Save failed! Trying yet again...\n");
1099
1100         // 3) In "/tmp" directory.
1101         // MakeAbsPath to prepend the current
1102         // drive letter on OS/2
1103         s = addName(package().temp_dir().absFilename(), absFileName());
1104         s += ".emergency";
1105         lyxerr << ' ' << s << endl;
1106         if (writeFile(FileName(s))) {
1107                 markClean();
1108                 user_message += bformat(_("  Saved to %1$s. Phew.\n"), from_utf8(s));
1109                 return user_message;
1110         }
1111
1112         user_message += _("  Save failed! Bummer. Document is lost.");
1113         // Don't try again.
1114         markClean();
1115         return user_message;
1116 }
1117
1118
1119 bool Buffer::write(ostream & ofs) const
1120 {
1121 #ifdef HAVE_LOCALE
1122         // Use the standard "C" locale for file output.
1123         ofs.imbue(locale::classic());
1124 #endif
1125
1126         // The top of the file should not be written by params().
1127
1128         // write out a comment in the top of the file
1129         ofs << "#LyX " << lyx_version
1130             << " created this file. For more info see http://www.lyx.org/\n"
1131             << "\\lyxformat " << LYX_FORMAT << "\n"
1132             << "\\begin_document\n";
1133
1134         /// For each author, set 'used' to true if there is a change
1135         /// by this author in the document; otherwise set it to 'false'.
1136         AuthorList::Authors::const_iterator a_it = params().authors().begin();
1137         AuthorList::Authors::const_iterator a_end = params().authors().end();
1138         for (; a_it != a_end; ++a_it)
1139                 a_it->setUsed(false);
1140
1141         ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1142         ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1143         for ( ; it != end; ++it)
1144                 it->checkAuthors(params().authors());
1145
1146         // now write out the buffer parameters.
1147         ofs << "\\begin_header\n";
1148         params().writeFile(ofs);
1149         ofs << "\\end_header\n";
1150
1151         // write the text
1152         ofs << "\n\\begin_body\n";
1153         text().write(ofs);
1154         ofs << "\n\\end_body\n";
1155
1156         // Write marker that shows file is complete
1157         ofs << "\\end_document" << endl;
1158
1159         // Shouldn't really be needed....
1160         //ofs.close();
1161
1162         // how to check if close went ok?
1163         // Following is an attempt... (BE 20001011)
1164
1165         // good() returns false if any error occured, including some
1166         //        formatting error.
1167         // bad()  returns true if something bad happened in the buffer,
1168         //        which should include file system full errors.
1169
1170         bool status = true;
1171         if (!ofs) {
1172                 status = false;
1173                 lyxerr << "File was not closed properly." << endl;
1174         }
1175
1176         return status;
1177 }
1178
1179
1180 bool Buffer::makeLaTeXFile(FileName const & fname,
1181                            string const & original_path,
1182                            OutputParams const & runparams_in,
1183                            bool output_preamble, bool output_body) const
1184 {
1185         OutputParams runparams = runparams_in;
1186         if (params().useXetex)
1187                 runparams.flavor = OutputParams::XETEX;
1188
1189         string const encoding = runparams.encoding->iconvName();
1190         LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1191
1192         ofdocstream ofs;
1193         try { ofs.reset(encoding); }
1194         catch (iconv_codecvt_facet_exception & e) {
1195                 lyxerr << "Caught iconv exception: " << e.what() << endl;
1196                 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1197                         "verify that the support software for your encoding (%1$s) is "
1198                         "properly installed"), from_ascii(encoding)));
1199                 return false;
1200         }
1201         if (!openFileWrite(ofs, fname))
1202                 return false;
1203
1204         //TexStream ts(ofs.rdbuf(), &texrow());
1205         ErrorList & errorList = d->errorLists["Export"];
1206         errorList.clear();
1207         bool failed_export = false;
1208         try {
1209                 d->texrow.reset();
1210                 writeLaTeXSource(ofs, original_path,
1211                       runparams, output_preamble, output_body);
1212         }
1213         catch (EncodingException & e) {
1214                 odocstringstream ods;
1215                 ods.put(e.failed_char);
1216                 ostringstream oss;
1217                 oss << "0x" << hex << e.failed_char << dec;
1218                 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1219                                           " (code point %2$s)"),
1220                                           ods.str(), from_utf8(oss.str()));
1221                 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1222                                 "representable in the chosen encoding.\n"
1223                                 "Changing the document encoding to utf8 could help."),
1224                                 e.par_id, e.pos, e.pos + 1));
1225                 failed_export = true;
1226         }
1227         catch (iconv_codecvt_facet_exception & e) {
1228                 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1229                         _(e.what()), -1, 0, 0));
1230                 failed_export = true;
1231         }
1232         catch (exception const & e) {
1233                 errorList.push_back(ErrorItem(_("conversion failed"),
1234                         _(e.what()), -1, 0, 0));
1235                 failed_export = true;
1236         }
1237         catch (...) {
1238                 lyxerr << "Caught some really weird exception..." << endl;
1239                 lyx_exit(1);
1240         }
1241
1242         ofs.close();
1243         if (ofs.fail()) {
1244                 failed_export = true;
1245                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1246         }
1247
1248         errors("Export");
1249         return !failed_export;
1250 }
1251
1252
1253 void Buffer::writeLaTeXSource(odocstream & os,
1254                            string const & original_path,
1255                            OutputParams const & runparams_in,
1256                            bool const output_preamble, bool const output_body) const
1257 {
1258         // The child documents, if any, shall be already loaded at this point.
1259
1260         OutputParams runparams = runparams_in;
1261
1262         // Classify the unicode characters appearing in math insets
1263         Encodings::initUnicodeMath(*this);
1264
1265         // validate the buffer.
1266         LYXERR(Debug::LATEX, "  Validating buffer...");
1267         LaTeXFeatures features(*this, params(), runparams);
1268         validate(features);
1269         LYXERR(Debug::LATEX, "  Buffer validation done.");
1270
1271         // The starting paragraph of the coming rows is the
1272         // first paragraph of the document. (Asger)
1273         if (output_preamble && runparams.nice) {
1274                 os << "%% LyX " << lyx_version << " created this file.  "
1275                         "For more info, see http://www.lyx.org/.\n"
1276                         "%% Do not edit unless you really know what "
1277                         "you are doing.\n";
1278                 d->texrow.newline();
1279                 d->texrow.newline();
1280         }
1281         LYXERR(Debug::INFO, "lyx document header finished");
1282
1283         // Don't move this behind the parent_buffer=0 code below,
1284         // because then the macros will not get the right "redefinition"
1285         // flag as they don't see the parent macros which are output before.
1286         updateMacros();
1287
1288         // fold macros if possible, still with parent buffer as the
1289         // macros will be put in the prefix anyway.
1290         updateMacroInstances();
1291
1292         // There are a few differences between nice LaTeX and usual files:
1293         // usual is \batchmode and has a
1294         // special input@path to allow the including of figures
1295         // with either \input or \includegraphics (what figinsets do).
1296         // input@path is set when the actual parameter
1297         // original_path is set. This is done for usual tex-file, but not
1298         // for nice-latex-file. (Matthias 250696)
1299         // Note that input@path is only needed for something the user does
1300         // in the preamble, included .tex files or ERT, files included by
1301         // LyX work without it.
1302         if (output_preamble) {
1303                 if (!runparams.nice) {
1304                         // code for usual, NOT nice-latex-file
1305                         os << "\\batchmode\n"; // changed
1306                         // from \nonstopmode
1307                         d->texrow.newline();
1308                 }
1309                 if (!original_path.empty()) {
1310                         // FIXME UNICODE
1311                         // We don't know the encoding of inputpath
1312                         docstring const inputpath = from_utf8(support::latex_path(original_path));
1313                         docstring uncodable_glyphs;
1314                         Encoding const * const enc = runparams.encoding;
1315                         if (enc) {
1316                                 for (size_t n = 0; n < inputpath.size(); ++n) {
1317                                         docstring const glyph =
1318                                                 docstring(1, inputpath[n]);
1319                                         if (enc->latexChar(inputpath[n], true) != glyph) {
1320                                                 LYXERR0("Uncodable character '"
1321                                                         << glyph
1322                                                         << "' in input path!");
1323                                                 uncodable_glyphs += glyph;
1324                                         }
1325                                 }
1326                         }
1327
1328                         // warn user if we found uncodable glyphs.
1329                         if (!uncodable_glyphs.empty()) {
1330                                 frontend::Alert::warning(_("Uncodable character in file path"),
1331                                                 support::bformat(_("The path of your document\n"
1332                                                   "(%1$s)\n"
1333                                                   "contains glyphs that are unknown in the\n"
1334                                                   "current document encoding (namely %2$s).\n"
1335                                                   "This will likely result in incomplete output.\n\n"
1336                                                   "Choose an appropriate document encoding (such as utf8)\n"
1337                                                   "or change the file path name."), inputpath, uncodable_glyphs));
1338                         } else {
1339                                 os << "\\makeatletter\n"
1340                                    << "\\def\\input@path{{"
1341                                    << inputpath << "/}}\n"
1342                                    << "\\makeatother\n";
1343                                 d->texrow.newline();
1344                                 d->texrow.newline();
1345                                 d->texrow.newline();
1346                         }
1347                 }
1348
1349                 // get parent macros (if this buffer has a parent) which will be
1350                 // written at the document begin further down.
1351                 MacroSet parentMacros;
1352                 listParentMacros(parentMacros, features);
1353
1354                 // Write the preamble
1355                 runparams.use_babel = params().writeLaTeX(os, features,
1356                                                           d->texrow,
1357                                                           d->filename.onlyPath());
1358
1359                 runparams.use_japanese = features.isRequired("japanese");
1360
1361                 if (!output_body)
1362                         return;
1363
1364                 // make the body.
1365                 os << "\\begin{document}\n";
1366                 d->texrow.newline();
1367
1368                 // output the parent macros
1369                 MacroSet::iterator it = parentMacros.begin();
1370                 MacroSet::iterator end = parentMacros.end();
1371                 for (; it != end; ++it) {
1372                         int num_lines = (*it)->write(os, true);
1373                         d->texrow.newlines(num_lines);
1374                 }
1375                 
1376         } // output_preamble
1377
1378         d->texrow.start(paragraphs().begin()->id(), 0);
1379
1380         LYXERR(Debug::INFO, "preamble finished, now the body.");
1381
1382         // if we are doing a real file with body, even if this is the
1383         // child of some other buffer, let's cut the link here.
1384         // This happens for example if only a child document is printed.
1385         Buffer const * save_parent = 0;
1386         if (output_preamble) {
1387                 save_parent = d->parent();
1388                 d->setParent(0);
1389         }
1390
1391         // the real stuff
1392         latexParagraphs(*this, text(), os, d->texrow, runparams);
1393
1394         // Restore the parenthood if needed
1395         if (output_preamble)
1396                 d->setParent(save_parent);
1397
1398         // add this just in case after all the paragraphs
1399         os << endl;
1400         d->texrow.newline();
1401
1402         if (output_preamble) {
1403                 os << "\\end{document}\n";
1404                 d->texrow.newline();
1405                 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1406         } else {
1407                 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1408         }
1409         runparams_in.encoding = runparams.encoding;
1410
1411         // Just to be sure. (Asger)
1412         d->texrow.newline();
1413
1414         LYXERR(Debug::INFO, "Finished making LaTeX file.");
1415         LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1416 }
1417
1418
1419 bool Buffer::isLatex() const
1420 {
1421         return params().documentClass().outputType() == LATEX;
1422 }
1423
1424
1425 bool Buffer::isLiterate() const
1426 {
1427         return params().documentClass().outputType() == LITERATE;
1428 }
1429
1430
1431 bool Buffer::isDocBook() const
1432 {
1433         return params().documentClass().outputType() == DOCBOOK;
1434 }
1435
1436
1437 void Buffer::makeDocBookFile(FileName const & fname,
1438                               OutputParams const & runparams,
1439                               bool const body_only) const
1440 {
1441         LYXERR(Debug::LATEX, "makeDocBookFile...");
1442
1443         ofdocstream ofs;
1444         if (!openFileWrite(ofs, fname))
1445                 return;
1446
1447         writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1448
1449         ofs.close();
1450         if (ofs.fail())
1451                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1452 }
1453
1454
1455 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1456                              OutputParams const & runparams,
1457                              bool const only_body) const
1458 {
1459         LaTeXFeatures features(*this, params(), runparams);
1460         validate(features);
1461
1462         d->texrow.reset();
1463
1464         DocumentClass const & tclass = params().documentClass();
1465         string const top_element = tclass.latexname();
1466
1467         if (!only_body) {
1468                 if (runparams.flavor == OutputParams::XML)
1469                         os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1470
1471                 // FIXME UNICODE
1472                 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1473
1474                 // FIXME UNICODE
1475                 if (! tclass.class_header().empty())
1476                         os << from_ascii(tclass.class_header());
1477                 else if (runparams.flavor == OutputParams::XML)
1478                         os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1479                             << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1480                 else
1481                         os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1482
1483                 docstring preamble = from_utf8(params().preamble);
1484                 if (runparams.flavor != OutputParams::XML ) {
1485                         preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1486                         preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1487                         preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1488                         preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1489                 }
1490
1491                 string const name = runparams.nice
1492                         ? changeExtension(absFileName(), ".sgml") : fname;
1493                 preamble += features.getIncludedFiles(name);
1494                 preamble += features.getLyXSGMLEntities();
1495
1496                 if (!preamble.empty()) {
1497                         os << "\n [ " << preamble << " ]";
1498                 }
1499                 os << ">\n\n";
1500         }
1501
1502         string top = top_element;
1503         top += " lang=\"";
1504         if (runparams.flavor == OutputParams::XML)
1505                 top += params().language->code();
1506         else
1507                 top += params().language->code().substr(0, 2);
1508         top += '"';
1509
1510         if (!params().options.empty()) {
1511                 top += ' ';
1512                 top += params().options;
1513         }
1514
1515         os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1516             << " file was created by LyX " << lyx_version
1517             << "\n  See http://www.lyx.org/ for more information -->\n";
1518
1519         params().documentClass().counters().reset();
1520
1521         updateMacros();
1522
1523         sgml::openTag(os, top);
1524         os << '\n';
1525         docbookParagraphs(text(), *this, os, runparams);
1526         sgml::closeTag(os, top_element);
1527 }
1528
1529
1530 void Buffer::makeLyXHTMLFile(FileName const & fname,
1531                               OutputParams const & runparams,
1532                               bool const body_only) const
1533 {
1534         LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1535
1536         ofdocstream ofs;
1537         if (!openFileWrite(ofs, fname))
1538                 return;
1539
1540         writeLyXHTMLSource(ofs, runparams, body_only);
1541
1542         ofs.close();
1543         if (ofs.fail())
1544                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1545 }
1546
1547
1548 void Buffer::writeLyXHTMLSource(odocstream & os,
1549                              OutputParams const & runparams,
1550                              bool const only_body) const
1551 {
1552         LaTeXFeatures features(*this, params(), runparams);
1553         validate(features);
1554         updateBuffer(UpdateMaster, OutputUpdate);
1555         checkBibInfoCache();
1556         d->bibinfo_.makeCitationLabels(*this);
1557         updateMacros();
1558         updateMacroInstances();
1559
1560         if (!only_body) {
1561                 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1562                 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";
1563                 // FIXME Language should be set properly.
1564                 os << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n";
1565                 os << "<head>\n";
1566                 // FIXME Presumably need to set this right
1567                 os << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1568                 os << "<title>" << features.htmlTitle() << "</title>\n";
1569
1570                 os << "\n<!-- Text Class Preamble -->\n"
1571                         << features.getTClassHTMLPreamble()
1572                         << "\n<!-- Premable Snippets -->\n"
1573                         << from_utf8(features.getPreambleSnippets());
1574
1575                 os << "\n<!-- Layout-provided Styles -->\n";
1576                 docstring const styleinfo = features.getTClassHTMLStyles();
1577                 if (!styleinfo.empty()) {
1578                         os << "<style type='text/css'>\n"
1579                                 << styleinfo
1580                                 << "</style>\n";
1581                 }
1582                 os << "</head>\n<body>\n";
1583         }
1584
1585         XHTMLStream xs(os);
1586         params().documentClass().counters().reset();
1587         xhtmlParagraphs(text(), *this, xs, runparams);
1588         if (!only_body)
1589                 os << "</body>\n</html>\n";
1590 }
1591
1592
1593 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1594 // Other flags: -wall -v0 -x
1595 int Buffer::runChktex()
1596 {
1597         setBusy(true);
1598
1599         // get LaTeX-Filename
1600         FileName const path(temppath());
1601         string const name = addName(path.absFilename(), latexName());
1602         string const org_path = filePath();
1603
1604         PathChanger p(path); // path to LaTeX file
1605         message(_("Running chktex..."));
1606
1607         // Generate the LaTeX file if neccessary
1608         OutputParams runparams(&params().encoding());
1609         runparams.flavor = OutputParams::LATEX;
1610         runparams.nice = false;
1611         runparams.linelen = lyxrc.plaintext_linelen;
1612         makeLaTeXFile(FileName(name), org_path, runparams);
1613
1614         TeXErrors terr;
1615         Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1616         int const res = chktex.run(terr); // run chktex
1617
1618         if (res == -1) {
1619                 Alert::error(_("chktex failure"),
1620                              _("Could not run chktex successfully."));
1621         } else if (res > 0) {
1622                 ErrorList & errlist = d->errorLists["ChkTeX"];
1623                 errlist.clear();
1624                 bufferErrors(terr, errlist);
1625         }
1626
1627         setBusy(false);
1628
1629         errors("ChkTeX");
1630
1631         return res;
1632 }
1633
1634
1635 void Buffer::validate(LaTeXFeatures & features) const
1636 {
1637         params().validate(features);
1638
1639         updateMacros();
1640
1641         for_each(paragraphs().begin(), paragraphs().end(),
1642                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1643
1644         if (lyxerr.debugging(Debug::LATEX)) {
1645                 features.showStruct();
1646         }
1647 }
1648
1649
1650 void Buffer::getLabelList(vector<docstring> & list) const
1651 {
1652         // If this is a child document, use the parent's list instead.
1653         Buffer const * const pbuf = d->parent();
1654         if (pbuf) {
1655                 pbuf->getLabelList(list);
1656                 return;
1657         }
1658
1659         list.clear();
1660         Toc & toc = d->toc_backend.toc("label");
1661         TocIterator toc_it = toc.begin();
1662         TocIterator end = toc.end();
1663         for (; toc_it != end; ++toc_it) {
1664                 if (toc_it->depth() == 0)
1665                         list.push_back(toc_it->str());
1666         }
1667 }
1668
1669
1670 void Buffer::updateBibfilesCache(UpdateScope scope) const
1671 {
1672         // If this is a child document, use the parent's cache instead.
1673         Buffer const * const pbuf = d->parent();
1674         if (pbuf && scope != UpdateChildOnly) {
1675                 pbuf->updateBibfilesCache();
1676                 return;
1677         }
1678
1679         d->bibfiles_cache_.clear();
1680         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1681                 if (it->lyxCode() == BIBTEX_CODE) {
1682                         InsetBibtex const & inset =
1683                                 static_cast<InsetBibtex const &>(*it);
1684                         support::FileNameList const bibfiles = inset.getBibFiles();
1685                         d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1686                                 bibfiles.begin(),
1687                                 bibfiles.end());
1688                 } else if (it->lyxCode() == INCLUDE_CODE) {
1689                         InsetInclude & inset =
1690                                 static_cast<InsetInclude &>(*it);
1691                         inset.updateBibfilesCache();
1692                         support::FileNameList const & bibfiles =
1693                                         inset.getBibfilesCache();
1694                         d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
1695                                 bibfiles.begin(),
1696                                 bibfiles.end());
1697                 }
1698         }
1699         // the bibinfo cache is now invalid
1700         d->bibinfo_cache_valid_ = false;
1701 }
1702
1703
1704 void Buffer::invalidateBibinfoCache()
1705 {
1706         d->bibinfo_cache_valid_ = false;
1707 }
1708
1709
1710 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1711 {
1712         // If this is a child document, use the parent's cache instead.
1713         Buffer const * const pbuf = d->parent();
1714         if (pbuf && scope != UpdateChildOnly)
1715                 return pbuf->getBibfilesCache();
1716
1717         // We update the cache when first used instead of at loading time.
1718         if (d->bibfiles_cache_.empty())
1719                 const_cast<Buffer *>(this)->updateBibfilesCache(scope);
1720
1721         return d->bibfiles_cache_;
1722 }
1723
1724
1725 BiblioInfo const & Buffer::masterBibInfo() const
1726 {
1727         // if this is a child document and the parent is already loaded
1728         // use the parent's list instead  [ale990412]
1729         Buffer const * const tmp = masterBuffer();
1730         LASSERT(tmp, /**/);
1731         if (tmp != this)
1732                 return tmp->masterBibInfo();
1733         return localBibInfo();
1734 }
1735
1736
1737 BiblioInfo const & Buffer::localBibInfo() const
1738 {
1739         return d->bibinfo_;
1740 }
1741
1742
1743 void Buffer::checkBibInfoCache() const 
1744 {
1745         support::FileNameList const & bibfilesCache = getBibfilesCache();
1746         // compare the cached timestamps with the actual ones.
1747         support::FileNameList::const_iterator ei = bibfilesCache.begin();
1748         support::FileNameList::const_iterator en = bibfilesCache.end();
1749         for (; ei != en; ++ ei) {
1750                 time_t lastw = ei->lastModified();
1751                 time_t prevw = d->bibfile_status_[*ei];
1752                 if (lastw != prevw) {
1753                         d->bibinfo_cache_valid_ = false;
1754                         d->bibfile_status_[*ei] = lastw;
1755                 }
1756         }
1757
1758         if (!d->bibinfo_cache_valid_) {
1759                 d->bibinfo_.clear();
1760                 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1761                         it->fillWithBibKeys(d->bibinfo_, it);
1762                 d->bibinfo_cache_valid_ = true;
1763         }       
1764 }
1765
1766
1767 bool Buffer::isDepClean(string const & name) const
1768 {
1769         DepClean::const_iterator const it = d->dep_clean.find(name);
1770         if (it == d->dep_clean.end())
1771                 return true;
1772         return it->second;
1773 }
1774
1775
1776 void Buffer::markDepClean(string const & name)
1777 {
1778         d->dep_clean[name] = true;
1779 }
1780
1781
1782 bool Buffer::isExportableFormat(string const & format) const
1783 {
1784                 typedef vector<Format const *> Formats;
1785                 Formats formats;
1786                 formats = exportableFormats(true);
1787                 Formats::const_iterator fit = formats.begin();
1788                 Formats::const_iterator end = formats.end();
1789                 for (; fit != end ; ++fit) {
1790                         if ((*fit)->name() == format)
1791                                 return true;
1792                 }
1793                 return false;
1794 }
1795
1796
1797 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1798 {
1799         if (isInternal()) {
1800                 // FIXME? if there is an Buffer LFUN that can be dispatched even
1801                 // if internal, put a switch '(cmd.action)' here.
1802                 return false;
1803         }
1804
1805         bool enable = true;
1806
1807         switch (cmd.action) {
1808
1809                 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1810                         flag.setOnOff(isReadonly());
1811                         break;
1812
1813                 // FIXME: There is need for a command-line import.
1814                 //case LFUN_BUFFER_IMPORT:
1815
1816                 case LFUN_BUFFER_AUTO_SAVE:
1817                         break;
1818
1819                 case LFUN_BUFFER_EXPORT_CUSTOM:
1820                         // FIXME: Nothing to check here?
1821                         break;
1822
1823                 case LFUN_BUFFER_EXPORT: {
1824                         docstring const arg = cmd.argument();
1825                         enable = arg == "custom" || isExportable(to_utf8(arg));
1826                         if (!enable)
1827                                 flag.message(bformat(
1828                                         _("Don't know how to export to format: %1$s"), arg));
1829                         break;
1830                 }
1831
1832                 case LFUN_BUFFER_CHKTEX:
1833                         enable = isLatex() && !lyxrc.chktex_command.empty();
1834                         break;
1835
1836                 case LFUN_BUILD_PROGRAM:
1837                         enable = isExportable("program");
1838                         break;
1839
1840                 case LFUN_BRANCH_ACTIVATE: 
1841                 case LFUN_BRANCH_DEACTIVATE: {
1842                         BranchList const & branchList = params().branchlist();
1843                         docstring const branchName = cmd.argument();
1844                         enable = !branchName.empty() && branchList.find(branchName);
1845                         break;
1846                 }
1847
1848                 case LFUN_BRANCH_ADD:
1849                 case LFUN_BRANCHES_RENAME:
1850                 case LFUN_BUFFER_PRINT:
1851                         // if no Buffer is present, then of course we won't be called!
1852                         break;
1853
1854                 case LFUN_BUFFER_LANGUAGE:
1855                         enable = !isReadonly();
1856                         break;
1857
1858                 default:
1859                         return false;
1860         }
1861         flag.setEnabled(enable);
1862         return true;
1863 }
1864
1865
1866 void Buffer::dispatch(string const & command, DispatchResult & result)
1867 {
1868         return dispatch(lyxaction.lookupFunc(command), result);
1869 }
1870
1871
1872 // NOTE We can end up here even if we have no GUI, because we are called
1873 // by LyX::exec to handled command-line requests. So we may need to check 
1874 // whether we have a GUI or not. The boolean use_gui holds this information.
1875 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1876 {
1877         if (isInternal()) {
1878                 // FIXME? if there is an Buffer LFUN that can be dispatched even
1879                 // if internal, put a switch '(cmd.action)' here.
1880                 dr.dispatched(false);
1881                 return;
1882         }
1883         string const argument = to_utf8(func.argument());
1884         // We'll set this back to false if need be.
1885         bool dispatched = true;
1886         undo().beginUndoGroup();
1887
1888         switch (func.action) {
1889         case LFUN_BUFFER_TOGGLE_READ_ONLY:
1890                 if (lyxvc().inUse())
1891                         lyxvc().toggleReadOnly();
1892                 else
1893                         setReadonly(!isReadonly());
1894                 break;
1895
1896         case LFUN_BUFFER_EXPORT: {
1897                 bool success = doExport(argument, false, false);
1898                 dr.setError(!success);
1899                 if (!success)
1900                         dr.setMessage(bformat(_("Error exporting to format: %1$s."), 
1901                                               func.argument()));
1902                 break;
1903         }
1904
1905         case LFUN_BUILD_PROGRAM:
1906                 doExport("program", true, false);
1907                 break;
1908
1909         case LFUN_BUFFER_CHKTEX:
1910                 runChktex();
1911                 break;
1912
1913         case LFUN_BUFFER_EXPORT_CUSTOM: {
1914                 string format_name;
1915                 string command = split(argument, format_name, ' ');
1916                 Format const * format = formats.getFormat(format_name);
1917                 if (!format) {
1918                         lyxerr << "Format \"" << format_name
1919                                 << "\" not recognized!"
1920                                 << endl;
1921                         break;
1922                 }
1923
1924                 // The name of the file created by the conversion process
1925                 string filename;
1926
1927                 // Output to filename
1928                 if (format->name() == "lyx") {
1929                         string const latexname = latexName(false);
1930                         filename = changeExtension(latexname,
1931                                 format->extension());
1932                         filename = addName(temppath(), filename);
1933
1934                         if (!writeFile(FileName(filename)))
1935                                 break;
1936
1937                 } else {
1938                         doExport(format_name, true, false, filename);
1939                 }
1940
1941                 // Substitute $$FName for filename
1942                 if (!contains(command, "$$FName"))
1943                         command = "( " + command + " ) < $$FName";
1944                 command = subst(command, "$$FName", filename);
1945
1946                 // Execute the command in the background
1947                 Systemcall call;
1948                 call.startscript(Systemcall::DontWait, command);
1949                 break;
1950         }
1951
1952         // FIXME: There is need for a command-line import.
1953         /*
1954         case LFUN_BUFFER_IMPORT:
1955                 doImport(argument);
1956                 break;
1957         */
1958
1959         case LFUN_BUFFER_AUTO_SAVE:
1960                 autoSave();
1961                 break;
1962
1963         case LFUN_BRANCH_ADD: {
1964                 docstring const branch_name = func.argument();
1965                 if (branch_name.empty()) {
1966                         dispatched = false;
1967                         break;
1968                 }
1969                 BranchList & branch_list = params().branchlist();
1970                 Branch * branch = branch_list.find(branch_name);
1971                 if (branch) {
1972                         LYXERR0("Branch " << branch_name << " already exists.");
1973                         dr.setError(true);
1974                         docstring const msg = 
1975                                 bformat(_("Branch \"%1$s\" already exists."), branch_name);
1976                         dr.setMessage(msg);
1977                 } else {
1978                         branch_list.add(branch_name);
1979                         branch = branch_list.find(branch_name);
1980                         string const x11hexname = X11hexname(branch->color());
1981                         docstring const str = branch_name + ' ' + from_ascii(x11hexname);
1982                         lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));        
1983                         dr.setError(false);
1984                         dr.update(Update::Force);
1985                 }
1986                 break;
1987         }
1988
1989         case LFUN_BRANCH_ACTIVATE:
1990         case LFUN_BRANCH_DEACTIVATE: {
1991                 BranchList & branchList = params().branchlist();
1992                 docstring const branchName = func.argument();
1993                 // the case without a branch name is handled elsewhere
1994                 if (branchName.empty()) {
1995                         dispatched = false;
1996                         break;
1997                 }
1998                 Branch * branch = branchList.find(branchName);
1999                 if (!branch) {
2000                         LYXERR0("Branch " << branchName << " does not exist.");
2001                         dr.setError(true);
2002                         docstring const msg = 
2003                                 bformat(_("Branch \"%1$s\" does not exist."), branchName);
2004                         dr.setMessage(msg);
2005                 } else {
2006                         branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
2007                         dr.setError(false);
2008                         dr.update(Update::Force);
2009                 }
2010                 break;
2011         }
2012
2013         case LFUN_BRANCHES_RENAME: {
2014                 if (func.argument().empty())
2015                         break;
2016
2017                 docstring const oldname = from_utf8(func.getArg(0));
2018                 docstring const newname = from_utf8(func.getArg(1));
2019                 InsetIterator it  = inset_iterator_begin(inset());
2020                 InsetIterator const end = inset_iterator_end(inset());
2021                 bool success = false;
2022                 for (; it != end; ++it) {
2023                         if (it->lyxCode() == BRANCH_CODE) {
2024                                 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2025                                 if (ins.branch() == oldname) {
2026                                         undo().recordUndo(it);
2027                                         ins.rename(newname);
2028                                         success = true;
2029                                         continue;
2030                                 }
2031                         }
2032                         if (it->lyxCode() == INCLUDE_CODE) {
2033                                 // get buffer of external file
2034                                 InsetInclude const & ins =
2035                                         static_cast<InsetInclude const &>(*it);
2036                                 Buffer * child = ins.getChildBuffer();
2037                                 if (!child)
2038                                         continue;
2039                                 child->dispatch(func, dr);
2040                         }
2041                 }
2042
2043                 if (success)
2044                         dr.update(Update::Force);
2045                 break;
2046         }
2047
2048         case LFUN_BUFFER_PRINT: {
2049                 // we'll assume there's a problem until we succeed
2050                 dr.setError(true); 
2051                 string target = func.getArg(0);
2052                 string target_name = func.getArg(1);
2053                 string command = func.getArg(2);
2054
2055                 if (target.empty()
2056                     || target_name.empty()
2057                     || command.empty()) {
2058                         LYXERR0("Unable to parse " << func.argument());
2059                         docstring const msg = 
2060                                 bformat(_("Unable to parse \"%1$s\""), func.argument());
2061                         dr.setMessage(msg);
2062                         break;
2063                 }
2064                 if (target != "printer" && target != "file") {
2065                         LYXERR0("Unrecognized target \"" << target << '"');
2066                         docstring const msg = 
2067                                 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2068                         dr.setMessage(msg);
2069                         break;
2070                 }
2071
2072                 bool const update_unincluded =
2073                                 params().maintain_unincluded_children
2074                                 && !params().getIncludedChildren().empty();
2075                 if (!doExport("dvi", true, update_unincluded)) {
2076                         showPrintError(absFileName());
2077                         dr.setMessage(_("Error exporting to DVI."));
2078                         break;
2079                 }
2080
2081                 // Push directory path.
2082                 string const path = temppath();
2083                 // Prevent the compiler from optimizing away p
2084                 FileName pp(path);
2085                 PathChanger p(pp);
2086
2087                 // there are three cases here:
2088                 // 1. we print to a file
2089                 // 2. we print directly to a printer
2090                 // 3. we print using a spool command (print to file first)
2091                 Systemcall one;
2092                 int res = 0;
2093                 string const dviname = changeExtension(latexName(true), "dvi");
2094
2095                 if (target == "printer") {
2096                         if (!lyxrc.print_spool_command.empty()) {
2097                                 // case 3: print using a spool
2098                                 string const psname = changeExtension(dviname,".ps");
2099                                 command += ' ' + lyxrc.print_to_file
2100                                         + quoteName(psname)
2101                                         + ' '
2102                                         + quoteName(dviname);
2103
2104                                 string command2 = lyxrc.print_spool_command + ' ';
2105                                 if (target_name != "default") {
2106                                         command2 += lyxrc.print_spool_printerprefix
2107                                                 + target_name
2108                                                 + ' ';
2109                                 }
2110                                 command2 += quoteName(psname);
2111                                 // First run dvips.
2112                                 // If successful, then spool command
2113                                 res = one.startscript(Systemcall::Wait, command);
2114
2115                                 if (res == 0) {
2116                                         // If there's no GUI, we have to wait on this command. Otherwise,
2117                                         // LyX deletes the temporary directory, and with it the spooled
2118                                         // file, before it can be printed!!
2119                                         Systemcall::Starttype stype = use_gui ?
2120                                                 Systemcall::DontWait : Systemcall::Wait;
2121                                         res = one.startscript(stype, command2);
2122                                 }
2123                         } else {
2124                                 // case 2: print directly to a printer
2125                                 if (target_name != "default")
2126                                         command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2127                                 // as above....
2128                                 Systemcall::Starttype stype = use_gui ?
2129                                         Systemcall::DontWait : Systemcall::Wait;
2130                                 res = one.startscript(stype, command + quoteName(dviname));
2131                         }
2132
2133                 } else {
2134                         // case 1: print to a file
2135                         FileName const filename(makeAbsPath(target_name, filePath()));
2136                         FileName const dvifile(makeAbsPath(dviname, path));
2137                         if (filename.exists()) {
2138                                 docstring text = bformat(
2139                                         _("The file %1$s already exists.\n\n"
2140                                           "Do you want to overwrite that file?"),
2141                                         makeDisplayPath(filename.absFilename()));
2142                                 if (Alert::prompt(_("Overwrite file?"),
2143                                                   text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2144                                         break;
2145                         }
2146                         command += ' ' + lyxrc.print_to_file
2147                                 + quoteName(filename.toFilesystemEncoding())
2148                                 + ' '
2149                                 + quoteName(dvifile.toFilesystemEncoding());
2150                         // as above....
2151                         Systemcall::Starttype stype = use_gui ?
2152                                 Systemcall::DontWait : Systemcall::Wait;
2153                         res = one.startscript(stype, command);
2154                 }
2155
2156                 if (res == 0) 
2157                         dr.setError(false);
2158                 else {
2159                         dr.setMessage(_("Error running external commands."));
2160                         showPrintError(absFileName());
2161                 }
2162                 break;
2163         }
2164
2165         case LFUN_BUFFER_LANGUAGE: {
2166                 Language const * oldL = params().language;
2167                 Language const * newL = languages.getLanguage(argument);
2168                 if (!newL || oldL == newL)
2169                         break;
2170                 if (oldL->rightToLeft() == newL->rightToLeft() && !isMultiLingual())
2171                         changeLanguage(oldL, newL);
2172                 break;
2173         }
2174
2175         default:
2176                 dispatched = false;
2177                 break;
2178         }
2179         dr.dispatched(dispatched);
2180         undo().endUndoGroup();
2181 }
2182
2183
2184 void Buffer::changeLanguage(Language const * from, Language const * to)
2185 {
2186         LASSERT(from, /**/);
2187         LASSERT(to, /**/);
2188
2189         for_each(par_iterator_begin(),
2190                  par_iterator_end(),
2191                  bind(&Paragraph::changeLanguage, _1, params(), from, to));
2192 }
2193
2194
2195 bool Buffer::isMultiLingual() const
2196 {
2197         ParConstIterator end = par_iterator_end();
2198         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2199                 if (it->isMultiLingual(params()))
2200                         return true;
2201
2202         return false;
2203 }
2204
2205
2206 std::set<Language const *> Buffer::getLanguages() const
2207 {
2208         std::set<Language const *> languages;
2209         getLanguages(languages);
2210         return languages;
2211 }
2212
2213
2214 void Buffer::getLanguages(std::set<Language const *> & languages) const
2215 {
2216         ParConstIterator end = par_iterator_end();
2217         // add the buffer language, even if it's not actively used
2218         languages.insert(language());
2219         // iterate over the paragraphs
2220         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2221                 it->getLanguages(languages);
2222         // also children
2223         std::vector<Buffer *> clist = getChildren();
2224         for (vector<Buffer *>::const_iterator cit = clist.begin();
2225              cit != clist.end(); ++cit)
2226                 (*cit)->getLanguages(languages);
2227 }
2228
2229
2230 DocIterator Buffer::getParFromID(int const id) const
2231 {
2232         Buffer * buf = const_cast<Buffer *>(this);
2233         if (id < 0) {
2234                 // John says this is called with id == -1 from undo
2235                 lyxerr << "getParFromID(), id: " << id << endl;
2236                 return doc_iterator_end(buf);
2237         }
2238
2239         for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2240                 if (it.paragraph().id() == id)
2241                         return it;
2242
2243         return doc_iterator_end(buf);
2244 }
2245
2246
2247 bool Buffer::hasParWithID(int const id) const
2248 {
2249         return !getParFromID(id).atEnd();
2250 }
2251
2252
2253 ParIterator Buffer::par_iterator_begin()
2254 {
2255         return ParIterator(doc_iterator_begin(this));
2256 }
2257
2258
2259 ParIterator Buffer::par_iterator_end()
2260 {
2261         return ParIterator(doc_iterator_end(this));
2262 }
2263
2264
2265 ParConstIterator Buffer::par_iterator_begin() const
2266 {
2267         return ParConstIterator(doc_iterator_begin(this));
2268 }
2269
2270
2271 ParConstIterator Buffer::par_iterator_end() const
2272 {
2273         return ParConstIterator(doc_iterator_end(this));
2274 }
2275
2276
2277 Language const * Buffer::language() const
2278 {
2279         return params().language;
2280 }
2281
2282
2283 docstring const Buffer::B_(string const & l10n) const
2284 {
2285         return params().B_(l10n);
2286 }
2287
2288
2289 bool Buffer::isClean() const
2290 {
2291         return d->lyx_clean;
2292 }
2293
2294
2295 bool Buffer::isExternallyModified(CheckMethod method) const
2296 {
2297         LASSERT(d->filename.exists(), /**/);
2298         // if method == timestamp, check timestamp before checksum
2299         return (method == checksum_method
2300                 || d->timestamp_ != d->filename.lastModified())
2301                 && d->checksum_ != d->filename.checksum();
2302 }
2303
2304
2305 void Buffer::saveCheckSum(FileName const & file) const
2306 {
2307         if (file.exists()) {
2308                 d->timestamp_ = file.lastModified();
2309                 d->checksum_ = file.checksum();
2310         } else {
2311                 // in the case of save to a new file.
2312                 d->timestamp_ = 0;
2313                 d->checksum_ = 0;
2314         }
2315 }
2316
2317
2318 void Buffer::markClean() const
2319 {
2320         if (!d->lyx_clean) {
2321                 d->lyx_clean = true;
2322                 updateTitles();
2323         }
2324         // if the .lyx file has been saved, we don't need an
2325         // autosave
2326         d->bak_clean = true;
2327 }
2328
2329
2330 void Buffer::setUnnamed(bool flag)
2331 {
2332         d->unnamed = flag;
2333 }
2334
2335
2336 bool Buffer::isUnnamed() const
2337 {
2338         return d->unnamed;
2339 }
2340
2341
2342 /// \note
2343 /// Don't check unnamed, here: isInternal() is used in
2344 /// newBuffer(), where the unnamed flag has not been set by anyone
2345 /// yet. Also, for an internal buffer, there should be no need for
2346 /// retrieving fileName() nor for checking if it is unnamed or not.
2347 bool Buffer::isInternal() const
2348 {
2349         return fileName().extension() == "internal";
2350 }
2351
2352
2353 void Buffer::markDirty()
2354 {
2355         if (d->lyx_clean) {
2356                 d->lyx_clean = false;
2357                 updateTitles();
2358         }
2359         d->bak_clean = false;
2360
2361         DepClean::iterator it = d->dep_clean.begin();
2362         DepClean::const_iterator const end = d->dep_clean.end();
2363
2364         for (; it != end; ++it)
2365                 it->second = false;
2366 }
2367
2368
2369 FileName Buffer::fileName() const
2370 {
2371         return d->filename;
2372 }
2373
2374
2375 string Buffer::absFileName() const
2376 {
2377         return d->filename.absFilename();
2378 }
2379
2380
2381 string Buffer::filePath() const
2382 {
2383         return d->filename.onlyPath().absFilename() + "/";
2384 }
2385
2386
2387 bool Buffer::isReadonly() const
2388 {
2389         return d->read_only;
2390 }
2391
2392
2393 void Buffer::setParent(Buffer const * buffer)
2394 {
2395         // Avoids recursive include.
2396         d->setParent(buffer == this ? 0 : buffer);
2397         updateMacros();
2398 }
2399
2400
2401 Buffer const * Buffer::parent() const
2402 {
2403         return d->parent();
2404 }
2405
2406
2407 void Buffer::Impl::collectRelatives(BufferSet & bufs) const
2408 {
2409         bufs.insert(owner_);
2410         if (parent())
2411                 parent()->d->collectRelatives(bufs);
2412
2413         // loop over children
2414         BufferPositionMap::const_iterator it = children_positions.begin();
2415         BufferPositionMap::const_iterator end = children_positions.end();
2416         for (; it != end; ++it)
2417                 bufs.insert(const_cast<Buffer *>(it->first));
2418 }
2419
2420
2421 std::vector<Buffer const *> Buffer::allRelatives() const
2422 {
2423         BufferSet bufs;
2424         d->collectRelatives(bufs);
2425         BufferSet::iterator it = bufs.begin();
2426         std::vector<Buffer const *> ret;
2427         for (; it != bufs.end(); ++it)
2428                 ret.push_back(*it);
2429         return ret;
2430 }
2431
2432
2433 Buffer const * Buffer::masterBuffer() const
2434 {
2435         Buffer const * const pbuf = d->parent();
2436         if (!pbuf)
2437                 return this;
2438
2439         return pbuf->masterBuffer();
2440 }
2441
2442
2443 bool Buffer::isChild(Buffer * child) const
2444 {
2445         return d->children_positions.find(child) != d->children_positions.end();
2446 }
2447
2448
2449 DocIterator Buffer::firstChildPosition(Buffer const * child)
2450 {
2451         Impl::BufferPositionMap::iterator it;
2452         it = d->children_positions.find(child);
2453         if (it == d->children_positions.end())
2454                 return DocIterator(this);
2455         return it->second;
2456 }
2457
2458
2459 void Buffer::getChildren(std::vector<Buffer *> & clist, bool grand_children) const
2460 {
2461         // loop over children
2462         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2463         Impl::BufferPositionMap::iterator end = d->children_positions.end();
2464         for (; it != end; ++it) {
2465                 Buffer * child = const_cast<Buffer *>(it->first);
2466                 clist.push_back(child);
2467                 if (grand_children) {
2468                         // there might be grandchildren
2469                         vector<Buffer *> glist = child->getChildren();
2470                         clist.insert(clist.end(), glist.begin(), glist.end());
2471                 }
2472         }
2473 }
2474
2475
2476 vector<Buffer *> Buffer::getChildren(bool grand_children) const
2477 {
2478         vector<Buffer *> v;
2479         getChildren(v, grand_children);
2480         return v;
2481 }
2482
2483
2484 template<typename M>
2485 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
2486 {
2487         if (m.empty())
2488                 return m.end();
2489
2490         typename M::const_iterator it = m.lower_bound(x);
2491         if (it == m.begin())
2492                 return m.end();
2493
2494         it--;
2495         return it;
2496 }
2497
2498
2499 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
2500                                          DocIterator const & pos) const
2501 {
2502         LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2503
2504         // if paragraphs have no macro context set, pos will be empty
2505         if (pos.empty())
2506                 return 0;
2507
2508         // we haven't found anything yet
2509         DocIterator bestPos = owner_->par_iterator_begin();
2510         MacroData const * bestData = 0;
2511
2512         // find macro definitions for name
2513         NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
2514         if (nameIt != macros.end()) {
2515                 // find last definition in front of pos or at pos itself
2516                 PositionScopeMacroMap::const_iterator it
2517                         = greatest_below(nameIt->second, pos);
2518                 if (it != nameIt->second.end()) {
2519                         while (true) {
2520                                 // scope ends behind pos?
2521                                 if (pos < it->second.first) {
2522                                         // Looks good, remember this. If there
2523                                         // is no external macro behind this,
2524                                         // we found the right one already.
2525                                         bestPos = it->first;
2526                                         bestData = &it->second.second;
2527                                         break;
2528                                 }
2529
2530                                 // try previous macro if there is one
2531                                 if (it == nameIt->second.begin())
2532                                         break;
2533                                 it--;
2534                         }
2535                 }
2536         }
2537
2538         // find macros in included files
2539         PositionScopeBufferMap::const_iterator it
2540                 = greatest_below(position_to_children, pos);
2541         if (it == position_to_children.end())
2542                 // no children before
2543                 return bestData;
2544
2545         while (true) {
2546                 // do we know something better (i.e. later) already?
2547                 if (it->first < bestPos )
2548                         break;
2549
2550                 // scope ends behind pos?
2551                 if (pos < it->second.first) {
2552                         // look for macro in external file
2553                         macro_lock = true;
2554                         MacroData const * data
2555                                 = it->second.second->getMacro(name, false);
2556                         macro_lock = false;
2557                         if (data) {
2558                                 bestPos = it->first;
2559                                 bestData = data;
2560                                 break;
2561                         }
2562                 }
2563
2564                 // try previous file if there is one
2565                 if (it == position_to_children.begin())
2566                         break;
2567                 --it;
2568         }
2569
2570         // return the best macro we have found
2571         return bestData;
2572 }
2573
2574
2575 MacroData const * Buffer::getMacro(docstring const & name,
2576         DocIterator const & pos, bool global) const
2577 {
2578         if (d->macro_lock)
2579                 return 0;
2580
2581         // query buffer macros
2582         MacroData const * data = d->getBufferMacro(name, pos);
2583         if (data != 0)
2584                 return data;
2585
2586         // If there is a master buffer, query that
2587         Buffer const * const pbuf = d->parent();
2588         if (pbuf) {
2589                 d->macro_lock = true;
2590                 MacroData const * macro = pbuf->getMacro(
2591                         name, *this, false);
2592                 d->macro_lock = false;
2593                 if (macro)
2594                         return macro;
2595         }
2596
2597         if (global) {
2598                 data = MacroTable::globalMacros().get(name);
2599                 if (data != 0)
2600                         return data;
2601         }
2602
2603         return 0;
2604 }
2605
2606
2607 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2608 {
2609         // set scope end behind the last paragraph
2610         DocIterator scope = par_iterator_begin();
2611         scope.pit() = scope.lastpit() + 1;
2612
2613         return getMacro(name, scope, global);
2614 }
2615
2616
2617 MacroData const * Buffer::getMacro(docstring const & name,
2618         Buffer const & child, bool global) const
2619 {
2620         // look where the child buffer is included first
2621         Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2622         if (it == d->children_positions.end())
2623                 return 0;
2624
2625         // check for macros at the inclusion position
2626         return getMacro(name, it->second, global);
2627 }
2628
2629
2630 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
2631 {
2632         pit_type const lastpit = it.lastpit();
2633
2634         // look for macros in each paragraph
2635         while (it.pit() <= lastpit) {
2636                 Paragraph & par = it.paragraph();
2637
2638                 // iterate over the insets of the current paragraph
2639                 InsetList const & insets = par.insetList();
2640                 InsetList::const_iterator iit = insets.begin();
2641                 InsetList::const_iterator end = insets.end();
2642                 for (; iit != end; ++iit) {
2643                         it.pos() = iit->pos;
2644
2645                         // is it a nested text inset?
2646                         if (iit->inset->asInsetText()) {
2647                                 // Inset needs its own scope?
2648                                 InsetText const * itext = iit->inset->asInsetText();
2649                                 bool newScope = itext->isMacroScope();
2650
2651                                 // scope which ends just behind the inset
2652                                 DocIterator insetScope = it;
2653                                 ++insetScope.pos();
2654
2655                                 // collect macros in inset
2656                                 it.push_back(CursorSlice(*iit->inset));
2657                                 updateMacros(it, newScope ? insetScope : scope);
2658                                 it.pop_back();
2659                                 continue;
2660                         }
2661
2662                         // is it an external file?
2663                         if (iit->inset->lyxCode() == INCLUDE_CODE) {
2664                                 // get buffer of external file
2665                                 InsetInclude const & inset =
2666                                         static_cast<InsetInclude const &>(*iit->inset);
2667                                 macro_lock = true;
2668                                 Buffer * child = inset.getChildBuffer();
2669                                 macro_lock = false;
2670                                 if (!child)
2671                                         continue;
2672
2673                                 // register its position, but only when it is
2674                                 // included first in the buffer
2675                                 if (children_positions.find(child) ==
2676                                         children_positions.end())
2677                                                 children_positions[child] = it;
2678
2679                                 // register child with its scope
2680                                 position_to_children[it] = Impl::ScopeBuffer(scope, child);
2681                                 continue;
2682                         }
2683
2684                         if (iit->inset->lyxCode() != MATHMACRO_CODE)
2685                                 continue;
2686
2687                         // get macro data
2688                         MathMacroTemplate & macroTemplate =
2689                                 static_cast<MathMacroTemplate &>(*iit->inset);
2690                         MacroContext mc(owner_, it);
2691                         macroTemplate.updateToContext(mc);
2692
2693                         // valid?
2694                         bool valid = macroTemplate.validMacro();
2695                         // FIXME: Should be fixNameAndCheckIfValid() in fact,
2696                         // then the BufferView's cursor will be invalid in
2697                         // some cases which leads to crashes.
2698                         if (!valid)
2699                                 continue;
2700
2701                         // register macro
2702                         // FIXME (Abdel), I don't understandt why we pass 'it' here
2703                         // instead of 'macroTemplate' defined above... is this correct?
2704                         macros[macroTemplate.name()][it] =
2705                                 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
2706                 }
2707
2708                 // next paragraph
2709                 it.pit()++;
2710                 it.pos() = 0;
2711         }
2712 }
2713
2714
2715 void Buffer::updateMacros() const
2716 {
2717         if (d->macro_lock)
2718                 return;
2719
2720         LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2721
2722         // start with empty table
2723         d->macros.clear();
2724         d->children_positions.clear();
2725         d->position_to_children.clear();
2726
2727         // Iterate over buffer, starting with first paragraph
2728         // The scope must be bigger than any lookup DocIterator
2729         // later. For the global lookup, lastpit+1 is used, hence
2730         // we use lastpit+2 here.
2731         DocIterator it = par_iterator_begin();
2732         DocIterator outerScope = it;
2733         outerScope.pit() = outerScope.lastpit() + 2;
2734         d->updateMacros(it, outerScope);
2735 }
2736
2737
2738 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2739 {
2740         InsetIterator it  = inset_iterator_begin(inset());
2741         InsetIterator const end = inset_iterator_end(inset());
2742         for (; it != end; ++it) {
2743                 if (it->lyxCode() == BRANCH_CODE) {
2744                         InsetBranch & br = static_cast<InsetBranch &>(*it);
2745                         docstring const name = br.branch();
2746                         if (!from_master && !params().branchlist().find(name))
2747                                 result.push_back(name);
2748                         else if (from_master && !masterBuffer()->params().branchlist().find(name))
2749                                 result.push_back(name);
2750                         continue;
2751                 }
2752                 if (it->lyxCode() == INCLUDE_CODE) {
2753                         // get buffer of external file
2754                         InsetInclude const & ins =
2755                                 static_cast<InsetInclude const &>(*it);
2756                         Buffer * child = ins.getChildBuffer();
2757                         if (!child)
2758                                 continue;
2759                         child->getUsedBranches(result, true);
2760                 }
2761         }
2762         // remove duplicates
2763         result.unique();
2764 }
2765
2766
2767 void Buffer::updateMacroInstances() const
2768 {
2769         LYXERR(Debug::MACROS, "updateMacroInstances for "
2770                 << d->filename.onlyFileName());
2771         DocIterator it = doc_iterator_begin(this);
2772         it.forwardInset();
2773         DocIterator const end = doc_iterator_end(this);
2774         for (; it != end; it.forwardInset()) {
2775                 // look for MathData cells in InsetMathNest insets
2776                 InsetMath * minset = it.nextInset()->asInsetMath();
2777                 if (!minset)
2778                         continue;
2779
2780                 // update macro in all cells of the InsetMathNest
2781                 DocIterator::idx_type n = minset->nargs();
2782                 MacroContext mc = MacroContext(this, it);
2783                 for (DocIterator::idx_type i = 0; i < n; ++i) {
2784                         MathData & data = minset->cell(i);
2785                         data.updateMacros(0, mc);
2786                 }
2787         }
2788 }
2789
2790
2791 void Buffer::listMacroNames(MacroNameSet & macros) const
2792 {
2793         if (d->macro_lock)
2794                 return;
2795
2796         d->macro_lock = true;
2797
2798         // loop over macro names
2799         Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2800         Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2801         for (; nameIt != nameEnd; ++nameIt)
2802                 macros.insert(nameIt->first);
2803
2804         // loop over children
2805         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2806         Impl::BufferPositionMap::iterator end = d->children_positions.end();
2807         for (; it != end; ++it)
2808                 it->first->listMacroNames(macros);
2809
2810         // call parent
2811         Buffer const * const pbuf = d->parent();
2812         if (pbuf)
2813                 pbuf->listMacroNames(macros);
2814
2815         d->macro_lock = false;
2816 }
2817
2818
2819 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2820 {
2821         Buffer const * const pbuf = d->parent();
2822         if (!pbuf)
2823                 return;
2824
2825         MacroNameSet names;
2826         pbuf->listMacroNames(names);
2827
2828         // resolve macros
2829         MacroNameSet::iterator it = names.begin();
2830         MacroNameSet::iterator end = names.end();
2831         for (; it != end; ++it) {
2832                 // defined?
2833                 MacroData const * data =
2834                 pbuf->getMacro(*it, *this, false);
2835                 if (data) {
2836                         macros.insert(data);
2837
2838                         // we cannot access the original MathMacroTemplate anymore
2839                         // here to calls validate method. So we do its work here manually.
2840                         // FIXME: somehow make the template accessible here.
2841                         if (data->optionals() > 0)
2842                                 features.require("xargs");
2843                 }
2844         }
2845 }
2846
2847
2848 Buffer::References & Buffer::references(docstring const & label)
2849 {
2850         if (d->parent())
2851                 return const_cast<Buffer *>(masterBuffer())->references(label);
2852
2853         RefCache::iterator it = d->ref_cache_.find(label);
2854         if (it != d->ref_cache_.end())
2855                 return it->second.second;
2856
2857         static InsetLabel const * dummy_il = 0;
2858         static References const dummy_refs;
2859         it = d->ref_cache_.insert(
2860                 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2861         return it->second.second;
2862 }
2863
2864
2865 Buffer::References const & Buffer::references(docstring const & label) const
2866 {
2867         return const_cast<Buffer *>(this)->references(label);
2868 }
2869
2870
2871 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2872 {
2873         masterBuffer()->d->ref_cache_[label].first = il;
2874 }
2875
2876
2877 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2878 {
2879         return masterBuffer()->d->ref_cache_[label].first;
2880 }
2881
2882
2883 void Buffer::clearReferenceCache() const
2884 {
2885         if (!d->parent())
2886                 d->ref_cache_.clear();
2887 }
2888
2889
2890 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2891         InsetCode code)
2892 {
2893         //FIXME: This does not work for child documents yet.
2894         LASSERT(code == CITE_CODE, /**/);
2895         // Check if the label 'from' appears more than once
2896         vector<docstring> labels;
2897         string paramName;
2898         checkBibInfoCache();
2899         BiblioInfo const & keys = masterBibInfo();
2900         BiblioInfo::const_iterator bit  = keys.begin();
2901         BiblioInfo::const_iterator bend = keys.end();
2902
2903         for (; bit != bend; ++bit)
2904                 // FIXME UNICODE
2905                 labels.push_back(bit->first);
2906         paramName = "key";
2907
2908         if (count(labels.begin(), labels.end(), from) > 1)
2909                 return;
2910
2911         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2912                 if (it->lyxCode() == code) {
2913                         InsetCommand & inset = static_cast<InsetCommand &>(*it);
2914                         docstring const oldValue = inset.getParam(paramName);
2915                         if (oldValue == from)
2916                                 inset.setParam(paramName, to);
2917                 }
2918         }
2919 }
2920
2921
2922 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2923         pit_type par_end, bool full_source) const
2924 {
2925         OutputParams runparams(&params().encoding());
2926         runparams.nice = true;
2927         runparams.flavor = params().useXetex ? 
2928                 OutputParams::XETEX : OutputParams::LATEX;
2929         runparams.linelen = lyxrc.plaintext_linelen;
2930         // No side effect of file copying and image conversion
2931         runparams.dryrun = true;
2932
2933         if (full_source) {
2934                 os << "% " << _("Preview source code") << "\n\n";
2935                 d->texrow.reset();
2936                 d->texrow.newline();
2937                 d->texrow.newline();
2938                 if (isDocBook())
2939                         writeDocBookSource(os, absFileName(), runparams, false);
2940                 else
2941                         // latex or literate
2942                         writeLaTeXSource(os, string(), runparams, true, true);
2943         } else {
2944                 runparams.par_begin = par_begin;
2945                 runparams.par_end = par_end;
2946                 if (par_begin + 1 == par_end) {
2947                         os << "% "
2948                            << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2949                            << "\n\n";
2950                 } else {
2951                         os << "% "
2952                            << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2953                                         convert<docstring>(par_begin),
2954                                         convert<docstring>(par_end - 1))
2955                            << "\n\n";
2956                 }
2957                 TexRow texrow;
2958                 texrow.reset();
2959                 texrow.newline();
2960                 texrow.newline();
2961                 // output paragraphs
2962                 if (isDocBook())
2963                         docbookParagraphs(text(), *this, os, runparams);
2964                 else 
2965                         // latex or literate
2966                         latexParagraphs(*this, text(), os, texrow, runparams);
2967         }
2968 }
2969
2970
2971 ErrorList & Buffer::errorList(string const & type) const
2972 {
2973         static ErrorList emptyErrorList;
2974         map<string, ErrorList>::iterator I = d->errorLists.find(type);
2975         if (I == d->errorLists.end())
2976                 return emptyErrorList;
2977
2978         return I->second;
2979 }
2980
2981
2982 void Buffer::updateTocItem(std::string const & type,
2983         DocIterator const & dit) const
2984 {
2985         if (d->gui_)
2986                 d->gui_->updateTocItem(type, dit);
2987 }
2988
2989
2990 void Buffer::structureChanged() const
2991 {
2992         if (d->gui_)
2993                 d->gui_->structureChanged();
2994 }
2995
2996
2997 void Buffer::errors(string const & err, bool from_master) const
2998 {
2999         if (d->gui_)
3000                 d->gui_->errors(err, from_master);
3001 }
3002
3003
3004 void Buffer::message(docstring const & msg) const
3005 {
3006         if (d->gui_)
3007                 d->gui_->message(msg);
3008 }
3009
3010
3011 void Buffer::setBusy(bool on) const
3012 {
3013         if (d->gui_)
3014                 d->gui_->setBusy(on);
3015 }
3016
3017
3018 void Buffer::updateTitles() const
3019 {
3020         if (d->wa_)
3021                 d->wa_->updateTitles();
3022 }
3023
3024
3025 void Buffer::resetAutosaveTimers() const
3026 {
3027         if (d->gui_)
3028                 d->gui_->resetAutosaveTimers();
3029 }
3030
3031
3032 bool Buffer::hasGuiDelegate() const
3033 {
3034         return d->gui_;
3035 }
3036
3037
3038 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3039 {
3040         d->gui_ = gui;
3041 }
3042
3043
3044
3045 namespace {
3046
3047 class AutoSaveBuffer : public ForkedProcess {
3048 public:
3049         ///
3050         AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3051                 : buffer_(buffer), fname_(fname) {}
3052         ///
3053         virtual boost::shared_ptr<ForkedProcess> clone() const
3054         {
3055                 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3056         }
3057         ///
3058         int start()
3059         {
3060                 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3061                                                  from_utf8(fname_.absFilename())));
3062                 return run(DontWait);
3063         }
3064 private:
3065         ///
3066         virtual int generateChild();
3067         ///
3068         Buffer const & buffer_;
3069         FileName fname_;
3070 };
3071
3072
3073 int AutoSaveBuffer::generateChild()
3074 {
3075 #if defined(__APPLE__)
3076         /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard) 
3077          *   We should use something else like threads.
3078          *
3079          * Since I do not know how to determine at run time what is the OS X
3080          * version, I just disable forking altogether for now (JMarc)
3081          */
3082         pid_t const pid = -1;
3083 #else
3084         // tmp_ret will be located (usually) in /tmp
3085         // will that be a problem?
3086         // Note that this calls ForkedCalls::fork(), so it's
3087         // ok cross-platform.
3088         pid_t const pid = fork();
3089         // If you want to debug the autosave
3090         // you should set pid to -1, and comment out the fork.
3091         if (pid != 0 && pid != -1)
3092                 return pid;
3093 #endif
3094
3095         // pid = -1 signifies that lyx was unable
3096         // to fork. But we will do the save
3097         // anyway.
3098         bool failed = false;
3099         FileName const tmp_ret = FileName::tempName("lyxauto");
3100         if (!tmp_ret.empty()) {
3101                 buffer_.writeFile(tmp_ret);
3102                 // assume successful write of tmp_ret
3103                 if (!tmp_ret.moveTo(fname_))
3104                         failed = true;
3105         } else
3106                 failed = true;
3107
3108         if (failed) {
3109                 // failed to write/rename tmp_ret so try writing direct
3110                 if (!buffer_.writeFile(fname_)) {
3111                         // It is dangerous to do this in the child,
3112                         // but safe in the parent, so...
3113                         if (pid == -1) // emit message signal.
3114                                 buffer_.message(_("Autosave failed!"));
3115                 }
3116         }
3117
3118         if (pid == 0) // we are the child so...
3119                 _exit(0);
3120
3121         return pid;
3122 }
3123
3124 } // namespace anon
3125
3126
3127 FileName Buffer::getAutosaveFilename() const
3128 {
3129         // if the document is unnamed try to save in the backup dir, else
3130         // in the default document path, and as a last try in the filePath, 
3131         // which will most often be the temporary directory
3132         string fpath;
3133         if (isUnnamed())
3134                 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3135                         : lyxrc.backupdir_path;
3136         if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3137                 fpath = filePath();
3138
3139         string const fname = "#" + d->filename.onlyFileName() + "#";
3140         return makeAbsPath(fname, fpath);
3141 }
3142
3143
3144 void Buffer::removeAutosaveFile() const
3145 {
3146         FileName const f = getAutosaveFilename();
3147         if (f.exists())
3148                 f.removeFile();
3149 }
3150
3151
3152 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3153 {
3154         FileName const newauto = getAutosaveFilename();
3155         oldauto.refresh();
3156         if (newauto != oldauto && oldauto.exists())
3157                 if (!oldauto.moveTo(newauto))
3158                         LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3159 }
3160
3161
3162 // Perfect target for a thread...
3163 void Buffer::autoSave() const
3164 {
3165         if (d->bak_clean || isReadonly()) {
3166                 // We don't save now, but we'll try again later
3167                 resetAutosaveTimers();
3168                 return;
3169         }
3170
3171         // emit message signal.
3172         message(_("Autosaving current document..."));
3173         AutoSaveBuffer autosave(*this, getAutosaveFilename());
3174         autosave.start();
3175
3176         d->bak_clean = true;
3177
3178         resetAutosaveTimers();
3179 }
3180
3181
3182 string Buffer::bufferFormat() const
3183 {
3184         string format = params().documentClass().outputFormat();
3185         if (format == "latex") {
3186                 if (params().useXetex)
3187                         return "xetex";
3188                 if (params().encoding().package() == Encoding::japanese)
3189                         return "platex";
3190         }
3191         return format;
3192 }
3193
3194
3195 string Buffer::getDefaultOutputFormat() const
3196 {
3197         if (!params().defaultOutputFormat.empty()
3198             && params().defaultOutputFormat != "default")
3199                 return params().defaultOutputFormat;
3200         typedef vector<Format const *> Formats;
3201         Formats formats = exportableFormats(true);
3202         if (isDocBook()
3203             || isLiterate()
3204             || params().useXetex
3205             || params().encoding().package() == Encoding::japanese) {
3206                 if (formats.empty())
3207                         return string();
3208                 // return the first we find
3209                 return formats.front()->name();
3210         }
3211         return lyxrc.default_view_format;
3212 }
3213
3214
3215
3216 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3217         bool includeall, string & result_file) const
3218 {
3219         string backend_format;
3220         OutputParams runparams(&params().encoding());
3221         runparams.flavor = OutputParams::LATEX;
3222         runparams.linelen = lyxrc.plaintext_linelen;
3223         runparams.includeall = includeall;
3224         vector<string> backs = backends();
3225         if (find(backs.begin(), backs.end(), format) == backs.end()) {
3226                 // Get shortest path to format
3227                 Graph::EdgePath path;
3228                 for (vector<string>::const_iterator it = backs.begin();
3229                      it != backs.end(); ++it) {
3230                         Graph::EdgePath p = theConverters().getPath(*it, format);
3231                         if (!p.empty() && (path.empty() || p.size() < path.size())) {
3232                                 backend_format = *it;
3233                                 path = p;
3234                         }
3235                 }
3236                 if (path.empty()) {
3237                         if (!put_in_tempdir) {
3238                                 // Only show this alert if this is an export to a non-temporary
3239                                 // file (not for previewing).
3240                                 Alert::error(_("Couldn't export file"), bformat(
3241                                         _("No information for exporting the format %1$s."),
3242                                         formats.prettyName(format)));
3243                         }
3244                         return false;
3245                 }
3246                 runparams.flavor = theConverters().getFlavor(path);
3247
3248         } else {
3249                 backend_format = format;
3250                 // FIXME: Don't hardcode format names here, but use a flag
3251                 if (backend_format == "pdflatex")
3252                         runparams.flavor = OutputParams::PDFLATEX;
3253         }
3254
3255         string filename = latexName(false);
3256         filename = addName(temppath(), filename);
3257         filename = changeExtension(filename,
3258                                    formats.extension(backend_format));
3259
3260         // fix macros
3261         updateMacroInstances();
3262
3263         // Plain text backend
3264         if (backend_format == "text") {
3265                 runparams.flavor = OutputParams::TEXT;
3266                 writePlaintextFile(*this, FileName(filename), runparams);
3267         }
3268         // HTML backend
3269         else if (backend_format == "xhtml") {
3270                 runparams.flavor = OutputParams::HTML;
3271                 makeLyXHTMLFile(FileName(filename), runparams);
3272         }       else if (backend_format == "lyx")
3273                 writeFile(FileName(filename));
3274         // Docbook backend
3275         else if (isDocBook()) {
3276                 runparams.nice = !put_in_tempdir;
3277                 makeDocBookFile(FileName(filename), runparams);
3278         }
3279         // LaTeX backend
3280         else if (backend_format == format) {
3281                 runparams.nice = true;
3282                 if (!makeLaTeXFile(FileName(filename), string(), runparams))
3283                         return false;
3284         } else if (!lyxrc.tex_allows_spaces
3285                    && contains(filePath(), ' ')) {
3286                 Alert::error(_("File name error"),
3287                            _("The directory path to the document cannot contain spaces."));
3288                 return false;
3289         } else {
3290                 runparams.nice = false;
3291                 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
3292                         return false;
3293         }
3294
3295         string const error_type = (format == "program")
3296                 ? "Build" : bufferFormat();
3297         ErrorList & error_list = d->errorLists[error_type];
3298         string const ext = formats.extension(format);
3299         FileName const tmp_result_file(changeExtension(filename, ext));
3300         bool const success = theConverters().convert(this, FileName(filename),
3301                 tmp_result_file, FileName(absFileName()), backend_format, format,
3302                 error_list);
3303         // Emit the signal to show the error list.
3304         if (format != backend_format) {
3305                 errors(error_type);
3306                 // also to the children, in case of master-buffer-view
3307                 std::vector<Buffer *> clist = getChildren();
3308                 for (vector<Buffer *>::const_iterator cit = clist.begin();
3309                      cit != clist.end(); ++cit)
3310                         (*cit)->errors(error_type, true);
3311         }
3312         if (!success)
3313                 return false;
3314
3315         if (d->cloned_buffer_) {
3316                 // Enable reverse dvi or pdf to work by copying back the texrow
3317                 // object to the cloned buffer.
3318                 // FIXME: There is a possibility of concurrent access to texrow
3319                 // here from the main GUI thread that should be securized.
3320                 d->cloned_buffer_->d->texrow = d->texrow;
3321         }
3322
3323         if (put_in_tempdir) {
3324                 result_file = tmp_result_file.absFilename();
3325                 return true;
3326         }
3327
3328         result_file = changeExtension(d->exportFileName().absFilename(), ext);
3329         // We need to copy referenced files (e. g. included graphics
3330         // if format == "dvi") to the result dir.
3331         vector<ExportedFile> const files =
3332                 runparams.exportdata->externalFiles(format);
3333         string const dest = onlyPath(result_file);
3334         CopyStatus status = SUCCESS;
3335         
3336         vector<ExportedFile>::const_iterator it = files.begin();
3337         vector<ExportedFile>::const_iterator const en = files.end();
3338         for (; it != en && status != CANCEL; ++it) {
3339                 string const fmt = formats.getFormatFromFile(it->sourceName);
3340                 status = copyFile(fmt, it->sourceName,
3341                         makeAbsPath(it->exportName, dest),
3342                         it->exportName, status == FORCE);
3343         }
3344
3345         if (status == CANCEL) {
3346                 message(_("Document export cancelled."));
3347         } else if (tmp_result_file.exists()) {
3348                 // Finally copy the main file
3349                 status = copyFile(format, tmp_result_file,
3350                         FileName(result_file), result_file,
3351                         status == FORCE);
3352                 message(bformat(_("Document exported as %1$s "
3353                         "to file `%2$s'"),
3354                         formats.prettyName(format),
3355                         makeDisplayPath(result_file)));
3356         } else {
3357                 // This must be a dummy converter like fax (bug 1888)
3358                 message(bformat(_("Document exported as %1$s"),
3359                         formats.prettyName(format)));
3360         }
3361
3362         return true;
3363 }
3364
3365
3366 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3367                       bool includeall) const
3368 {
3369         string result_file;
3370         // (1) export with all included children (omit \includeonly)
3371         if (includeall && !doExport(format, put_in_tempdir, true, result_file))
3372                 return false;
3373         // (2) export with included children only
3374         return doExport(format, put_in_tempdir, false, result_file);
3375 }
3376
3377
3378 bool Buffer::preview(string const & format, bool includeall) const
3379 {
3380         string result_file;
3381         // (1) export with all included children (omit \includeonly)
3382         if (includeall && !doExport(format, true, true))
3383                 return false;
3384         // (2) export with included children only
3385         if (!doExport(format, true, false, result_file))
3386                 return false;
3387         return formats.view(*this, FileName(result_file), format);
3388 }
3389
3390
3391 bool Buffer::isExportable(string const & format) const
3392 {
3393         vector<string> backs = backends();
3394         for (vector<string>::const_iterator it = backs.begin();
3395              it != backs.end(); ++it)
3396                 if (theConverters().isReachable(*it, format))
3397                         return true;
3398         return false;
3399 }
3400
3401
3402 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
3403 {
3404         vector<string> const backs = backends();
3405         vector<Format const *> result =
3406                 theConverters().getReachable(backs[0], only_viewable, true);
3407         for (vector<string>::const_iterator it = backs.begin() + 1;
3408              it != backs.end(); ++it) {
3409                 vector<Format const *>  r =
3410                         theConverters().getReachable(*it, only_viewable, false);
3411                 result.insert(result.end(), r.begin(), r.end());
3412         }
3413         return result;
3414 }
3415
3416
3417 vector<string> Buffer::backends() const
3418 {
3419         vector<string> v;
3420         v.push_back(bufferFormat());
3421         // FIXME: Don't hardcode format names here, but use a flag
3422         if (v.back() == "latex")
3423                 v.push_back("pdflatex");
3424         v.push_back("xhtml");
3425         v.push_back("text");
3426         v.push_back("lyx");
3427         return v;
3428 }
3429
3430
3431 bool Buffer::readFileHelper(FileName const & s)
3432 {
3433         // File information about normal file
3434         if (!s.exists()) {
3435                 docstring const file = makeDisplayPath(s.absFilename(), 50);
3436                 docstring text = bformat(_("The specified document\n%1$s"
3437                                                      "\ncould not be read."), file);
3438                 Alert::error(_("Could not read document"), text);
3439                 return false;
3440         }
3441
3442         // Check if emergency save file exists and is newer.
3443         FileName const e(s.absFilename() + ".emergency");
3444
3445         if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
3446                 docstring const file = makeDisplayPath(s.absFilename(), 20);
3447                 docstring const text =
3448                         bformat(_("An emergency save of the document "
3449                                   "%1$s exists.\n\n"
3450                                                "Recover emergency save?"), file);
3451                 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
3452                                       _("&Recover"),  _("&Load Original"),
3453                                       _("&Cancel")))
3454                 {
3455                 case 0: {
3456                         // the file is not saved if we load the emergency file.
3457                         markDirty();
3458                         docstring str;
3459                         bool res;
3460
3461                         if ((res = readFile(e)) == success)
3462                                 str = _("Document was successfully recovered.");
3463                         else
3464                                 str = _("Document was NOT successfully recovered.");
3465                         str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3466                                                 from_utf8(e.absFilename()));
3467
3468                         if (!Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3469                                         _("&Remove"), _("&Keep it"))) {
3470                                 e.removeFile();
3471                                 if (res == success)
3472                                         Alert::warning(_("Emergency file deleted"),
3473                                                 _("Do not forget to save your file now!"), true);
3474                                 }
3475                         return res;
3476                 }
3477                 case 1:
3478                         if (!Alert::prompt(_("Delete emergency file?"),
3479                                         _("Remove emergency file now?"), 1, 1,
3480                                         _("&Remove"), _("&Keep it")))
3481                                 e.removeFile();
3482                         break;
3483                 default:
3484                         return false;
3485                 }
3486         }
3487
3488         // Now check if autosave file is newer.
3489         FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
3490
3491         if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
3492                 docstring const file = makeDisplayPath(s.absFilename(), 20);
3493                 docstring const text =
3494                         bformat(_("The backup of the document "
3495                                   "%1$s is newer.\n\nLoad the "
3496                                                "backup instead?"), file);
3497                 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
3498                                       _("&Load backup"), _("Load &original"),
3499                                       _("&Cancel") ))
3500                 {
3501                 case 0:
3502                         // the file is not saved if we load the autosave file.
3503                         markDirty();
3504                         return readFile(a);
3505                 case 1:
3506                         // Here we delete the autosave
3507                         a.removeFile();
3508                         break;
3509                 default:
3510                         return false;
3511                 }
3512         }
3513         return readFile(s);
3514 }
3515
3516
3517 bool Buffer::loadLyXFile(FileName const & s)
3518 {
3519         // If the file is not readable, we try to
3520         // retrieve the file from version control.
3521         if (!s.isReadableFile()
3522                   && !LyXVC::file_not_found_hook(s))
3523                 return false;
3524         
3525         if (s.isReadableFile()){
3526                 // InsetInfo needs to know if file is under VCS
3527                 lyxvc().file_found_hook(s);
3528                 if (readFileHelper(s)) {
3529                         d->read_only = !s.isWritable();
3530                         return true;
3531                 }
3532         }
3533         return false;
3534 }
3535
3536
3537 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3538 {
3539         TeXErrors::Errors::const_iterator cit = terr.begin();
3540         TeXErrors::Errors::const_iterator end = terr.end();
3541
3542         for (; cit != end; ++cit) {
3543                 int id_start = -1;
3544                 int pos_start = -1;
3545                 int errorRow = cit->error_in_line;
3546                 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3547                                                        pos_start);
3548                 int id_end = -1;
3549                 int pos_end = -1;
3550                 do {
3551                         ++errorRow;
3552                         found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3553                 } while (found && id_start == id_end && pos_start == pos_end);
3554
3555                 errorList.push_back(ErrorItem(cit->error_desc,
3556                         cit->error_text, id_start, pos_start, pos_end));
3557         }
3558 }
3559
3560
3561 void Buffer::setBuffersForInsets() const
3562 {
3563         inset().setBuffer(const_cast<Buffer &>(*this)); 
3564 }
3565
3566
3567 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
3568 {
3569         // Use the master text class also for child documents
3570         Buffer const * const master = masterBuffer();
3571         DocumentClass const & textclass = master->params().documentClass();
3572         
3573         // do this only if we are the top-level Buffer
3574         if (scope != UpdateMaster || master == this)
3575                 checkBibInfoCache();
3576
3577         // keep the buffers to be children in this set. If the call from the
3578         // master comes back we can see which of them were actually seen (i.e.
3579         // via an InsetInclude). The remaining ones in the set need still be updated.
3580         static std::set<Buffer const *> bufToUpdate;
3581         if (scope == UpdateMaster) {
3582                 // If this is a child document start with the master
3583                 if (master != this) {
3584                         bufToUpdate.insert(this);
3585                         master->updateBuffer(UpdateMaster, utype);
3586                         // Do this here in case the master has no gui associated with it. Then, 
3587                         // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3588                         if (!master->d->gui_)
3589                                 structureChanged();
3590
3591                         // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3592                         if (bufToUpdate.find(this) == bufToUpdate.end())
3593                                 return;
3594                 }
3595
3596                 // start over the counters in the master
3597                 textclass.counters().reset();
3598         }
3599
3600         // update will be done below for this buffer
3601         bufToUpdate.erase(this);
3602
3603         // update all caches
3604         clearReferenceCache();
3605         updateMacros();
3606
3607         Buffer & cbuf = const_cast<Buffer &>(*this);
3608
3609         LASSERT(!text().paragraphs().empty(), /**/);
3610
3611         // do the real work
3612         ParIterator parit = cbuf.par_iterator_begin();
3613         updateBuffer(parit, utype);
3614
3615         if (master != this)
3616                 // TocBackend update will be done later.
3617                 return;
3618
3619         cbuf.tocBackend().update();
3620         if (scope == UpdateMaster)
3621                 cbuf.structureChanged();
3622 }
3623
3624
3625 static depth_type getDepth(DocIterator const & it)
3626 {
3627         depth_type depth = 0;
3628         for (size_t i = 0 ; i < it.depth() ; ++i)
3629                 if (!it[i].inset().inMathed())
3630                         depth += it[i].paragraph().getDepth() + 1;
3631         // remove 1 since the outer inset does not count
3632         return depth - 1;
3633 }
3634
3635 static depth_type getItemDepth(ParIterator const & it)
3636 {
3637         Paragraph const & par = *it;
3638         LabelType const labeltype = par.layout().labeltype;
3639
3640         if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3641                 return 0;
3642
3643         // this will hold the lowest depth encountered up to now.
3644         depth_type min_depth = getDepth(it);
3645         ParIterator prev_it = it;
3646         while (true) {
3647                 if (prev_it.pit())
3648                         --prev_it.top().pit();
3649                 else {
3650                         // start of nested inset: go to outer par
3651                         prev_it.pop_back();
3652                         if (prev_it.empty()) {
3653                                 // start of document: nothing to do
3654                                 return 0;
3655                         }
3656                 }
3657
3658                 // We search for the first paragraph with same label
3659                 // that is not more deeply nested.
3660                 Paragraph & prev_par = *prev_it;
3661                 depth_type const prev_depth = getDepth(prev_it);
3662                 if (labeltype == prev_par.layout().labeltype) {
3663                         if (prev_depth < min_depth)
3664                                 return prev_par.itemdepth + 1;
3665                         if (prev_depth == min_depth)
3666                                 return prev_par.itemdepth;
3667                 }
3668                 min_depth = min(min_depth, prev_depth);
3669                 // small optimization: if we are at depth 0, we won't
3670                 // find anything else
3671                 if (prev_depth == 0)
3672                         return 0;
3673         }
3674 }
3675
3676
3677 static bool needEnumCounterReset(ParIterator const & it)
3678 {
3679         Paragraph const & par = *it;
3680         LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3681         depth_type const cur_depth = par.getDepth();
3682         ParIterator prev_it = it;
3683         while (prev_it.pit()) {
3684                 --prev_it.top().pit();
3685                 Paragraph const & prev_par = *prev_it;
3686                 if (prev_par.getDepth() <= cur_depth)
3687                         return  prev_par.layout().labeltype != LABEL_ENUMERATE;
3688         }
3689         // start of nested inset: reset
3690         return true;
3691 }
3692
3693
3694 // set the label of a paragraph. This includes the counters.
3695 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
3696 {
3697         BufferParams const & bp = owner_->masterBuffer()->params();
3698         DocumentClass const & textclass = bp.documentClass();
3699         Paragraph & par = it.paragraph();
3700         Layout const & layout = par.layout();
3701         Counters & counters = textclass.counters();
3702
3703         if (par.params().startOfAppendix()) {
3704                 // FIXME: only the counter corresponding to toplevel
3705                 // sectioning should be reset
3706                 counters.reset();
3707                 counters.appendix(true);
3708         }
3709         par.params().appendix(counters.appendix());
3710
3711         // Compute the item depth of the paragraph
3712         par.itemdepth = getItemDepth(it);
3713
3714         if (layout.margintype == MARGIN_MANUAL
3715             || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3716                 if (par.params().labelWidthString().empty())
3717                         par.params().labelWidthString(par.expandLabel(layout, bp));
3718         } else {
3719                 par.params().labelWidthString(docstring());
3720         }
3721
3722         switch(layout.labeltype) {
3723         case LABEL_COUNTER:
3724                 if (layout.toclevel <= bp.secnumdepth
3725                     && (layout.latextype != LATEX_ENVIRONMENT
3726                         || it.text()->isFirstInSequence(it.pit()))) {
3727                         counters.step(layout.counter, utype);
3728                         par.params().labelString(
3729                                 par.expandLabel(layout, bp));
3730                 } else
3731                         par.params().labelString(docstring());
3732                 break;
3733
3734         case LABEL_ITEMIZE: {
3735                 // At some point of time we should do something more
3736                 // clever here, like:
3737                 //   par.params().labelString(
3738                 //    bp.user_defined_bullet(par.itemdepth).getText());
3739                 // for now, use a simple hardcoded label
3740                 docstring itemlabel;
3741                 switch (par.itemdepth) {
3742                 case 0:
3743                         itemlabel = char_type(0x2022);
3744                         break;
3745                 case 1:
3746                         itemlabel = char_type(0x2013);
3747                         break;
3748                 case 2:
3749                         itemlabel = char_type(0x2217);
3750                         break;
3751                 case 3:
3752                         itemlabel = char_type(0x2219); // or 0x00b7
3753                         break;
3754                 }
3755                 par.params().labelString(itemlabel);
3756                 break;
3757         }
3758
3759         case LABEL_ENUMERATE: {
3760                 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
3761
3762                 switch (par.itemdepth) {
3763                 case 2:
3764                         enumcounter += 'i';
3765                 case 1:
3766                         enumcounter += 'i';
3767                 case 0:
3768                         enumcounter += 'i';
3769                         break;
3770                 case 3:
3771                         enumcounter += "iv";
3772                         break;
3773                 default:
3774                         // not a valid enumdepth...
3775                         break;
3776                 }
3777
3778                 // Maybe we have to reset the enumeration counter.
3779                 if (needEnumCounterReset(it))
3780                         counters.reset(enumcounter);
3781                 counters.step(enumcounter, utype);
3782
3783                 string const & lang = par.getParLanguage(bp)->code();
3784                 par.params().labelString(counters.theCounter(enumcounter, lang));
3785
3786                 break;
3787         }
3788
3789         case LABEL_SENSITIVE: {
3790                 string const & type = counters.current_float();
3791                 docstring full_label;
3792                 if (type.empty())
3793                         full_label = owner_->B_("Senseless!!! ");
3794                 else {
3795                         docstring name = owner_->B_(textclass.floats().getType(type).name());
3796                         if (counters.hasCounter(from_utf8(type))) {
3797                                 string const & lang = par.getParLanguage(bp)->code();
3798                                 counters.step(from_utf8(type), utype);
3799                                 full_label = bformat(from_ascii("%1$s %2$s:"), 
3800                                                      name, 
3801                                                      counters.theCounter(from_utf8(type), lang));
3802                         } else
3803                                 full_label = bformat(from_ascii("%1$s #:"), name);      
3804                 }
3805                 par.params().labelString(full_label);   
3806                 break;
3807         }
3808
3809         case LABEL_NO_LABEL:
3810                 par.params().labelString(docstring());
3811                 break;
3812
3813         case LABEL_MANUAL:
3814         case LABEL_TOP_ENVIRONMENT:
3815         case LABEL_CENTERED_TOP_ENVIRONMENT:
3816         case LABEL_STATIC:      
3817         case LABEL_BIBLIO:
3818                 par.params().labelString(par.expandLabel(layout, bp));
3819                 break;
3820         }
3821 }
3822
3823
3824 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
3825 {
3826         LASSERT(parit.pit() == 0, /**/);
3827
3828         // set the position of the text in the buffer to be able
3829         // to resolve macros in it. This has nothing to do with
3830         // labels, but by putting it here we avoid implementing
3831         // a whole bunch of traversal routines just for this call.
3832         parit.text()->setMacrocontextPosition(parit);
3833
3834         depth_type maxdepth = 0;
3835         pit_type const lastpit = parit.lastpit();
3836         for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3837                 // reduce depth if necessary
3838                 parit->params().depth(min(parit->params().depth(), maxdepth));
3839                 maxdepth = parit->getMaxDepthAfter();
3840
3841                 if (utype == OutputUpdate) {
3842                         // track the active counters
3843                         // we have to do this for the master buffer, since the local
3844                         // buffer isn't tracking anything.
3845                         masterBuffer()->params().documentClass().counters().
3846                                         setActiveLayout(parit->layout());
3847                 }
3848                 
3849                 // set the counter for this paragraph
3850                 d->setLabel(parit, utype);
3851
3852                 // now the insets
3853                 InsetList::const_iterator iit = parit->insetList().begin();
3854                 InsetList::const_iterator end = parit->insetList().end();
3855                 for (; iit != end; ++iit) {
3856                         parit.pos() = iit->pos;
3857                         iit->inset->updateBuffer(parit, utype);
3858                 }
3859         }
3860 }
3861
3862
3863 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
3864         WordLangTuple & word_lang, docstring_list & suggestions) const
3865 {
3866         int progress = 0;
3867         WordLangTuple wl;
3868         suggestions.clear();
3869         word_lang = WordLangTuple();
3870         // OK, we start from here.
3871         DocIterator const end = doc_iterator_end(this);
3872         for (; from != end; from.forwardPos()) {
3873                 // We are only interested in text so remove the math CursorSlice.
3874                 while (from.inMathed()) {
3875                         from.pop_back();
3876                         from.pos()++;
3877                 }
3878                 // If from is at the end of the document (which is possible
3879                 // when leaving the mathed) LyX will crash later.
3880                 if (from == end)
3881                         break;
3882                 to = from;
3883                 if (from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions)) {
3884                         word_lang = wl;
3885                         break;
3886                 }
3887
3888                 // Do not increase progress when from == to, otherwise the word
3889                 // count will be wrong.
3890                 if (from != to) {
3891                         from = to;
3892                         ++progress;
3893                 }
3894         }
3895         return progress;
3896 }
3897
3898
3899 bool Buffer::reload()
3900 {
3901         setBusy(true);
3902         // e.g., read-only status could have changed due to version control
3903         d->filename.refresh();
3904         docstring const disp_fn = makeDisplayPath(d->filename.absFilename());
3905
3906         bool const success = loadLyXFile(d->filename);
3907         if (success) {
3908                 updateBuffer();
3909                 changed(true);
3910                 markClean();
3911                 message(bformat(_("Document %1$s reloaded."), disp_fn));
3912         } else {
3913                 message(bformat(_("Could not reload document %1$s."), disp_fn));
3914         }       
3915         setBusy(false);
3916         errors("Parse");
3917         return success;
3918 }
3919
3920
3921 // FIXME We could do better here, but it is complicated. What would be
3922 // nice is to offer either (a) to save the child buffer to an appropriate
3923 // location, so that it would "move with the master", or else (b) to update
3924 // the InsetInclude so that it pointed to the same file. But (a) is a bit
3925 // complicated, because the code for this lives in GuiView.
3926 void Buffer::checkChildBuffers()
3927 {
3928         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3929         Impl::BufferPositionMap::iterator const en = d->children_positions.end();
3930         for (; it != en; ++it) {
3931                 DocIterator dit = it->second;
3932                 Buffer * cbuf = const_cast<Buffer *>(it->first);
3933                 if (!cbuf || !theBufferList().isLoaded(cbuf))
3934                         continue;
3935                 Inset * inset = dit.nextInset();
3936                 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
3937                 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
3938                 docstring const & incfile = inset_inc->getParam("filename");
3939                 string oldloc = cbuf->absFileName();
3940                 string newloc = makeAbsPath(to_utf8(incfile),
3941                                 onlyPath(absFileName())).absFilename();
3942                 if (oldloc == newloc)
3943                         continue;
3944                 // the location of the child file is incorrect.
3945                 Alert::warning(_("Included File Invalid"),
3946                                 bformat(_("Saving this document to a new location has made the file:\n"
3947                                 "  %1$s\n"
3948                                 "inaccessible. You will need to update the included filename."),
3949                                 from_utf8(oldloc)));
3950                 cbuf->setParent(0);
3951                 inset_inc->setChildBuffer(0);
3952         }
3953         // invalidate cache of children
3954         d->children_positions.clear();
3955         d->position_to_children.clear();
3956 }
3957
3958 } // namespace lyx