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