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