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