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