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