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