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