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