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