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