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