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