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