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