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