]> git.lyx.org Git - lyx.git/blob - src/Buffer.cpp
Add an update parameter to BufferView::scrollToCursor and BufferView::scrollDocView...
[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 = 393; // rgh: rename OptArg to Argument in LyX format
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                 }
2041                 break;
2042         }
2043
2044         case LFUN_BRANCHES_RENAME: {
2045                 if (func.argument().empty())
2046                         break;
2047
2048                 docstring const oldname = from_utf8(func.getArg(0));
2049                 docstring const newname = from_utf8(func.getArg(1));
2050                 InsetIterator it  = inset_iterator_begin(inset());
2051                 InsetIterator const end = inset_iterator_end(inset());
2052                 bool success = false;
2053                 for (; it != end; ++it) {
2054                         if (it->lyxCode() == BRANCH_CODE) {
2055                                 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2056                                 if (ins.branch() == oldname) {
2057                                         undo().recordUndo(it);
2058                                         ins.rename(newname);
2059                                         success = true;
2060                                         continue;
2061                                 }
2062                         }
2063                         if (it->lyxCode() == INCLUDE_CODE) {
2064                                 // get buffer of external file
2065                                 InsetInclude const & ins =
2066                                         static_cast<InsetInclude const &>(*it);
2067                                 Buffer * child = ins.getChildBuffer();
2068                                 if (!child)
2069                                         continue;
2070                                 child->dispatch(func, dr);
2071                         }
2072                 }
2073
2074                 if (success)
2075                         dr.update(Update::Force);
2076                 break;
2077         }
2078
2079         case LFUN_BUFFER_PRINT: {
2080                 // we'll assume there's a problem until we succeed
2081                 dr.setError(true); 
2082                 string target = func.getArg(0);
2083                 string target_name = func.getArg(1);
2084                 string command = func.getArg(2);
2085
2086                 if (target.empty()
2087                     || target_name.empty()
2088                     || command.empty()) {
2089                         LYXERR0("Unable to parse " << func.argument());
2090                         docstring const msg = 
2091                                 bformat(_("Unable to parse \"%1$s\""), func.argument());
2092                         dr.setMessage(msg);
2093                         break;
2094                 }
2095                 if (target != "printer" && target != "file") {
2096                         LYXERR0("Unrecognized target \"" << target << '"');
2097                         docstring const msg = 
2098                                 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2099                         dr.setMessage(msg);
2100                         break;
2101                 }
2102
2103                 bool const update_unincluded =
2104                                 params().maintain_unincluded_children
2105                                 && !params().getIncludedChildren().empty();
2106                 if (!doExport("dvi", true, update_unincluded)) {
2107                         showPrintError(absFileName());
2108                         dr.setMessage(_("Error exporting to DVI."));
2109                         break;
2110                 }
2111
2112                 // Push directory path.
2113                 string const path = temppath();
2114                 // Prevent the compiler from optimizing away p
2115                 FileName pp(path);
2116                 PathChanger p(pp);
2117
2118                 // there are three cases here:
2119                 // 1. we print to a file
2120                 // 2. we print directly to a printer
2121                 // 3. we print using a spool command (print to file first)
2122                 Systemcall one;
2123                 int res = 0;
2124                 string const dviname = changeExtension(latexName(true), "dvi");
2125
2126                 if (target == "printer") {
2127                         if (!lyxrc.print_spool_command.empty()) {
2128                                 // case 3: print using a spool
2129                                 string const psname = changeExtension(dviname,".ps");
2130                                 command += ' ' + lyxrc.print_to_file
2131                                         + quoteName(psname)
2132                                         + ' '
2133                                         + quoteName(dviname);
2134
2135                                 string command2 = lyxrc.print_spool_command + ' ';
2136                                 if (target_name != "default") {
2137                                         command2 += lyxrc.print_spool_printerprefix
2138                                                 + target_name
2139                                                 + ' ';
2140                                 }
2141                                 command2 += quoteName(psname);
2142                                 // First run dvips.
2143                                 // If successful, then spool command
2144                                 res = one.startscript(Systemcall::Wait, command);
2145
2146                                 if (res == 0) {
2147                                         // If there's no GUI, we have to wait on this command. Otherwise,
2148                                         // LyX deletes the temporary directory, and with it the spooled
2149                                         // file, before it can be printed!!
2150                                         Systemcall::Starttype stype = use_gui ?
2151                                                 Systemcall::DontWait : Systemcall::Wait;
2152                                         res = one.startscript(stype, command2);
2153                                 }
2154                         } else {
2155                                 // case 2: print directly to a printer
2156                                 if (target_name != "default")
2157                                         command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2158                                 // as above....
2159                                 Systemcall::Starttype stype = use_gui ?
2160                                         Systemcall::DontWait : Systemcall::Wait;
2161                                 res = one.startscript(stype, command + quoteName(dviname));
2162                         }
2163
2164                 } else {
2165                         // case 1: print to a file
2166                         FileName const filename(makeAbsPath(target_name, filePath()));
2167                         FileName const dvifile(makeAbsPath(dviname, path));
2168                         if (filename.exists()) {
2169                                 docstring text = bformat(
2170                                         _("The file %1$s already exists.\n\n"
2171                                           "Do you want to overwrite that file?"),
2172                                         makeDisplayPath(filename.absFileName()));
2173                                 if (Alert::prompt(_("Overwrite file?"),
2174                                                   text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2175                                         break;
2176                         }
2177                         command += ' ' + lyxrc.print_to_file
2178                                 + quoteName(filename.toFilesystemEncoding())
2179                                 + ' '
2180                                 + quoteName(dvifile.toFilesystemEncoding());
2181                         // as above....
2182                         Systemcall::Starttype stype = use_gui ?
2183                                 Systemcall::DontWait : Systemcall::Wait;
2184                         res = one.startscript(stype, command);
2185                 }
2186
2187                 if (res == 0) 
2188                         dr.setError(false);
2189                 else {
2190                         dr.setMessage(_("Error running external commands."));
2191                         showPrintError(absFileName());
2192                 }
2193                 break;
2194         }
2195
2196         case LFUN_BUFFER_LANGUAGE: {
2197                 Language const * oldL = params().language;
2198                 Language const * newL = languages.getLanguage(argument);
2199                 if (!newL || oldL == newL)
2200                         break;
2201                 if (oldL->rightToLeft() == newL->rightToLeft() && !isMultiLingual())
2202                         changeLanguage(oldL, newL);
2203                 break;
2204         }
2205
2206         default:
2207                 dispatched = false;
2208                 break;
2209         }
2210         dr.dispatched(dispatched);
2211         undo().endUndoGroup();
2212 }
2213
2214
2215 void Buffer::changeLanguage(Language const * from, Language const * to)
2216 {
2217         LASSERT(from, /**/);
2218         LASSERT(to, /**/);
2219
2220         for_each(par_iterator_begin(),
2221                  par_iterator_end(),
2222                  bind(&Paragraph::changeLanguage, _1, params(), from, to));
2223 }
2224
2225
2226 bool Buffer::isMultiLingual() const
2227 {
2228         ParConstIterator end = par_iterator_end();
2229         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2230                 if (it->isMultiLingual(params()))
2231                         return true;
2232
2233         return false;
2234 }
2235
2236
2237 std::set<Language const *> Buffer::getLanguages() const
2238 {
2239         std::set<Language const *> languages;
2240         getLanguages(languages);
2241         return languages;
2242 }
2243
2244
2245 void Buffer::getLanguages(std::set<Language const *> & languages) const
2246 {
2247         ParConstIterator end = par_iterator_end();
2248         // add the buffer language, even if it's not actively used
2249         languages.insert(language());
2250         // iterate over the paragraphs
2251         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2252                 it->getLanguages(languages);
2253         // also children
2254         std::vector<Buffer *> clist = getChildren();
2255         for (vector<Buffer *>::const_iterator cit = clist.begin();
2256              cit != clist.end(); ++cit)
2257                 (*cit)->getLanguages(languages);
2258 }
2259
2260
2261 DocIterator Buffer::getParFromID(int const id) const
2262 {
2263         Buffer * buf = const_cast<Buffer *>(this);
2264         if (id < 0) {
2265                 // John says this is called with id == -1 from undo
2266                 lyxerr << "getParFromID(), id: " << id << endl;
2267                 return doc_iterator_end(buf);
2268         }
2269
2270         for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2271                 if (it.paragraph().id() == id)
2272                         return it;
2273
2274         return doc_iterator_end(buf);
2275 }
2276
2277
2278 bool Buffer::hasParWithID(int const id) const
2279 {
2280         return !getParFromID(id).atEnd();
2281 }
2282
2283
2284 ParIterator Buffer::par_iterator_begin()
2285 {
2286         return ParIterator(doc_iterator_begin(this));
2287 }
2288
2289
2290 ParIterator Buffer::par_iterator_end()
2291 {
2292         return ParIterator(doc_iterator_end(this));
2293 }
2294
2295
2296 ParConstIterator Buffer::par_iterator_begin() const
2297 {
2298         return ParConstIterator(doc_iterator_begin(this));
2299 }
2300
2301
2302 ParConstIterator Buffer::par_iterator_end() const
2303 {
2304         return ParConstIterator(doc_iterator_end(this));
2305 }
2306
2307
2308 Language const * Buffer::language() const
2309 {
2310         return params().language;
2311 }
2312
2313
2314 docstring const Buffer::B_(string const & l10n) const
2315 {
2316         return params().B_(l10n);
2317 }
2318
2319
2320 bool Buffer::isClean() const
2321 {
2322         return d->lyx_clean;
2323 }
2324
2325
2326 bool Buffer::isExternallyModified(CheckMethod method) const
2327 {
2328         LASSERT(d->filename.exists(), /**/);
2329         // if method == timestamp, check timestamp before checksum
2330         return (method == checksum_method
2331                 || d->timestamp_ != d->filename.lastModified())
2332                 && d->checksum_ != d->filename.checksum();
2333 }
2334
2335
2336 void Buffer::saveCheckSum(FileName const & file) const
2337 {
2338         if (file.exists()) {
2339                 d->timestamp_ = file.lastModified();
2340                 d->checksum_ = file.checksum();
2341         } else {
2342                 // in the case of save to a new file.
2343                 d->timestamp_ = 0;
2344                 d->checksum_ = 0;
2345         }
2346 }
2347
2348
2349 void Buffer::markClean() const
2350 {
2351         if (!d->lyx_clean) {
2352                 d->lyx_clean = true;
2353                 updateTitles();
2354         }
2355         // if the .lyx file has been saved, we don't need an
2356         // autosave
2357         d->bak_clean = true;
2358 }
2359
2360
2361 void Buffer::setUnnamed(bool flag)
2362 {
2363         d->unnamed = flag;
2364 }
2365
2366
2367 bool Buffer::isUnnamed() const
2368 {
2369         return d->unnamed;
2370 }
2371
2372
2373 /// \note
2374 /// Don't check unnamed, here: isInternal() is used in
2375 /// newBuffer(), where the unnamed flag has not been set by anyone
2376 /// yet. Also, for an internal buffer, there should be no need for
2377 /// retrieving fileName() nor for checking if it is unnamed or not.
2378 bool Buffer::isInternal() const
2379 {
2380         return fileName().extension() == "internal";
2381 }
2382
2383
2384 void Buffer::markDirty()
2385 {
2386         if (d->lyx_clean) {
2387                 d->lyx_clean = false;
2388                 updateTitles();
2389         }
2390         d->bak_clean = false;
2391
2392         DepClean::iterator it = d->dep_clean.begin();
2393         DepClean::const_iterator const end = d->dep_clean.end();
2394
2395         for (; it != end; ++it)
2396                 it->second = false;
2397 }
2398
2399
2400 FileName Buffer::fileName() const
2401 {
2402         return d->filename;
2403 }
2404
2405
2406 string Buffer::absFileName() const
2407 {
2408         return d->filename.absFileName();
2409 }
2410
2411
2412 string Buffer::filePath() const
2413 {
2414         return d->filename.onlyPath().absFileName() + "/";
2415 }
2416
2417
2418 bool Buffer::isReadonly() const
2419 {
2420         return d->read_only;
2421 }
2422
2423
2424 void Buffer::setParent(Buffer const * buffer)
2425 {
2426         // Avoids recursive include.
2427         d->setParent(buffer == this ? 0 : buffer);
2428         updateMacros();
2429 }
2430
2431
2432 Buffer const * Buffer::parent() const
2433 {
2434         return d->parent();
2435 }
2436
2437
2438 void Buffer::Impl::collectRelatives(BufferSet & bufs) const
2439 {
2440         bufs.insert(owner_);
2441         if (parent())
2442                 parent()->d->collectRelatives(bufs);
2443
2444         // loop over children
2445         BufferPositionMap::const_iterator it = children_positions.begin();
2446         BufferPositionMap::const_iterator end = children_positions.end();
2447         for (; it != end; ++it)
2448                 bufs.insert(const_cast<Buffer *>(it->first));
2449 }
2450
2451
2452 std::vector<Buffer const *> Buffer::allRelatives() const
2453 {
2454         BufferSet bufs;
2455         d->collectRelatives(bufs);
2456         BufferSet::iterator it = bufs.begin();
2457         std::vector<Buffer const *> ret;
2458         for (; it != bufs.end(); ++it)
2459                 ret.push_back(*it);
2460         return ret;
2461 }
2462
2463
2464 Buffer const * Buffer::masterBuffer() const
2465 {
2466         Buffer const * const pbuf = d->parent();
2467         if (!pbuf)
2468                 return this;
2469
2470         return pbuf->masterBuffer();
2471 }
2472
2473
2474 bool Buffer::isChild(Buffer * child) const
2475 {
2476         return d->children_positions.find(child) != d->children_positions.end();
2477 }
2478
2479
2480 DocIterator Buffer::firstChildPosition(Buffer const * child)
2481 {
2482         Impl::BufferPositionMap::iterator it;
2483         it = d->children_positions.find(child);
2484         if (it == d->children_positions.end())
2485                 return DocIterator(this);
2486         return it->second;
2487 }
2488
2489
2490 void Buffer::getChildren(std::vector<Buffer *> & clist, bool grand_children) const
2491 {
2492         // loop over children
2493         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2494         Impl::BufferPositionMap::iterator end = d->children_positions.end();
2495         for (; it != end; ++it) {
2496                 Buffer * child = const_cast<Buffer *>(it->first);
2497                 clist.push_back(child);
2498                 if (grand_children) {
2499                         // there might be grandchildren
2500                         vector<Buffer *> glist = child->getChildren();
2501                         clist.insert(clist.end(), glist.begin(), glist.end());
2502                 }
2503         }
2504 }
2505
2506
2507 vector<Buffer *> Buffer::getChildren(bool grand_children) const
2508 {
2509         vector<Buffer *> v;
2510         getChildren(v, grand_children);
2511         return v;
2512 }
2513
2514
2515 template<typename M>
2516 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
2517 {
2518         if (m.empty())
2519                 return m.end();
2520
2521         typename M::const_iterator it = m.lower_bound(x);
2522         if (it == m.begin())
2523                 return m.end();
2524
2525         it--;
2526         return it;
2527 }
2528
2529
2530 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
2531                                          DocIterator const & pos) const
2532 {
2533         LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2534
2535         // if paragraphs have no macro context set, pos will be empty
2536         if (pos.empty())
2537                 return 0;
2538
2539         // we haven't found anything yet
2540         DocIterator bestPos = owner_->par_iterator_begin();
2541         MacroData const * bestData = 0;
2542
2543         // find macro definitions for name
2544         NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
2545         if (nameIt != macros.end()) {
2546                 // find last definition in front of pos or at pos itself
2547                 PositionScopeMacroMap::const_iterator it
2548                         = greatest_below(nameIt->second, pos);
2549                 if (it != nameIt->second.end()) {
2550                         while (true) {
2551                                 // scope ends behind pos?
2552                                 if (pos < it->second.first) {
2553                                         // Looks good, remember this. If there
2554                                         // is no external macro behind this,
2555                                         // we found the right one already.
2556                                         bestPos = it->first;
2557                                         bestData = &it->second.second;
2558                                         break;
2559                                 }
2560
2561                                 // try previous macro if there is one
2562                                 if (it == nameIt->second.begin())
2563                                         break;
2564                                 it--;
2565                         }
2566                 }
2567         }
2568
2569         // find macros in included files
2570         PositionScopeBufferMap::const_iterator it
2571                 = greatest_below(position_to_children, pos);
2572         if (it == position_to_children.end())
2573                 // no children before
2574                 return bestData;
2575
2576         while (true) {
2577                 // do we know something better (i.e. later) already?
2578                 if (it->first < bestPos )
2579                         break;
2580
2581                 // scope ends behind pos?
2582                 if (pos < it->second.first) {
2583                         // look for macro in external file
2584                         macro_lock = true;
2585                         MacroData const * data
2586                                 = it->second.second->getMacro(name, false);
2587                         macro_lock = false;
2588                         if (data) {
2589                                 bestPos = it->first;
2590                                 bestData = data;
2591                                 break;
2592                         }
2593                 }
2594
2595                 // try previous file if there is one
2596                 if (it == position_to_children.begin())
2597                         break;
2598                 --it;
2599         }
2600
2601         // return the best macro we have found
2602         return bestData;
2603 }
2604
2605
2606 MacroData const * Buffer::getMacro(docstring const & name,
2607         DocIterator const & pos, bool global) const
2608 {
2609         if (d->macro_lock)
2610                 return 0;
2611
2612         // query buffer macros
2613         MacroData const * data = d->getBufferMacro(name, pos);
2614         if (data != 0)
2615                 return data;
2616
2617         // If there is a master buffer, query that
2618         Buffer const * const pbuf = d->parent();
2619         if (pbuf) {
2620                 d->macro_lock = true;
2621                 MacroData const * macro = pbuf->getMacro(
2622                         name, *this, false);
2623                 d->macro_lock = false;
2624                 if (macro)
2625                         return macro;
2626         }
2627
2628         if (global) {
2629                 data = MacroTable::globalMacros().get(name);
2630                 if (data != 0)
2631                         return data;
2632         }
2633
2634         return 0;
2635 }
2636
2637
2638 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2639 {
2640         // set scope end behind the last paragraph
2641         DocIterator scope = par_iterator_begin();
2642         scope.pit() = scope.lastpit() + 1;
2643
2644         return getMacro(name, scope, global);
2645 }
2646
2647
2648 MacroData const * Buffer::getMacro(docstring const & name,
2649         Buffer const & child, bool global) const
2650 {
2651         // look where the child buffer is included first
2652         Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2653         if (it == d->children_positions.end())
2654                 return 0;
2655
2656         // check for macros at the inclusion position
2657         return getMacro(name, it->second, global);
2658 }
2659
2660
2661 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
2662 {
2663         pit_type const lastpit = it.lastpit();
2664
2665         // look for macros in each paragraph
2666         while (it.pit() <= lastpit) {
2667                 Paragraph & par = it.paragraph();
2668
2669                 // iterate over the insets of the current paragraph
2670                 InsetList const & insets = par.insetList();
2671                 InsetList::const_iterator iit = insets.begin();
2672                 InsetList::const_iterator end = insets.end();
2673                 for (; iit != end; ++iit) {
2674                         it.pos() = iit->pos;
2675
2676                         // is it a nested text inset?
2677                         if (iit->inset->asInsetText()) {
2678                                 // Inset needs its own scope?
2679                                 InsetText const * itext = iit->inset->asInsetText();
2680                                 bool newScope = itext->isMacroScope();
2681
2682                                 // scope which ends just behind the inset
2683                                 DocIterator insetScope = it;
2684                                 ++insetScope.pos();
2685
2686                                 // collect macros in inset
2687                                 it.push_back(CursorSlice(*iit->inset));
2688                                 updateMacros(it, newScope ? insetScope : scope);
2689                                 it.pop_back();
2690                                 continue;
2691                         }
2692
2693                         // is it an external file?
2694                         if (iit->inset->lyxCode() == INCLUDE_CODE) {
2695                                 // get buffer of external file
2696                                 InsetInclude const & inset =
2697                                         static_cast<InsetInclude const &>(*iit->inset);
2698                                 macro_lock = true;
2699                                 Buffer * child = inset.getChildBuffer();
2700                                 macro_lock = false;
2701                                 if (!child)
2702                                         continue;
2703
2704                                 // register its position, but only when it is
2705                                 // included first in the buffer
2706                                 if (children_positions.find(child) ==
2707                                         children_positions.end())
2708                                                 children_positions[child] = it;
2709
2710                                 // register child with its scope
2711                                 position_to_children[it] = Impl::ScopeBuffer(scope, child);
2712                                 continue;
2713                         }
2714
2715                         if (iit->inset->lyxCode() != MATHMACRO_CODE)
2716                                 continue;
2717
2718                         // get macro data
2719                         MathMacroTemplate & macroTemplate =
2720                                 static_cast<MathMacroTemplate &>(*iit->inset);
2721                         MacroContext mc(owner_, it);
2722                         macroTemplate.updateToContext(mc);
2723
2724                         // valid?
2725                         bool valid = macroTemplate.validMacro();
2726                         // FIXME: Should be fixNameAndCheckIfValid() in fact,
2727                         // then the BufferView's cursor will be invalid in
2728                         // some cases which leads to crashes.
2729                         if (!valid)
2730                                 continue;
2731
2732                         // register macro
2733                         // FIXME (Abdel), I don't understandt why we pass 'it' here
2734                         // instead of 'macroTemplate' defined above... is this correct?
2735                         macros[macroTemplate.name()][it] =
2736                                 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
2737                 }
2738
2739                 // next paragraph
2740                 it.pit()++;
2741                 it.pos() = 0;
2742         }
2743 }
2744
2745
2746 void Buffer::updateMacros() const
2747 {
2748         if (d->macro_lock)
2749                 return;
2750
2751         LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2752
2753         // start with empty table
2754         d->macros.clear();
2755         d->children_positions.clear();
2756         d->position_to_children.clear();
2757
2758         // Iterate over buffer, starting with first paragraph
2759         // The scope must be bigger than any lookup DocIterator
2760         // later. For the global lookup, lastpit+1 is used, hence
2761         // we use lastpit+2 here.
2762         DocIterator it = par_iterator_begin();
2763         DocIterator outerScope = it;
2764         outerScope.pit() = outerScope.lastpit() + 2;
2765         d->updateMacros(it, outerScope);
2766 }
2767
2768
2769 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2770 {
2771         InsetIterator it  = inset_iterator_begin(inset());
2772         InsetIterator const end = inset_iterator_end(inset());
2773         for (; it != end; ++it) {
2774                 if (it->lyxCode() == BRANCH_CODE) {
2775                         InsetBranch & br = static_cast<InsetBranch &>(*it);
2776                         docstring const name = br.branch();
2777                         if (!from_master && !params().branchlist().find(name))
2778                                 result.push_back(name);
2779                         else if (from_master && !masterBuffer()->params().branchlist().find(name))
2780                                 result.push_back(name);
2781                         continue;
2782                 }
2783                 if (it->lyxCode() == INCLUDE_CODE) {
2784                         // get buffer of external file
2785                         InsetInclude const & ins =
2786                                 static_cast<InsetInclude const &>(*it);
2787                         Buffer * child = ins.getChildBuffer();
2788                         if (!child)
2789                                 continue;
2790                         child->getUsedBranches(result, true);
2791                 }
2792         }
2793         // remove duplicates
2794         result.unique();
2795 }
2796
2797
2798 void Buffer::updateMacroInstances() const
2799 {
2800         LYXERR(Debug::MACROS, "updateMacroInstances for "
2801                 << d->filename.onlyFileName());
2802         DocIterator it = doc_iterator_begin(this);
2803         it.forwardInset();
2804         DocIterator const end = doc_iterator_end(this);
2805         for (; it != end; it.forwardInset()) {
2806                 // look for MathData cells in InsetMathNest insets
2807                 InsetMath * minset = it.nextInset()->asInsetMath();
2808                 if (!minset)
2809                         continue;
2810
2811                 // update macro in all cells of the InsetMathNest
2812                 DocIterator::idx_type n = minset->nargs();
2813                 MacroContext mc = MacroContext(this, it);
2814                 for (DocIterator::idx_type i = 0; i < n; ++i) {
2815                         MathData & data = minset->cell(i);
2816                         data.updateMacros(0, mc);
2817                 }
2818         }
2819 }
2820
2821
2822 void Buffer::listMacroNames(MacroNameSet & macros) const
2823 {
2824         if (d->macro_lock)
2825                 return;
2826
2827         d->macro_lock = true;
2828
2829         // loop over macro names
2830         Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2831         Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2832         for (; nameIt != nameEnd; ++nameIt)
2833                 macros.insert(nameIt->first);
2834
2835         // loop over children
2836         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2837         Impl::BufferPositionMap::iterator end = d->children_positions.end();
2838         for (; it != end; ++it)
2839                 it->first->listMacroNames(macros);
2840
2841         // call parent
2842         Buffer const * const pbuf = d->parent();
2843         if (pbuf)
2844                 pbuf->listMacroNames(macros);
2845
2846         d->macro_lock = false;
2847 }
2848
2849
2850 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2851 {
2852         Buffer const * const pbuf = d->parent();
2853         if (!pbuf)
2854                 return;
2855
2856         MacroNameSet names;
2857         pbuf->listMacroNames(names);
2858
2859         // resolve macros
2860         MacroNameSet::iterator it = names.begin();
2861         MacroNameSet::iterator end = names.end();
2862         for (; it != end; ++it) {
2863                 // defined?
2864                 MacroData const * data =
2865                 pbuf->getMacro(*it, *this, false);
2866                 if (data) {
2867                         macros.insert(data);
2868
2869                         // we cannot access the original MathMacroTemplate anymore
2870                         // here to calls validate method. So we do its work here manually.
2871                         // FIXME: somehow make the template accessible here.
2872                         if (data->optionals() > 0)
2873                                 features.require("xargs");
2874                 }
2875         }
2876 }
2877
2878
2879 Buffer::References & Buffer::references(docstring const & label)
2880 {
2881         if (d->parent())
2882                 return const_cast<Buffer *>(masterBuffer())->references(label);
2883
2884         RefCache::iterator it = d->ref_cache_.find(label);
2885         if (it != d->ref_cache_.end())
2886                 return it->second.second;
2887
2888         static InsetLabel const * dummy_il = 0;
2889         static References const dummy_refs;
2890         it = d->ref_cache_.insert(
2891                 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2892         return it->second.second;
2893 }
2894
2895
2896 Buffer::References const & Buffer::references(docstring const & label) const
2897 {
2898         return const_cast<Buffer *>(this)->references(label);
2899 }
2900
2901
2902 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2903 {
2904         masterBuffer()->d->ref_cache_[label].first = il;
2905 }
2906
2907
2908 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2909 {
2910         return masterBuffer()->d->ref_cache_[label].first;
2911 }
2912
2913
2914 void Buffer::clearReferenceCache() const
2915 {
2916         if (!d->parent())
2917                 d->ref_cache_.clear();
2918 }
2919
2920
2921 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2922         InsetCode code)
2923 {
2924         //FIXME: This does not work for child documents yet.
2925         LASSERT(code == CITE_CODE, /**/);
2926         // Check if the label 'from' appears more than once
2927         vector<docstring> labels;
2928         string paramName;
2929         checkBibInfoCache();
2930         BiblioInfo const & keys = masterBibInfo();
2931         BiblioInfo::const_iterator bit  = keys.begin();
2932         BiblioInfo::const_iterator bend = keys.end();
2933
2934         for (; bit != bend; ++bit)
2935                 // FIXME UNICODE
2936                 labels.push_back(bit->first);
2937         paramName = "key";
2938
2939         if (count(labels.begin(), labels.end(), from) > 1)
2940                 return;
2941
2942         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2943                 if (it->lyxCode() == code) {
2944                         InsetCommand & inset = static_cast<InsetCommand &>(*it);
2945                         docstring const oldValue = inset.getParam(paramName);
2946                         if (oldValue == from)
2947                                 inset.setParam(paramName, to);
2948                 }
2949         }
2950 }
2951
2952
2953 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2954         pit_type par_end, bool full_source) const
2955 {
2956         OutputParams runparams(&params().encoding());
2957         runparams.nice = true;
2958         runparams.flavor = params().useXetex ? 
2959                 OutputParams::XETEX : OutputParams::LATEX;
2960         runparams.linelen = lyxrc.plaintext_linelen;
2961         // No side effect of file copying and image conversion
2962         runparams.dryrun = true;
2963
2964         if (full_source) {
2965                 os << "% " << _("Preview source code") << "\n\n";
2966                 d->texrow.reset();
2967                 d->texrow.newline();
2968                 d->texrow.newline();
2969                 if (isDocBook())
2970                         writeDocBookSource(os, absFileName(), runparams, false);
2971                 else
2972                         // latex or literate
2973                         writeLaTeXSource(os, string(), runparams, true, true);
2974         } else {
2975                 runparams.par_begin = par_begin;
2976                 runparams.par_end = par_end;
2977                 if (par_begin + 1 == par_end) {
2978                         os << "% "
2979                            << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2980                            << "\n\n";
2981                 } else {
2982                         os << "% "
2983                            << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2984                                         convert<docstring>(par_begin),
2985                                         convert<docstring>(par_end - 1))
2986                            << "\n\n";
2987                 }
2988                 TexRow texrow;
2989                 texrow.reset();
2990                 texrow.newline();
2991                 texrow.newline();
2992                 // output paragraphs
2993                 if (isDocBook())
2994                         docbookParagraphs(text(), *this, os, runparams);
2995                 else 
2996                         // latex or literate
2997                         latexParagraphs(*this, text(), os, texrow, runparams);
2998         }
2999 }
3000
3001
3002 ErrorList & Buffer::errorList(string const & type) const
3003 {
3004         static ErrorList emptyErrorList;
3005         map<string, ErrorList>::iterator it = d->errorLists.find(type);
3006         if (it == d->errorLists.end())
3007                 return emptyErrorList;
3008
3009         return it->second;
3010 }
3011
3012
3013 void Buffer::updateTocItem(std::string const & type,
3014         DocIterator const & dit) const
3015 {
3016         if (d->gui_)
3017                 d->gui_->updateTocItem(type, dit);
3018 }
3019
3020
3021 void Buffer::structureChanged() const
3022 {
3023         if (d->gui_)
3024                 d->gui_->structureChanged();
3025 }
3026
3027
3028 void Buffer::errors(string const & err, bool from_master) const
3029 {
3030         if (d->gui_)
3031                 d->gui_->errors(err, from_master);
3032 }
3033
3034
3035 void Buffer::message(docstring const & msg) const
3036 {
3037         if (d->gui_)
3038                 d->gui_->message(msg);
3039 }
3040
3041
3042 void Buffer::setBusy(bool on) const
3043 {
3044         if (d->gui_)
3045                 d->gui_->setBusy(on);
3046 }
3047
3048
3049 void Buffer::updateTitles() const
3050 {
3051         if (d->wa_)
3052                 d->wa_->updateTitles();
3053 }
3054
3055
3056 void Buffer::resetAutosaveTimers() const
3057 {
3058         if (d->gui_)
3059                 d->gui_->resetAutosaveTimers();
3060 }
3061
3062
3063 bool Buffer::hasGuiDelegate() const
3064 {
3065         return d->gui_;
3066 }
3067
3068
3069 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3070 {
3071         d->gui_ = gui;
3072 }
3073
3074
3075
3076 namespace {
3077
3078 class AutoSaveBuffer : public ForkedProcess {
3079 public:
3080         ///
3081         AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3082                 : buffer_(buffer), fname_(fname) {}
3083         ///
3084         virtual shared_ptr<ForkedProcess> clone() const
3085         {
3086                 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3087         }
3088         ///
3089         int start()
3090         {
3091                 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3092                                                  from_utf8(fname_.absFileName())));
3093                 return run(DontWait);
3094         }
3095 private:
3096         ///
3097         virtual int generateChild();
3098         ///
3099         Buffer const & buffer_;
3100         FileName fname_;
3101 };
3102
3103
3104 int AutoSaveBuffer::generateChild()
3105 {
3106 #if defined(__APPLE__)
3107         /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard) 
3108          *   We should use something else like threads.
3109          *
3110          * Since I do not know how to determine at run time what is the OS X
3111          * version, I just disable forking altogether for now (JMarc)
3112          */
3113         pid_t const pid = -1;
3114 #else
3115         // tmp_ret will be located (usually) in /tmp
3116         // will that be a problem?
3117         // Note that this calls ForkedCalls::fork(), so it's
3118         // ok cross-platform.
3119         pid_t const pid = fork();
3120         // If you want to debug the autosave
3121         // you should set pid to -1, and comment out the fork.
3122         if (pid != 0 && pid != -1)
3123                 return pid;
3124 #endif
3125
3126         // pid = -1 signifies that lyx was unable
3127         // to fork. But we will do the save
3128         // anyway.
3129         bool failed = false;
3130         FileName const tmp_ret = FileName::tempName("lyxauto");
3131         if (!tmp_ret.empty()) {
3132                 buffer_.writeFile(tmp_ret);
3133                 // assume successful write of tmp_ret
3134                 if (!tmp_ret.moveTo(fname_))
3135                         failed = true;
3136         } else
3137                 failed = true;
3138
3139         if (failed) {
3140                 // failed to write/rename tmp_ret so try writing direct
3141                 if (!buffer_.writeFile(fname_)) {
3142                         // It is dangerous to do this in the child,
3143                         // but safe in the parent, so...
3144                         if (pid == -1) // emit message signal.
3145                                 buffer_.message(_("Autosave failed!"));
3146                 }
3147         }
3148
3149         if (pid == 0) // we are the child so...
3150                 _exit(0);
3151
3152         return pid;
3153 }
3154
3155 } // namespace anon
3156
3157
3158 FileName Buffer::getAutosaveFileName() const
3159 {
3160         // if the document is unnamed try to save in the backup dir, else
3161         // in the default document path, and as a last try in the filePath, 
3162         // which will most often be the temporary directory
3163         string fpath;
3164         if (isUnnamed())
3165                 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3166                         : lyxrc.backupdir_path;
3167         if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3168                 fpath = filePath();
3169
3170         string const fname = "#" + d->filename.onlyFileName() + "#";
3171         return makeAbsPath(fname, fpath);
3172 }
3173
3174
3175 void Buffer::removeAutosaveFile() const
3176 {
3177         FileName const f = getAutosaveFileName();
3178         if (f.exists())
3179                 f.removeFile();
3180 }
3181
3182
3183 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3184 {
3185         FileName const newauto = getAutosaveFileName();
3186         oldauto.refresh();
3187         if (newauto != oldauto && oldauto.exists())
3188                 if (!oldauto.moveTo(newauto))
3189                         LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3190 }
3191
3192
3193 // Perfect target for a thread...
3194 void Buffer::autoSave() const
3195 {
3196         if (d->bak_clean || isReadonly()) {
3197                 // We don't save now, but we'll try again later
3198                 resetAutosaveTimers();
3199                 return;
3200         }
3201
3202         // emit message signal.
3203         message(_("Autosaving current document..."));
3204         AutoSaveBuffer autosave(*this, getAutosaveFileName());
3205         autosave.start();
3206
3207         d->bak_clean = true;
3208
3209         resetAutosaveTimers();
3210 }
3211
3212
3213 string Buffer::bufferFormat() const
3214 {
3215         string format = params().documentClass().outputFormat();
3216         if (format == "latex") {
3217                 if (params().useXetex)
3218                         return "xetex";
3219                 if (params().encoding().package() == Encoding::japanese)
3220                         return "platex";
3221         }
3222         return format;
3223 }
3224
3225
3226 string Buffer::getDefaultOutputFormat() const
3227 {
3228         if (!params().defaultOutputFormat.empty()
3229             && params().defaultOutputFormat != "default")
3230                 return params().defaultOutputFormat;
3231         typedef vector<Format const *> Formats;
3232         Formats formats = exportableFormats(true);
3233         if (isDocBook()
3234             || isLiterate()
3235             || params().useXetex
3236             || params().encoding().package() == Encoding::japanese) {
3237                 if (formats.empty())
3238                         return string();
3239                 // return the first we find
3240                 return formats.front()->name();
3241         }
3242         return lyxrc.default_view_format;
3243 }
3244
3245
3246
3247 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3248         bool includeall, string & result_file) const
3249 {
3250         string backend_format;
3251         OutputParams runparams(&params().encoding());
3252         runparams.flavor = OutputParams::LATEX;
3253         runparams.linelen = lyxrc.plaintext_linelen;
3254         runparams.includeall = includeall;
3255         vector<string> backs = backends();
3256         if (find(backs.begin(), backs.end(), format) == backs.end()) {
3257                 // Get shortest path to format
3258                 Graph::EdgePath path;
3259                 for (vector<string>::const_iterator it = backs.begin();
3260                      it != backs.end(); ++it) {
3261                         Graph::EdgePath p = theConverters().getPath(*it, format);
3262                         if (!p.empty() && (path.empty() || p.size() < path.size())) {
3263                                 backend_format = *it;
3264                                 path = p;
3265                         }
3266                 }
3267                 if (path.empty()) {
3268                         if (!put_in_tempdir) {
3269                                 // Only show this alert if this is an export to a non-temporary
3270                                 // file (not for previewing).
3271                                 Alert::error(_("Couldn't export file"), bformat(
3272                                         _("No information for exporting the format %1$s."),
3273                                         formats.prettyName(format)));
3274                         }
3275                         return false;
3276                 }
3277                 runparams.flavor = theConverters().getFlavor(path);
3278
3279         } else {
3280                 backend_format = format;
3281                 // FIXME: Don't hardcode format names here, but use a flag
3282                 if (backend_format == "pdflatex")
3283                         runparams.flavor = OutputParams::PDFLATEX;
3284         }
3285
3286         string filename = latexName(false);
3287         filename = addName(temppath(), filename);
3288         filename = changeExtension(filename,
3289                                    formats.extension(backend_format));
3290
3291         // fix macros
3292         updateMacroInstances();
3293
3294         // Plain text backend
3295         if (backend_format == "text") {
3296                 runparams.flavor = OutputParams::TEXT;
3297                 writePlaintextFile(*this, FileName(filename), runparams);
3298         }
3299         // HTML backend
3300         else if (backend_format == "xhtml") {
3301                 runparams.flavor = OutputParams::HTML;
3302                 switch (params().html_math_output) {
3303                 case BufferParams::MathML: 
3304                         runparams.math_flavor = OutputParams::MathAsMathML; 
3305                         break;
3306                 case BufferParams::HTML: 
3307                         runparams.math_flavor = OutputParams::MathAsHTML; 
3308                         break;
3309                 case BufferParams::Images:
3310                         runparams.math_flavor = OutputParams::MathAsImages; 
3311                         break;
3312                 case BufferParams::LaTeX:
3313                         runparams.math_flavor = OutputParams::MathAsLaTeX; 
3314                         break;                                                                                  
3315                 }
3316                 
3317                 makeLyXHTMLFile(FileName(filename), runparams);
3318         }       else if (backend_format == "lyx")
3319                 writeFile(FileName(filename));
3320         // Docbook backend
3321         else if (isDocBook()) {
3322                 runparams.nice = !put_in_tempdir;
3323                 makeDocBookFile(FileName(filename), runparams);
3324         }
3325         // LaTeX backend
3326         else if (backend_format == format) {
3327                 runparams.nice = true;
3328                 if (!makeLaTeXFile(FileName(filename), string(), runparams))
3329                         return false;
3330         } else if (!lyxrc.tex_allows_spaces
3331                    && contains(filePath(), ' ')) {
3332                 Alert::error(_("File name error"),
3333                            _("The directory path to the document cannot contain spaces."));
3334                 return false;
3335         } else {
3336                 runparams.nice = false;
3337                 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
3338                         return false;
3339         }
3340
3341         string const error_type = (format == "program")
3342                 ? "Build" : bufferFormat();
3343         ErrorList & error_list = d->errorLists[error_type];
3344         string const ext = formats.extension(format);
3345         FileName const tmp_result_file(changeExtension(filename, ext));
3346         bool const success = theConverters().convert(this, FileName(filename),
3347                 tmp_result_file, FileName(absFileName()), backend_format, format,
3348                 error_list);
3349
3350         // Emit the signal to show the error list or copy it back to the
3351         // cloned Buffer so that it cab be emitted afterwards.
3352         if (format != backend_format) {
3353                 if (d->cloned_buffer_) {
3354                         d->cloned_buffer_->d->errorLists[error_type] = 
3355                                 d->errorLists[error_type];
3356                 } else 
3357                         errors(error_type);
3358                 // also to the children, in case of master-buffer-view
3359                 std::vector<Buffer *> clist = getChildren();
3360                 for (vector<Buffer *>::const_iterator cit = clist.begin();
3361                         cit != clist.end(); ++cit) {
3362                         if (d->cloned_buffer_) {
3363                                 (*cit)->d->cloned_buffer_->d->errorLists[error_type] = 
3364                                         (*cit)->d->errorLists[error_type];
3365                         } else
3366                                 (*cit)->errors(error_type, true);
3367                 }
3368         }
3369
3370         if (d->cloned_buffer_) {
3371                 // Enable reverse dvi or pdf to work by copying back the texrow
3372                 // object to the cloned buffer.
3373                 // FIXME: There is a possibility of concurrent access to texrow
3374                 // here from the main GUI thread that should be securized.
3375                 d->cloned_buffer_->d->texrow = d->texrow;
3376                 string const error_type = bufferFormat();
3377                 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
3378         }
3379
3380         if (!success)
3381                 return false;
3382
3383         if (put_in_tempdir) {
3384                 result_file = tmp_result_file.absFileName();
3385                 return true;
3386         }
3387
3388         result_file = changeExtension(d->exportFileName().absFileName(), ext);
3389         // We need to copy referenced files (e. g. included graphics
3390         // if format == "dvi") to the result dir.
3391         vector<ExportedFile> const files =
3392                 runparams.exportdata->externalFiles(format);
3393         string const dest = onlyPath(result_file);
3394         bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
3395                                  : force_overwrite == ALL_FILES;
3396         CopyStatus status = use_force ? FORCE : SUCCESS;
3397         
3398         vector<ExportedFile>::const_iterator it = files.begin();
3399         vector<ExportedFile>::const_iterator const en = files.end();
3400         for (; it != en && status != CANCEL; ++it) {
3401                 string const fmt = formats.getFormatFromFile(it->sourceName);
3402                 status = copyFile(fmt, it->sourceName,
3403                         makeAbsPath(it->exportName, dest),
3404                         it->exportName, status == FORCE);
3405         }
3406
3407         if (status == CANCEL) {
3408                 message(_("Document export cancelled."));
3409         } else if (tmp_result_file.exists()) {
3410                 // Finally copy the main file
3411                 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
3412                                     : force_overwrite != NO_FILES;
3413                 if (status == SUCCESS && use_force)
3414                         status = FORCE;
3415                 status = copyFile(format, tmp_result_file,
3416                         FileName(result_file), result_file,
3417                         status == FORCE);
3418                 message(bformat(_("Document exported as %1$s "
3419                         "to file `%2$s'"),
3420                         formats.prettyName(format),
3421                         makeDisplayPath(result_file)));
3422         } else {
3423                 // This must be a dummy converter like fax (bug 1888)
3424                 message(bformat(_("Document exported as %1$s"),
3425                         formats.prettyName(format)));
3426         }
3427
3428         return true;
3429 }
3430
3431
3432 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3433                       bool includeall) const
3434 {
3435         string result_file;
3436         // (1) export with all included children (omit \includeonly)
3437         if (includeall && !doExport(format, put_in_tempdir, true, result_file))
3438                 return false;
3439         // (2) export with included children only
3440         return doExport(format, put_in_tempdir, false, result_file);
3441 }
3442
3443
3444 bool Buffer::preview(string const & format, bool includeall) const
3445 {
3446         string result_file;
3447         // (1) export with all included children (omit \includeonly)
3448         if (includeall && !doExport(format, true, true))
3449                 return false;
3450         // (2) export with included children only
3451         if (!doExport(format, true, false, result_file))
3452                 return false;
3453         return formats.view(*this, FileName(result_file), format);
3454 }
3455
3456
3457 bool Buffer::isExportable(string const & format) const
3458 {
3459         vector<string> backs = backends();
3460         for (vector<string>::const_iterator it = backs.begin();
3461              it != backs.end(); ++it)
3462                 if (theConverters().isReachable(*it, format))
3463                         return true;
3464         return false;
3465 }
3466
3467
3468 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
3469 {
3470         vector<string> const backs = backends();
3471         vector<Format const *> result =
3472                 theConverters().getReachable(backs[0], only_viewable, true);
3473         for (vector<string>::const_iterator it = backs.begin() + 1;
3474              it != backs.end(); ++it) {
3475                 vector<Format const *>  r =
3476                         theConverters().getReachable(*it, only_viewable, false);
3477                 result.insert(result.end(), r.begin(), r.end());
3478         }
3479         return result;
3480 }
3481
3482
3483 vector<string> Buffer::backends() const
3484 {
3485         vector<string> v;
3486         v.push_back(bufferFormat());
3487         // FIXME: Don't hardcode format names here, but use a flag
3488         if (v.back() == "latex")
3489                 v.push_back("pdflatex");
3490         v.push_back("xhtml");
3491         v.push_back("text");
3492         v.push_back("lyx");
3493         return v;
3494 }
3495
3496
3497 bool Buffer::readFileHelper(FileName const & s)
3498 {
3499         // File information about normal file
3500         if (!s.exists()) {
3501                 docstring const file = makeDisplayPath(s.absFileName(), 50);
3502                 docstring text = bformat(_("The specified document\n%1$s"
3503                                                      "\ncould not be read."), file);
3504                 Alert::error(_("Could not read document"), text);
3505                 return false;
3506         }
3507
3508         // Check if emergency save file exists and is newer.
3509         FileName const e(s.absFileName() + ".emergency");
3510
3511         if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
3512                 docstring const file = makeDisplayPath(s.absFileName(), 20);
3513                 docstring const text =
3514                         bformat(_("An emergency save of the document "
3515                                   "%1$s exists.\n\n"
3516                                                "Recover emergency save?"), file);
3517                 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
3518                                       _("&Recover"),  _("&Load Original"),
3519                                       _("&Cancel")))
3520                 {
3521                 case 0: {
3522                         // the file is not saved if we load the emergency file.
3523                         markDirty();
3524                         docstring str;
3525                         bool res;
3526
3527                         if ((res = readFile(e)) == success)
3528                                 str = _("Document was successfully recovered.");
3529                         else
3530                                 str = _("Document was NOT successfully recovered.");
3531                         str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3532                                                 makeDisplayPath(e.absFileName()));
3533
3534                         if (!Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3535                                         _("&Remove"), _("&Keep it"))) {
3536                                 e.removeFile();
3537                                 if (res == success)
3538                                         Alert::warning(_("Emergency file deleted"),
3539                                                 _("Do not forget to save your file now!"), true);
3540                                 }
3541                         return res;
3542                 }
3543                 case 1:
3544                         if (!Alert::prompt(_("Delete emergency file?"),
3545                                         _("Remove emergency file now?"), 1, 1,
3546                                         _("&Remove"), _("&Keep it")))
3547                                 e.removeFile();
3548                         break;
3549                 default:
3550                         return false;
3551                 }
3552         }
3553
3554         // Now check if autosave file is newer.
3555         FileName const a(onlyPath(s.absFileName()) + '#' + onlyFileName(s.absFileName()) + '#');
3556
3557         if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
3558                 docstring const file = makeDisplayPath(s.absFileName(), 20);
3559                 docstring const text =
3560                         bformat(_("The backup of the document "
3561                                   "%1$s is newer.\n\nLoad the "
3562                                                "backup instead?"), file);
3563                 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
3564                                       _("&Load backup"), _("Load &original"),
3565                                       _("&Cancel") ))
3566                 {
3567                 case 0:
3568                         // the file is not saved if we load the autosave file.
3569                         markDirty();
3570                         return readFile(a);
3571                 case 1:
3572                         // Here we delete the autosave
3573                         a.removeFile();
3574                         break;
3575                 default:
3576                         return false;
3577                 }
3578         }
3579         return readFile(s);
3580 }
3581
3582
3583 bool Buffer::loadLyXFile(FileName const & s)
3584 {
3585         // If the file is not readable, we try to
3586         // retrieve the file from version control.
3587         if (!s.isReadableFile()
3588                   && !LyXVC::file_not_found_hook(s))
3589                 return false;
3590         
3591         if (s.isReadableFile()){
3592                 // InsetInfo needs to know if file is under VCS
3593                 lyxvc().file_found_hook(s);
3594                 if (readFileHelper(s)) {
3595                         d->read_only = !s.isWritable();
3596                         return true;
3597                 }
3598         }
3599         return false;
3600 }
3601
3602
3603 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3604 {
3605         TeXErrors::Errors::const_iterator cit = terr.begin();
3606         TeXErrors::Errors::const_iterator end = terr.end();
3607
3608         for (; cit != end; ++cit) {
3609                 int id_start = -1;
3610                 int pos_start = -1;
3611                 int errorRow = cit->error_in_line;
3612                 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3613                                                        pos_start);
3614                 int id_end = -1;
3615                 int pos_end = -1;
3616                 do {
3617                         ++errorRow;
3618                         found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3619                 } while (found && id_start == id_end && pos_start == pos_end);
3620
3621                 errorList.push_back(ErrorItem(cit->error_desc,
3622                         cit->error_text, id_start, pos_start, pos_end));
3623         }
3624 }
3625
3626
3627 void Buffer::setBuffersForInsets() const
3628 {
3629         inset().setBuffer(const_cast<Buffer &>(*this)); 
3630 }
3631
3632
3633 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
3634 {
3635         // Use the master text class also for child documents
3636         Buffer const * const master = masterBuffer();
3637         DocumentClass const & textclass = master->params().documentClass();
3638         
3639         // do this only if we are the top-level Buffer
3640         if (scope != UpdateMaster || master == this)
3641                 checkBibInfoCache();
3642
3643         // keep the buffers to be children in this set. If the call from the
3644         // master comes back we can see which of them were actually seen (i.e.
3645         // via an InsetInclude). The remaining ones in the set need still be updated.
3646         static std::set<Buffer const *> bufToUpdate;
3647         if (scope == UpdateMaster) {
3648                 // If this is a child document start with the master
3649                 if (master != this) {
3650                         bufToUpdate.insert(this);
3651                         master->updateBuffer(UpdateMaster, utype);
3652                         // Do this here in case the master has no gui associated with it. Then, 
3653                         // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3654                         if (!master->d->gui_)
3655                                 structureChanged();
3656
3657                         // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3658                         if (bufToUpdate.find(this) == bufToUpdate.end())
3659                                 return;
3660                 }
3661
3662                 // start over the counters in the master
3663                 textclass.counters().reset();
3664         }
3665
3666         // update will be done below for this buffer
3667         bufToUpdate.erase(this);
3668
3669         // update all caches
3670         clearReferenceCache();
3671         updateMacros();
3672
3673         Buffer & cbuf = const_cast<Buffer &>(*this);
3674
3675         LASSERT(!text().paragraphs().empty(), /**/);
3676
3677         // do the real work
3678         ParIterator parit = cbuf.par_iterator_begin();
3679         updateBuffer(parit, utype);
3680
3681         if (master != this)
3682                 // TocBackend update will be done later.
3683                 return;
3684
3685         cbuf.tocBackend().update();
3686         if (scope == UpdateMaster)
3687                 cbuf.structureChanged();
3688 }
3689
3690
3691 static depth_type getDepth(DocIterator const & it)
3692 {
3693         depth_type depth = 0;
3694         for (size_t i = 0 ; i < it.depth() ; ++i)
3695                 if (!it[i].inset().inMathed())
3696                         depth += it[i].paragraph().getDepth() + 1;
3697         // remove 1 since the outer inset does not count
3698         return depth - 1;
3699 }
3700
3701 static depth_type getItemDepth(ParIterator const & it)
3702 {
3703         Paragraph const & par = *it;
3704         LabelType const labeltype = par.layout().labeltype;
3705
3706         if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3707                 return 0;
3708
3709         // this will hold the lowest depth encountered up to now.
3710         depth_type min_depth = getDepth(it);
3711         ParIterator prev_it = it;
3712         while (true) {
3713                 if (prev_it.pit())
3714                         --prev_it.top().pit();
3715                 else {
3716                         // start of nested inset: go to outer par
3717                         prev_it.pop_back();
3718                         if (prev_it.empty()) {
3719                                 // start of document: nothing to do
3720                                 return 0;
3721                         }
3722                 }
3723
3724                 // We search for the first paragraph with same label
3725                 // that is not more deeply nested.
3726                 Paragraph & prev_par = *prev_it;
3727                 depth_type const prev_depth = getDepth(prev_it);
3728                 if (labeltype == prev_par.layout().labeltype) {
3729                         if (prev_depth < min_depth)
3730                                 return prev_par.itemdepth + 1;
3731                         if (prev_depth == min_depth)
3732                                 return prev_par.itemdepth;
3733                 }
3734                 min_depth = min(min_depth, prev_depth);
3735                 // small optimization: if we are at depth 0, we won't
3736                 // find anything else
3737                 if (prev_depth == 0)
3738                         return 0;
3739         }
3740 }
3741
3742
3743 static bool needEnumCounterReset(ParIterator const & it)
3744 {
3745         Paragraph const & par = *it;
3746         LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3747         depth_type const cur_depth = par.getDepth();
3748         ParIterator prev_it = it;
3749         while (prev_it.pit()) {
3750                 --prev_it.top().pit();
3751                 Paragraph const & prev_par = *prev_it;
3752                 if (prev_par.getDepth() <= cur_depth)
3753                         return  prev_par.layout().labeltype != LABEL_ENUMERATE;
3754         }
3755         // start of nested inset: reset
3756         return true;
3757 }
3758
3759
3760 // set the label of a paragraph. This includes the counters.
3761 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
3762 {
3763         BufferParams const & bp = owner_->masterBuffer()->params();
3764         DocumentClass const & textclass = bp.documentClass();
3765         Paragraph & par = it.paragraph();
3766         Layout const & layout = par.layout();
3767         Counters & counters = textclass.counters();
3768
3769         if (par.params().startOfAppendix()) {
3770                 // FIXME: only the counter corresponding to toplevel
3771                 // sectioning should be reset
3772                 counters.reset();
3773                 counters.appendix(true);
3774         }
3775         par.params().appendix(counters.appendix());
3776
3777         // Compute the item depth of the paragraph
3778         par.itemdepth = getItemDepth(it);
3779
3780         if (layout.margintype == MARGIN_MANUAL
3781             || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3782                 if (par.params().labelWidthString().empty())
3783                         par.params().labelWidthString(par.expandLabel(layout, bp));
3784         } else {
3785                 par.params().labelWidthString(docstring());
3786         }
3787
3788         switch(layout.labeltype) {
3789         case LABEL_COUNTER:
3790                 if (layout.toclevel <= bp.secnumdepth
3791                     && (layout.latextype != LATEX_ENVIRONMENT
3792                         || it.text()->isFirstInSequence(it.pit()))) {
3793                         counters.step(layout.counter, utype);
3794                         par.params().labelString(
3795                                 par.expandLabel(layout, bp));
3796                 } else
3797                         par.params().labelString(docstring());
3798                 break;
3799
3800         case LABEL_ITEMIZE: {
3801                 // At some point of time we should do something more
3802                 // clever here, like:
3803                 //   par.params().labelString(
3804                 //    bp.user_defined_bullet(par.itemdepth).getText());
3805                 // for now, use a simple hardcoded label
3806                 docstring itemlabel;
3807                 switch (par.itemdepth) {
3808                 case 0:
3809                         itemlabel = char_type(0x2022);
3810                         break;
3811                 case 1:
3812                         itemlabel = char_type(0x2013);
3813                         break;
3814                 case 2:
3815                         itemlabel = char_type(0x2217);
3816                         break;
3817                 case 3:
3818                         itemlabel = char_type(0x2219); // or 0x00b7
3819                         break;
3820                 }
3821                 par.params().labelString(itemlabel);
3822                 break;
3823         }
3824
3825         case LABEL_ENUMERATE: {
3826                 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
3827
3828                 switch (par.itemdepth) {
3829                 case 2:
3830                         enumcounter += 'i';
3831                 case 1:
3832                         enumcounter += 'i';
3833                 case 0:
3834                         enumcounter += 'i';
3835                         break;
3836                 case 3:
3837                         enumcounter += "iv";
3838                         break;
3839                 default:
3840                         // not a valid enumdepth...
3841                         break;
3842                 }
3843
3844                 // Maybe we have to reset the enumeration counter.
3845                 if (needEnumCounterReset(it))
3846                         counters.reset(enumcounter);
3847                 counters.step(enumcounter, utype);
3848
3849                 string const & lang = par.getParLanguage(bp)->code();
3850                 par.params().labelString(counters.theCounter(enumcounter, lang));
3851
3852                 break;
3853         }
3854
3855         case LABEL_SENSITIVE: {
3856                 string const & type = counters.current_float();
3857                 docstring full_label;
3858                 if (type.empty())
3859                         full_label = owner_->B_("Senseless!!! ");
3860                 else {
3861                         docstring name = owner_->B_(textclass.floats().getType(type).name());
3862                         if (counters.hasCounter(from_utf8(type))) {
3863                                 string const & lang = par.getParLanguage(bp)->code();
3864                                 counters.step(from_utf8(type), utype);
3865                                 full_label = bformat(from_ascii("%1$s %2$s:"), 
3866                                                      name, 
3867                                                      counters.theCounter(from_utf8(type), lang));
3868                         } else
3869                                 full_label = bformat(from_ascii("%1$s #:"), name);      
3870                 }
3871                 par.params().labelString(full_label);   
3872                 break;
3873         }
3874
3875         case LABEL_NO_LABEL:
3876                 par.params().labelString(docstring());
3877                 break;
3878
3879         case LABEL_MANUAL:
3880         case LABEL_TOP_ENVIRONMENT:
3881         case LABEL_CENTERED_TOP_ENVIRONMENT:
3882         case LABEL_STATIC:      
3883         case LABEL_BIBLIO:
3884                 par.params().labelString(par.expandLabel(layout, bp));
3885                 break;
3886         }
3887 }
3888
3889
3890 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
3891 {
3892         LASSERT(parit.pit() == 0, /**/);
3893
3894         // set the position of the text in the buffer to be able
3895         // to resolve macros in it. This has nothing to do with
3896         // labels, but by putting it here we avoid implementing
3897         // a whole bunch of traversal routines just for this call.
3898         parit.text()->setMacrocontextPosition(parit);
3899
3900         depth_type maxdepth = 0;
3901         pit_type const lastpit = parit.lastpit();
3902         for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3903                 // reduce depth if necessary
3904                 parit->params().depth(min(parit->params().depth(), maxdepth));
3905                 maxdepth = parit->getMaxDepthAfter();
3906
3907                 if (utype == OutputUpdate) {
3908                         // track the active counters
3909                         // we have to do this for the master buffer, since the local
3910                         // buffer isn't tracking anything.
3911                         masterBuffer()->params().documentClass().counters().
3912                                         setActiveLayout(parit->layout());
3913                 }
3914                 
3915                 // set the counter for this paragraph
3916                 d->setLabel(parit, utype);
3917
3918                 // now the insets
3919                 InsetList::const_iterator iit = parit->insetList().begin();
3920                 InsetList::const_iterator end = parit->insetList().end();
3921                 for (; iit != end; ++iit) {
3922                         parit.pos() = iit->pos;
3923                         iit->inset->updateBuffer(parit, utype);
3924                 }
3925         }
3926 }
3927
3928
3929 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
3930         WordLangTuple & word_lang, docstring_list & suggestions) const
3931 {
3932         int progress = 0;
3933         WordLangTuple wl;
3934         suggestions.clear();
3935         word_lang = WordLangTuple();
3936         // OK, we start from here.
3937         DocIterator const end = doc_iterator_end(this);
3938         for (; from != end; from.forwardPos()) {
3939                 // We are only interested in text so remove the math CursorSlice.
3940                 while (from.inMathed()) {
3941                         from.pop_back();
3942                         from.pos()++;
3943                 }
3944                 // If from is at the end of the document (which is possible
3945                 // when leaving the mathed) LyX will crash later.
3946                 if (from == end)
3947                         break;
3948                 to = from;
3949                 if (from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions)) {
3950                         word_lang = wl;
3951                         break;
3952                 }
3953
3954                 // Do not increase progress when from == to, otherwise the word
3955                 // count will be wrong.
3956                 if (from != to) {
3957                         from = to;
3958                         ++progress;
3959                 }
3960         }
3961         return progress;
3962 }
3963
3964
3965 bool Buffer::reload()
3966 {
3967         setBusy(true);
3968         // c.f. bug 6587
3969         removeAutosaveFile();
3970         // e.g., read-only status could have changed due to version control
3971         d->filename.refresh();
3972         docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
3973
3974         bool const success = loadLyXFile(d->filename);
3975         if (success) {
3976                 updateBuffer();
3977                 changed(true);
3978                 updateTitles();
3979                 markClean();
3980                 message(bformat(_("Document %1$s reloaded."), disp_fn));
3981         } else {
3982                 message(bformat(_("Could not reload document %1$s."), disp_fn));
3983         }       
3984         setBusy(false);
3985         thePreviews().removeLoader(*this);
3986         if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
3987                 thePreviews().generateBufferPreviews(*this);
3988         errors("Parse");
3989         return success;
3990 }
3991
3992
3993 // FIXME We could do better here, but it is complicated. What would be
3994 // nice is to offer either (a) to save the child buffer to an appropriate
3995 // location, so that it would "move with the master", or else (b) to update
3996 // the InsetInclude so that it pointed to the same file. But (a) is a bit
3997 // complicated, because the code for this lives in GuiView.
3998 void Buffer::checkChildBuffers()
3999 {
4000         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4001         Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4002         for (; it != en; ++it) {
4003                 DocIterator dit = it->second;
4004                 Buffer * cbuf = const_cast<Buffer *>(it->first);
4005                 if (!cbuf || !theBufferList().isLoaded(cbuf))
4006                         continue;
4007                 Inset * inset = dit.nextInset();
4008                 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4009                 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4010                 docstring const & incfile = inset_inc->getParam("filename");
4011                 string oldloc = cbuf->absFileName();
4012                 string newloc = makeAbsPath(to_utf8(incfile),
4013                                 onlyPath(absFileName())).absFileName();
4014                 if (oldloc == newloc)
4015                         continue;
4016                 // the location of the child file is incorrect.
4017                 Alert::warning(_("Included File Invalid"),
4018                                 bformat(_("Saving this document to a new location has made the file:\n"
4019                                 "  %1$s\n"
4020                                 "inaccessible. You will need to update the included filename."),
4021                                 from_utf8(oldloc)));
4022                 cbuf->setParent(0);
4023                 inset_inc->setChildBuffer(0);
4024         }
4025         // invalidate cache of children
4026         d->children_positions.clear();
4027         d->position_to_children.clear();
4028 }
4029
4030 } // namespace lyx