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