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