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