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