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