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