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