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