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