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