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