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