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