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