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