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