3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Stefan Schimanski
9 * Full author contact details are available in file CREDITS.
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"
25 #include "Converter.h"
27 #include "DocIterator.h"
29 #include "ErrorList.h"
32 #include "FuncRequest.h"
33 #include "InsetIterator.h"
34 #include "InsetList.h"
36 #include "LaTeXFeatures.h"
40 #include "LyXAction.h"
44 #include "output_docbook.h"
46 #include "output_latex.h"
47 #include "output_plaintext.h"
48 #include "paragraph_funcs.h"
49 #include "Paragraph.h"
50 #include "ParagraphParameters.h"
51 #include "ParIterator.h"
52 #include "PDFOptions.h"
55 #include "TexStream.h"
57 #include "TextClass.h"
58 #include "TocBackend.h"
60 #include "VCBackend.h"
64 #include "insets/InsetBibitem.h"
65 #include "insets/InsetBibtex.h"
66 #include "insets/InsetInclude.h"
67 #include "insets/InsetText.h"
69 #include "mathed/MacroTable.h"
70 #include "mathed/MathMacroTemplate.h"
71 #include "mathed/MathSupport.h"
73 #include "frontends/alert.h"
74 #include "frontends/Delegates.h"
75 #include "frontends/WorkAreaManager.h"
77 #include "graphics/Previews.h"
79 #include "support/lassert.h"
80 #include "support/convert.h"
81 #include "support/debug.h"
82 #include "support/ExceptionMessage.h"
83 #include "support/FileName.h"
84 #include "support/FileNameList.h"
85 #include "support/filetools.h"
86 #include "support/ForkedCalls.h"
87 #include "support/gettext.h"
88 #include "support/gzstream.h"
89 #include "support/lstrings.h"
90 #include "support/lyxalgo.h"
91 #include "support/os.h"
92 #include "support/Package.h"
93 #include "support/Path.h"
94 #include "support/textutils.h"
95 #include "support/types.h"
97 #include <boost/bind.hpp>
98 #include <boost/shared_ptr.hpp>
109 using namespace lyx::support;
113 namespace Alert = frontend::Alert;
114 namespace os = support::os;
118 int const LYX_FORMAT = 338; //Uwe: support for polytonic Greek
120 typedef map<string, bool> DepClean;
121 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
128 Impl(Buffer & parent, FileName const & file, bool readonly);
141 mutable TexRow texrow;
142 Buffer const * parent_buffer;
144 /// need to regenerate .tex?
148 mutable bool lyx_clean;
150 /// is autosave needed?
151 mutable bool bak_clean;
153 /// is this a unnamed file (New...)?
159 /// name of the file the buffer is associated with.
162 /** Set to true only when the file is fully loaded.
163 * Used to prevent the premature generation of previews
164 * and by the citation inset.
166 bool file_fully_loaded;
169 mutable TocBackend toc_backend;
172 typedef pair<DocIterator, MacroData> ScopeMacro;
173 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
174 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
175 /// map from the macro name to the position map,
176 /// which maps the macro definition position to the scope and the MacroData.
177 NamePositionScopeMacroMap macros;
180 /// positions of child buffers in the buffer
181 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
182 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
183 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
184 /// position of children buffers in this buffer
185 BufferPositionMap children_positions;
186 /// map from children inclusion positions to their scope and their buffer
187 PositionScopeBufferMap position_to_children;
189 /// Container for all sort of Buffer dependant errors.
190 map<string, ErrorList> errorLists;
192 /// timestamp and checksum used to test if the file has been externally
193 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
195 unsigned long checksum_;
198 frontend::WorkAreaManager * wa_;
203 /// A cache for the bibfiles (including bibfiles of loaded child
204 /// documents), needed for appropriate update of natbib labels.
205 mutable support::FileNameList bibfilesCache_;
207 // FIXME The caching mechanism could be improved. At present, we have a
208 // cache for each Buffer, that caches all the bibliography info for that
209 // Buffer. A more efficient solution would be to have a global cache per
210 // file, and then to construct the Buffer's bibinfo from that.
211 /// A cache for bibliography info
212 mutable BiblioInfo bibinfo_;
213 /// whether the bibinfo cache is valid
214 bool bibinfoCacheValid_;
215 /// Cache of timestamps of .bib files
216 map<FileName, time_t> bibfileStatus_;
218 mutable RefCache ref_cache_;
220 /// our Text that should be wrapped in an InsetText
225 /// Creates the per buffer temporary directory
226 static FileName createBufferTmpDir()
229 // We are in our own directory. Why bother to mangle name?
230 // In fact I wrote this code to circumvent a problematic behaviour
231 // (bug?) of EMX mkstemp().
232 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
233 convert<string>(count++));
235 if (!tmpfl.createDirectory(0777)) {
236 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
237 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
238 from_utf8(tmpfl.absFilename())));
244 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
245 : parent_buffer(0), lyx_clean(true), bak_clean(true), unnamed(false),
246 read_only(readonly_), filename(file), file_fully_loaded(false),
247 toc_backend(&parent), macro_lock(false), timestamp_(0),
248 checksum_(0), wa_(0), undo_(parent), bibinfoCacheValid_(false)
250 temppath = createBufferTmpDir();
251 lyxvc.setBuffer(&parent);
253 wa_ = new frontend::WorkAreaManager;
257 Buffer::Buffer(string const & file, bool readonly)
258 : d(new Impl(*this, FileName(file), readonly)), gui_(0)
260 LYXERR(Debug::INFO, "Buffer::Buffer()");
262 d->inset.setBuffer(*this);
263 d->inset.initParagraphs(*this);
264 d->inset.setAutoBreakRows(true);
265 d->inset.getText(0)->setMacrocontextPosition(par_iterator_begin());
271 LYXERR(Debug::INFO, "Buffer::~Buffer()");
272 // here the buffer should take care that it is
273 // saved properly, before it goes into the void.
275 // GuiView already destroyed
279 // loop over children
280 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
281 Impl::BufferPositionMap::iterator end = d->children_positions.end();
282 for (; it != end; ++it)
283 theBufferList().releaseChild(this, const_cast<Buffer *>(it->first));
285 // clear references to children in macro tables
286 d->children_positions.clear();
287 d->position_to_children.clear();
289 if (!d->temppath.destroyDirectory()) {
290 Alert::warning(_("Could not remove temporary directory"),
291 bformat(_("Could not remove the temporary directory %1$s"),
292 from_utf8(d->temppath.absFilename())));
295 // Remove any previewed LaTeX snippets associated with this buffer.
296 thePreviews().removeLoader(*this);
302 void Buffer::changed() const
309 frontend::WorkAreaManager & Buffer::workAreaManager() const
311 LASSERT(d->wa_, /**/);
316 Text & Buffer::text() const
318 return const_cast<Text &>(d->inset.text_);
322 Inset & Buffer::inset() const
324 return const_cast<InsetText &>(d->inset);
328 BufferParams & Buffer::params()
334 BufferParams const & Buffer::params() const
340 ParagraphList & Buffer::paragraphs()
342 return text().paragraphs();
346 ParagraphList const & Buffer::paragraphs() const
348 return text().paragraphs();
352 LyXVC & Buffer::lyxvc()
358 LyXVC const & Buffer::lyxvc() const
364 string const Buffer::temppath() const
366 return d->temppath.absFilename();
370 TexRow const & Buffer::texrow() const
376 TocBackend & Buffer::tocBackend() const
378 return d->toc_backend;
382 Undo & Buffer::undo()
388 string Buffer::latexName(bool const no_path) const
390 FileName latex_name = makeLatexName(d->filename);
391 return no_path ? latex_name.onlyFileName()
392 : latex_name.absFilename();
396 string Buffer::logName(LogType * type) const
398 string const filename = latexName(false);
400 if (filename.empty()) {
406 string const path = temppath();
408 FileName const fname(addName(temppath(),
409 onlyFilename(changeExtension(filename,
411 FileName const bname(
412 addName(path, onlyFilename(
413 changeExtension(filename,
414 formats.extension("literate") + ".out"))));
416 // If no Latex log or Build log is newer, show Build log
418 if (bname.exists() &&
419 (!fname.exists() || fname.lastModified() < bname.lastModified())) {
420 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
423 return bname.absFilename();
425 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
428 return fname.absFilename();
432 void Buffer::setReadonly(bool const flag)
434 if (d->read_only != flag) {
441 void Buffer::setFileName(string const & newfile)
443 d->filename = makeAbsPath(newfile);
444 setReadonly(d->filename.isReadOnly());
449 int Buffer::readHeader(Lexer & lex)
451 int unknown_tokens = 0;
453 int begin_header_line = -1;
455 // Initialize parameters that may be/go lacking in header:
456 params().branchlist().clear();
457 params().preamble.erase();
458 params().options.erase();
459 params().master.erase();
460 params().float_placement.erase();
461 params().paperwidth.erase();
462 params().paperheight.erase();
463 params().leftmargin.erase();
464 params().rightmargin.erase();
465 params().topmargin.erase();
466 params().bottommargin.erase();
467 params().headheight.erase();
468 params().headsep.erase();
469 params().footskip.erase();
470 params().columnsep.erase();
471 params().fontsCJK.erase();
472 params().listings_params.clear();
473 params().clearLayoutModules();
474 params().pdfoptions().clear();
476 for (int i = 0; i < 4; ++i) {
477 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
478 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
481 ErrorList & errorList = d->errorLists["Parse"];
490 if (token == "\\end_header")
494 if (token == "\\begin_header") {
495 begin_header_line = line;
499 LYXERR(Debug::PARSER, "Handling document header token: `"
502 string unknown = params().readToken(lex, token, d->filename.onlyPath());
503 if (!unknown.empty()) {
504 if (unknown[0] != '\\' && token == "\\textclass") {
505 Alert::warning(_("Unknown document class"),
506 bformat(_("Using the default document class, because the "
507 "class %1$s is unknown."), from_utf8(unknown)));
510 docstring const s = bformat(_("Unknown token: "
514 errorList.push_back(ErrorItem(_("Document header error"),
519 if (begin_header_line) {
520 docstring const s = _("\\begin_header is missing");
521 errorList.push_back(ErrorItem(_("Document header error"),
525 params().makeDocumentClass();
527 return unknown_tokens;
532 // changed to be public and have one parameter
533 // Returns false if "\end_document" is not read (Asger)
534 bool Buffer::readDocument(Lexer & lex)
536 ErrorList & errorList = d->errorLists["Parse"];
539 if (!lex.checkFor("\\begin_document")) {
540 docstring const s = _("\\begin_document is missing");
541 errorList.push_back(ErrorItem(_("Document header error"),
545 // we are reading in a brand new document
546 LASSERT(paragraphs().empty(), /**/);
550 if (params().outputChanges) {
551 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
552 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
553 LaTeXFeatures::isAvailable("xcolor");
555 if (!dvipost && !xcolorsoul) {
556 Alert::warning(_("Changes not shown in LaTeX output"),
557 _("Changes will not be highlighted in LaTeX output, "
558 "because neither dvipost nor xcolor/soul are installed.\n"
559 "Please install these packages or redefine "
560 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
561 } else if (!xcolorsoul) {
562 Alert::warning(_("Changes not shown in LaTeX output"),
563 _("Changes will not be highlighted in LaTeX output "
564 "when using pdflatex, because xcolor and soul are not installed.\n"
565 "Please install both packages or redefine "
566 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
570 if (!params().master.empty()) {
571 FileName const master_file = makeAbsPath(params().master,
572 onlyPath(absFileName()));
573 if (isLyXFilename(master_file.absFilename())) {
574 Buffer * master = checkAndLoadLyXFile(master_file);
575 d->parent_buffer = master;
580 bool const res = text().read(*this, lex, errorList, &(d->inset));
583 updateMacroInstances();
588 // needed to insert the selection
589 void Buffer::insertStringAsLines(ParagraphList & pars,
590 pit_type & pit, pos_type & pos,
591 Font const & fn, docstring const & str, bool autobreakrows)
595 // insert the string, don't insert doublespace
596 bool space_inserted = true;
597 for (docstring::const_iterator cit = str.begin();
598 cit != str.end(); ++cit) {
599 Paragraph & par = pars[pit];
601 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
602 breakParagraph(params(), pars, pit, pos,
603 par.layout().isEnvironment());
606 space_inserted = true;
610 // do not insert consecutive spaces if !free_spacing
611 } else if ((*cit == ' ' || *cit == '\t') &&
612 space_inserted && !par.isFreeSpacing()) {
614 } else if (*cit == '\t') {
615 if (!par.isFreeSpacing()) {
616 // tabs are like spaces here
617 par.insertChar(pos, ' ', font, params().trackChanges);
619 space_inserted = true;
621 const pos_type n = 8 - pos % 8;
622 for (pos_type i = 0; i < n; ++i) {
623 par.insertChar(pos, ' ', font, params().trackChanges);
626 space_inserted = true;
628 } else if (!isPrintable(*cit)) {
629 // Ignore unprintables
632 // just insert the character
633 par.insertChar(pos, *cit, font, params().trackChanges);
635 space_inserted = (*cit == ' ');
642 bool Buffer::readString(string const & s)
644 params().compressed = false;
646 // remove dummy empty par
647 paragraphs().clear();
651 FileName const name = FileName::tempName("Buffer_readString");
652 switch (readFile(lex, name, true)) {
656 // We need to call lyx2lyx, so write the input to a file
657 ofstream os(name.toFilesystemEncoding().c_str());
660 return readFile(name);
670 bool Buffer::readFile(FileName const & filename)
672 FileName fname(filename);
674 // remove dummy empty par
675 paragraphs().clear();
678 if (readFile(lex, fname) != success)
685 bool Buffer::isFullyLoaded() const
687 return d->file_fully_loaded;
691 void Buffer::setFullyLoaded(bool value)
693 d->file_fully_loaded = value;
697 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
700 LASSERT(!filename.empty(), /**/);
702 // the first (non-comment) token _must_ be...
703 if (!lex.checkFor("\\lyxformat")) {
704 Alert::error(_("Document format failure"),
705 bformat(_("%1$s is not a readable LyX document."),
706 from_utf8(filename.absFilename())));
712 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
713 // if present remove ".," from string.
714 size_t dot = tmp_format.find_first_of(".,");
715 //lyxerr << " dot found at " << dot << endl;
716 if (dot != string::npos)
717 tmp_format.erase(dot, 1);
718 int const file_format = convert<int>(tmp_format);
719 //lyxerr << "format: " << file_format << endl;
721 // save timestamp and checksum of the original disk file, making sure
722 // to not overwrite them with those of the file created in the tempdir
723 // when it has to be converted to the current format.
725 // Save the timestamp and checksum of disk file. If filename is an
726 // emergency file, save the timestamp and checksum of the original lyx file
727 // because isExternallyModified will check for this file. (BUG4193)
728 string diskfile = filename.absFilename();
729 if (suffixIs(diskfile, ".emergency"))
730 diskfile = diskfile.substr(0, diskfile.size() - 10);
731 saveCheckSum(FileName(diskfile));
734 if (file_format != LYX_FORMAT) {
737 // lyx2lyx would fail
740 FileName const tmpfile = FileName::tempName("Buffer_readFile");
741 if (tmpfile.empty()) {
742 Alert::error(_("Conversion failed"),
743 bformat(_("%1$s is from a different"
744 " version of LyX, but a temporary"
745 " file for converting it could"
747 from_utf8(filename.absFilename())));
750 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
751 if (lyx2lyx.empty()) {
752 Alert::error(_("Conversion script not found"),
753 bformat(_("%1$s is from a different"
754 " version of LyX, but the"
755 " conversion script lyx2lyx"
756 " could not be found."),
757 from_utf8(filename.absFilename())));
760 ostringstream command;
761 command << os::python()
762 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
763 << " -t " << convert<string>(LYX_FORMAT)
764 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
765 << ' ' << quoteName(filename.toFilesystemEncoding());
766 string const command_str = command.str();
768 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
770 cmd_ret const ret = runCommand(command_str);
771 if (ret.first != 0) {
772 Alert::error(_("Conversion script failed"),
773 bformat(_("%1$s is from a different version"
774 " of LyX, but the lyx2lyx script"
775 " failed to convert it."),
776 from_utf8(filename.absFilename())));
779 bool const ret = readFile(tmpfile);
780 // Do stuff with tmpfile name and buffer name here.
781 return ret ? success : failure;
786 if (readDocument(lex)) {
787 Alert::error(_("Document format failure"),
788 bformat(_("%1$s ended unexpectedly, which means"
789 " that it is probably corrupted."),
790 from_utf8(filename.absFilename())));
793 d->file_fully_loaded = true;
798 // Should probably be moved to somewhere else: BufferView? LyXView?
799 bool Buffer::save() const
801 // We don't need autosaves in the immediate future. (Asger)
802 resetAutosaveTimers();
804 string const encodedFilename = d->filename.toFilesystemEncoding();
807 bool madeBackup = false;
809 // make a backup if the file already exists
810 if (lyxrc.make_backup && fileName().exists()) {
811 backupName = FileName(absFileName() + '~');
812 if (!lyxrc.backupdir_path.empty()) {
813 string const mangledName =
814 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
815 backupName = FileName(addName(lyxrc.backupdir_path,
818 if (fileName().copyTo(backupName)) {
821 Alert::error(_("Backup failure"),
822 bformat(_("Cannot create backup file %1$s.\n"
823 "Please check whether the directory exists and is writeable."),
824 from_utf8(backupName.absFilename())));
825 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
829 // ask if the disk file has been externally modified (use checksum method)
830 if (fileName().exists() && isExternallyModified(checksum_method)) {
831 docstring const file = makeDisplayPath(absFileName(), 20);
832 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
833 "you want to overwrite this file?"), file);
834 int const ret = Alert::prompt(_("Overwrite modified file?"),
835 text, 1, 1, _("&Overwrite"), _("&Cancel"));
840 if (writeFile(d->filename)) {
844 // Saving failed, so backup is not backup
846 backupName.moveTo(d->filename);
852 bool Buffer::writeFile(FileName const & fname) const
854 if (d->read_only && fname == d->filename)
859 docstring const str = bformat(_("Saving document %1$s..."),
860 makeDisplayPath(fname.absFilename()));
863 if (params().compressed) {
864 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
865 retval = ofs && write(ofs);
867 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
868 retval = ofs && write(ofs);
872 message(str + _(" could not write file!"));
876 removeAutosaveFile(d->filename.absFilename());
878 saveCheckSum(d->filename);
879 message(str + _(" done."));
885 bool Buffer::write(ostream & ofs) const
888 // Use the standard "C" locale for file output.
889 ofs.imbue(locale::classic());
892 // The top of the file should not be written by params().
894 // write out a comment in the top of the file
895 ofs << "#LyX " << lyx_version
896 << " created this file. For more info see http://www.lyx.org/\n"
897 << "\\lyxformat " << LYX_FORMAT << "\n"
898 << "\\begin_document\n";
900 /// For each author, set 'used' to true if there is a change
901 /// by this author in the document; otherwise set it to 'false'.
902 AuthorList::Authors::const_iterator a_it = params().authors().begin();
903 AuthorList::Authors::const_iterator a_end = params().authors().end();
904 for (; a_it != a_end; ++a_it)
905 a_it->second.setUsed(false);
907 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
908 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
909 for ( ; it != end; ++it)
910 it->checkAuthors(params().authors());
912 // now write out the buffer parameters.
913 ofs << "\\begin_header\n";
914 params().writeFile(ofs);
915 ofs << "\\end_header\n";
918 ofs << "\n\\begin_body\n";
919 text().write(*this, ofs);
920 ofs << "\n\\end_body\n";
922 // Write marker that shows file is complete
923 ofs << "\\end_document" << endl;
925 // Shouldn't really be needed....
928 // how to check if close went ok?
929 // Following is an attempt... (BE 20001011)
931 // good() returns false if any error occured, including some
933 // bad() returns true if something bad happened in the buffer,
934 // which should include file system full errors.
939 lyxerr << "File was not closed properly." << endl;
946 bool Buffer::makeLaTeXFile(FileName const & fname,
947 string const & original_path,
948 OutputParams const & runparams,
949 bool output_preamble, bool output_body) const
951 string const encoding = runparams.encoding->iconvName();
952 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
955 try { ofs.reset(encoding); }
956 catch (iconv_codecvt_facet_exception & e) {
957 lyxerr << "Caught iconv exception: " << e.what() << endl;
958 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
959 "verify that the support software for your encoding (%1$s) is "
960 "properly installed"), from_ascii(encoding)));
963 if (!openFileWrite(ofs, fname))
966 //TexStream ts(ofs.rdbuf(), &texrow());
967 ErrorList & errorList = d->errorLists["Export"];
969 bool failed_export = false;
972 writeLaTeXSource(ofs, original_path,
973 runparams, output_preamble, output_body);
975 catch (EncodingException & e) {
976 odocstringstream ods;
977 ods.put(e.failed_char);
979 oss << "0x" << hex << e.failed_char << dec;
980 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
981 " (code point %2$s)"),
982 ods.str(), from_utf8(oss.str()));
983 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
984 "representable in the chosen encoding.\n"
985 "Changing the document encoding to utf8 could help."),
986 e.par_id, e.pos, e.pos + 1));
987 failed_export = true;
989 catch (iconv_codecvt_facet_exception & e) {
990 errorList.push_back(ErrorItem(_("iconv conversion failed"),
991 _(e.what()), -1, 0, 0));
992 failed_export = true;
994 catch (exception const & e) {
995 errorList.push_back(ErrorItem(_("conversion failed"),
996 _(e.what()), -1, 0, 0));
997 failed_export = true;
1000 lyxerr << "Caught some really weird exception..." << endl;
1006 failed_export = true;
1007 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1011 return !failed_export;
1015 void Buffer::writeLaTeXSource(odocstream & os,
1016 string const & original_path,
1017 OutputParams const & runparams_in,
1018 bool const output_preamble, bool const output_body) const
1020 // The child documents, if any, shall be already loaded at this point.
1022 OutputParams runparams = runparams_in;
1024 // validate the buffer.
1025 LYXERR(Debug::LATEX, " Validating buffer...");
1026 LaTeXFeatures features(*this, params(), runparams);
1028 LYXERR(Debug::LATEX, " Buffer validation done.");
1030 // The starting paragraph of the coming rows is the
1031 // first paragraph of the document. (Asger)
1032 if (output_preamble && runparams.nice) {
1033 os << "%% LyX " << lyx_version << " created this file. "
1034 "For more info, see http://www.lyx.org/.\n"
1035 "%% Do not edit unless you really know what "
1037 d->texrow.newline();
1038 d->texrow.newline();
1040 LYXERR(Debug::INFO, "lyx document header finished");
1042 // Don't move this behind the parent_buffer=0 code below,
1043 // because then the macros will not get the right "redefinition"
1044 // flag as they don't see the parent macros which are output before.
1047 // fold macros if possible, still with parent buffer as the
1048 // macros will be put in the prefix anyway.
1049 updateMacroInstances();
1051 // There are a few differences between nice LaTeX and usual files:
1052 // usual is \batchmode and has a
1053 // special input@path to allow the including of figures
1054 // with either \input or \includegraphics (what figinsets do).
1055 // input@path is set when the actual parameter
1056 // original_path is set. This is done for usual tex-file, but not
1057 // for nice-latex-file. (Matthias 250696)
1058 // Note that input@path is only needed for something the user does
1059 // in the preamble, included .tex files or ERT, files included by
1060 // LyX work without it.
1061 if (output_preamble) {
1062 if (!runparams.nice) {
1063 // code for usual, NOT nice-latex-file
1064 os << "\\batchmode\n"; // changed
1065 // from \nonstopmode
1066 d->texrow.newline();
1068 if (!original_path.empty()) {
1070 // We don't know the encoding of inputpath
1071 docstring const inputpath = from_utf8(latex_path(original_path));
1072 os << "\\makeatletter\n"
1073 << "\\def\\input@path{{"
1074 << inputpath << "/}}\n"
1075 << "\\makeatother\n";
1076 d->texrow.newline();
1077 d->texrow.newline();
1078 d->texrow.newline();
1081 // get parent macros (if this buffer has a parent) which will be
1082 // written at the document begin further down.
1083 MacroSet parentMacros;
1084 listParentMacros(parentMacros, features);
1086 // Write the preamble
1087 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1093 os << "\\begin{document}\n";
1094 d->texrow.newline();
1096 // output the parent macros
1097 MacroSet::iterator it = parentMacros.begin();
1098 MacroSet::iterator end = parentMacros.end();
1099 for (; it != end; ++it)
1100 (*it)->write(os, true);
1101 } // output_preamble
1103 d->texrow.start(paragraphs().begin()->id(), 0);
1105 LYXERR(Debug::INFO, "preamble finished, now the body.");
1107 // if we are doing a real file with body, even if this is the
1108 // child of some other buffer, let's cut the link here.
1109 // This happens for example if only a child document is printed.
1110 Buffer const * save_parent = 0;
1111 if (output_preamble) {
1112 save_parent = d->parent_buffer;
1113 d->parent_buffer = 0;
1117 latexParagraphs(*this, text(), os, d->texrow, runparams);
1119 // Restore the parenthood if needed
1120 if (output_preamble)
1121 d->parent_buffer = save_parent;
1123 // add this just in case after all the paragraphs
1125 d->texrow.newline();
1127 if (output_preamble) {
1128 os << "\\end{document}\n";
1129 d->texrow.newline();
1130 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1132 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1134 runparams_in.encoding = runparams.encoding;
1136 // Just to be sure. (Asger)
1137 d->texrow.newline();
1139 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1140 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1144 bool Buffer::isLatex() const
1146 return params().documentClass().outputType() == LATEX;
1150 bool Buffer::isLiterate() const
1152 return params().documentClass().outputType() == LITERATE;
1156 bool Buffer::isDocBook() const
1158 return params().documentClass().outputType() == DOCBOOK;
1162 void Buffer::makeDocBookFile(FileName const & fname,
1163 OutputParams const & runparams,
1164 bool const body_only) const
1166 LYXERR(Debug::LATEX, "makeDocBookFile...");
1169 if (!openFileWrite(ofs, fname))
1172 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1176 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1180 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1181 OutputParams const & runparams,
1182 bool const only_body) const
1184 LaTeXFeatures features(*this, params(), runparams);
1189 DocumentClass const & tclass = params().documentClass();
1190 string const top_element = tclass.latexname();
1193 if (runparams.flavor == OutputParams::XML)
1194 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1197 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1200 if (! tclass.class_header().empty())
1201 os << from_ascii(tclass.class_header());
1202 else if (runparams.flavor == OutputParams::XML)
1203 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1204 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1206 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1208 docstring preamble = from_utf8(params().preamble);
1209 if (runparams.flavor != OutputParams::XML ) {
1210 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1211 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1212 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1213 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1216 string const name = runparams.nice
1217 ? changeExtension(absFileName(), ".sgml") : fname;
1218 preamble += features.getIncludedFiles(name);
1219 preamble += features.getLyXSGMLEntities();
1221 if (!preamble.empty()) {
1222 os << "\n [ " << preamble << " ]";
1227 string top = top_element;
1229 if (runparams.flavor == OutputParams::XML)
1230 top += params().language->code();
1232 top += params().language->code().substr(0,2);
1235 if (!params().options.empty()) {
1237 top += params().options;
1240 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1241 << " file was created by LyX " << lyx_version
1242 << "\n See http://www.lyx.org/ for more information -->\n";
1244 params().documentClass().counters().reset();
1248 sgml::openTag(os, top);
1250 docbookParagraphs(paragraphs(), *this, os, runparams);
1251 sgml::closeTag(os, top_element);
1255 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1256 // Other flags: -wall -v0 -x
1257 int Buffer::runChktex()
1261 // get LaTeX-Filename
1262 FileName const path(temppath());
1263 string const name = addName(path.absFilename(), latexName());
1264 string const org_path = filePath();
1266 PathChanger p(path); // path to LaTeX file
1267 message(_("Running chktex..."));
1269 // Generate the LaTeX file if neccessary
1270 OutputParams runparams(¶ms().encoding());
1271 runparams.flavor = OutputParams::LATEX;
1272 runparams.nice = false;
1273 makeLaTeXFile(FileName(name), org_path, runparams);
1276 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1277 int const res = chktex.run(terr); // run chktex
1280 Alert::error(_("chktex failure"),
1281 _("Could not run chktex successfully."));
1282 } else if (res > 0) {
1283 ErrorList & errlist = d->errorLists["ChkTeX"];
1285 bufferErrors(terr, errlist);
1296 void Buffer::validate(LaTeXFeatures & features) const
1298 params().validate(features);
1302 for_each(paragraphs().begin(), paragraphs().end(),
1303 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1305 if (lyxerr.debugging(Debug::LATEX)) {
1306 features.showStruct();
1311 void Buffer::getLabelList(vector<docstring> & list) const
1313 // If this is a child document, use the parent's list instead.
1314 if (d->parent_buffer) {
1315 d->parent_buffer->getLabelList(list);
1320 Toc & toc = d->toc_backend.toc("label");
1321 TocIterator toc_it = toc.begin();
1322 TocIterator end = toc.end();
1323 for (; toc_it != end; ++toc_it) {
1324 if (toc_it->depth() == 0)
1325 list.push_back(toc_it->str());
1330 void Buffer::updateBibfilesCache() const
1332 // If this is a child document, use the parent's cache instead.
1333 if (d->parent_buffer) {
1334 d->parent_buffer->updateBibfilesCache();
1338 d->bibfilesCache_.clear();
1339 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1340 if (it->lyxCode() == BIBTEX_CODE) {
1341 InsetBibtex const & inset =
1342 static_cast<InsetBibtex const &>(*it);
1343 support::FileNameList const bibfiles = inset.getBibFiles();
1344 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1347 } else if (it->lyxCode() == INCLUDE_CODE) {
1348 InsetInclude & inset =
1349 static_cast<InsetInclude &>(*it);
1350 inset.updateBibfilesCache();
1351 support::FileNameList const & bibfiles =
1352 inset.getBibfilesCache(*this);
1353 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1358 // the bibinfo cache is now invalid
1359 d->bibinfoCacheValid_ = false;
1363 void Buffer::invalidateBibinfoCache()
1365 d->bibinfoCacheValid_ = false;
1369 support::FileNameList const & Buffer::getBibfilesCache() const
1371 // If this is a child document, use the parent's cache instead.
1372 if (d->parent_buffer)
1373 return d->parent_buffer->getBibfilesCache();
1375 // We update the cache when first used instead of at loading time.
1376 if (d->bibfilesCache_.empty())
1377 const_cast<Buffer *>(this)->updateBibfilesCache();
1379 return d->bibfilesCache_;
1383 BiblioInfo const & Buffer::masterBibInfo() const
1385 // if this is a child document and the parent is already loaded
1386 // use the parent's list instead [ale990412]
1387 Buffer const * const tmp = masterBuffer();
1390 return tmp->masterBibInfo();
1391 return localBibInfo();
1395 BiblioInfo const & Buffer::localBibInfo() const
1397 if (d->bibinfoCacheValid_) {
1398 support::FileNameList const & bibfilesCache = getBibfilesCache();
1399 // compare the cached timestamps with the actual ones.
1400 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1401 support::FileNameList::const_iterator en = bibfilesCache.end();
1402 for (; ei != en; ++ ei) {
1403 time_t lastw = ei->lastModified();
1404 if (lastw != d->bibfileStatus_[*ei]) {
1405 d->bibinfoCacheValid_ = false;
1406 d->bibfileStatus_[*ei] = lastw;
1412 if (!d->bibinfoCacheValid_) {
1413 d->bibinfo_.clear();
1414 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1415 it->fillWithBibKeys(d->bibinfo_, it);
1416 d->bibinfoCacheValid_ = true;
1422 bool Buffer::isDepClean(string const & name) const
1424 DepClean::const_iterator const it = d->dep_clean.find(name);
1425 if (it == d->dep_clean.end())
1431 void Buffer::markDepClean(string const & name)
1433 d->dep_clean[name] = true;
1437 bool Buffer::dispatch(string const & command, bool * result)
1439 return dispatch(lyxaction.lookupFunc(command), result);
1443 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1445 bool dispatched = true;
1447 switch (func.action) {
1448 case LFUN_BUFFER_EXPORT: {
1449 bool const tmp = doExport(to_utf8(func.argument()), false);
1455 case LFUN_BRANCH_ACTIVATE:
1456 case LFUN_BRANCH_DEACTIVATE: {
1457 BranchList & branchList = params().branchlist();
1458 docstring const branchName = func.argument();
1459 Branch * branch = branchList.find(branchName);
1461 LYXERR0("Branch " << branchName << " does not exist.");
1463 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1475 void Buffer::changeLanguage(Language const * from, Language const * to)
1477 LASSERT(from, /**/);
1480 for_each(par_iterator_begin(),
1482 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1486 bool Buffer::isMultiLingual() const
1488 ParConstIterator end = par_iterator_end();
1489 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1490 if (it->isMultiLingual(params()))
1497 DocIterator Buffer::getParFromID(int const id) const
1500 // John says this is called with id == -1 from undo
1501 lyxerr << "getParFromID(), id: " << id << endl;
1502 return doc_iterator_end(inset());
1505 for (DocIterator it = doc_iterator_begin(inset()); !it.atEnd(); it.forwardPar())
1506 if (it.paragraph().id() == id)
1509 return doc_iterator_end(inset());
1513 bool Buffer::hasParWithID(int const id) const
1515 return !getParFromID(id).atEnd();
1519 ParIterator Buffer::par_iterator_begin()
1521 return ParIterator(doc_iterator_begin(inset()));
1525 ParIterator Buffer::par_iterator_end()
1527 return ParIterator(doc_iterator_end(inset()));
1531 ParConstIterator Buffer::par_iterator_begin() const
1533 return lyx::par_const_iterator_begin(inset());
1537 ParConstIterator Buffer::par_iterator_end() const
1539 return lyx::par_const_iterator_end(inset());
1543 Language const * Buffer::language() const
1545 return params().language;
1549 docstring const Buffer::B_(string const & l10n) const
1551 return params().B_(l10n);
1555 bool Buffer::isClean() const
1557 return d->lyx_clean;
1561 bool Buffer::isBakClean() const
1563 return d->bak_clean;
1567 bool Buffer::isExternallyModified(CheckMethod method) const
1569 LASSERT(d->filename.exists(), /**/);
1570 // if method == timestamp, check timestamp before checksum
1571 return (method == checksum_method
1572 || d->timestamp_ != d->filename.lastModified())
1573 && d->checksum_ != d->filename.checksum();
1577 void Buffer::saveCheckSum(FileName const & file) const
1579 if (file.exists()) {
1580 d->timestamp_ = file.lastModified();
1581 d->checksum_ = file.checksum();
1583 // in the case of save to a new file.
1590 void Buffer::markClean() const
1592 if (!d->lyx_clean) {
1593 d->lyx_clean = true;
1596 // if the .lyx file has been saved, we don't need an
1598 d->bak_clean = true;
1602 void Buffer::markBakClean() const
1604 d->bak_clean = true;
1608 void Buffer::setUnnamed(bool flag)
1614 bool Buffer::isUnnamed() const
1620 // FIXME: this function should be moved to buffer_pimpl.C
1621 void Buffer::markDirty()
1624 d->lyx_clean = false;
1627 d->bak_clean = false;
1629 DepClean::iterator it = d->dep_clean.begin();
1630 DepClean::const_iterator const end = d->dep_clean.end();
1632 for (; it != end; ++it)
1637 FileName Buffer::fileName() const
1643 string Buffer::absFileName() const
1645 return d->filename.absFilename();
1649 string Buffer::filePath() const
1651 return d->filename.onlyPath().absFilename() + "/";
1655 bool Buffer::isReadonly() const
1657 return d->read_only;
1661 void Buffer::setParent(Buffer const * buffer)
1663 // Avoids recursive include.
1664 d->parent_buffer = buffer == this ? 0 : buffer;
1669 Buffer const * Buffer::parent()
1671 return d->parent_buffer;
1675 Buffer const * Buffer::masterBuffer() const
1677 if (!d->parent_buffer)
1680 return d->parent_buffer->masterBuffer();
1684 bool Buffer::isChild(Buffer * child) const
1686 return d->children_positions.find(child) != d->children_positions.end();
1690 template<typename M>
1691 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
1696 typename M::iterator it = m.lower_bound(x);
1697 if (it == m.begin())
1705 MacroData const * Buffer::getBufferMacro(docstring const & name,
1706 DocIterator const & pos) const
1708 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
1710 // if paragraphs have no macro context set, pos will be empty
1714 // we haven't found anything yet
1715 DocIterator bestPos = par_iterator_begin();
1716 MacroData const * bestData = 0;
1718 // find macro definitions for name
1719 Impl::NamePositionScopeMacroMap::iterator nameIt
1720 = d->macros.find(name);
1721 if (nameIt != d->macros.end()) {
1722 // find last definition in front of pos or at pos itself
1723 Impl::PositionScopeMacroMap::const_iterator it
1724 = greatest_below(nameIt->second, pos);
1725 if (it != nameIt->second.end()) {
1727 // scope ends behind pos?
1728 if (pos < it->second.first) {
1729 // Looks good, remember this. If there
1730 // is no external macro behind this,
1731 // we found the right one already.
1732 bestPos = it->first;
1733 bestData = &it->second.second;
1737 // try previous macro if there is one
1738 if (it == nameIt->second.begin())
1745 // find macros in included files
1746 Impl::PositionScopeBufferMap::const_iterator it
1747 = greatest_below(d->position_to_children, pos);
1748 if (it == d->position_to_children.end())
1749 // no children before
1753 // do we know something better (i.e. later) already?
1754 if (it->first < bestPos )
1757 // scope ends behind pos?
1758 if (pos < it->second.first) {
1759 // look for macro in external file
1760 d->macro_lock = true;
1761 MacroData const * data
1762 = it->second.second->getMacro(name, false);
1763 d->macro_lock = false;
1765 bestPos = it->first;
1771 // try previous file if there is one
1772 if (it == d->position_to_children.begin())
1777 // return the best macro we have found
1782 MacroData const * Buffer::getMacro(docstring const & name,
1783 DocIterator const & pos, bool global) const
1788 // query buffer macros
1789 MacroData const * data = getBufferMacro(name, pos);
1793 // If there is a master buffer, query that
1794 if (d->parent_buffer) {
1795 d->macro_lock = true;
1796 MacroData const * macro = d->parent_buffer->getMacro(
1797 name, *this, false);
1798 d->macro_lock = false;
1804 data = MacroTable::globalMacros().get(name);
1813 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
1815 // set scope end behind the last paragraph
1816 DocIterator scope = par_iterator_begin();
1817 scope.pit() = scope.lastpit() + 1;
1819 return getMacro(name, scope, global);
1823 MacroData const * Buffer::getMacro(docstring const & name,
1824 Buffer const & child, bool global) const
1826 // look where the child buffer is included first
1827 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
1828 if (it == d->children_positions.end())
1831 // check for macros at the inclusion position
1832 return getMacro(name, it->second, global);
1836 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
1838 pit_type lastpit = it.lastpit();
1840 // look for macros in each paragraph
1841 while (it.pit() <= lastpit) {
1842 Paragraph & par = it.paragraph();
1844 // iterate over the insets of the current paragraph
1845 InsetList const & insets = par.insetList();
1846 InsetList::const_iterator iit = insets.begin();
1847 InsetList::const_iterator end = insets.end();
1848 for (; iit != end; ++iit) {
1849 it.pos() = iit->pos;
1851 // is it a nested text inset?
1852 if (iit->inset->asInsetText()) {
1853 // Inset needs its own scope?
1854 InsetText const * itext
1855 = iit->inset->asInsetText();
1856 bool newScope = itext->isMacroScope();
1858 // scope which ends just behind the inset
1859 DocIterator insetScope = it;
1862 // collect macros in inset
1863 it.push_back(CursorSlice(*iit->inset));
1864 updateMacros(it, newScope ? insetScope : scope);
1869 // is it an external file?
1870 if (iit->inset->lyxCode() == INCLUDE_CODE) {
1871 // get buffer of external file
1872 InsetCommand const & inset
1873 = static_cast<InsetCommand const &>(*iit->inset);
1874 InsetCommandParams const & ip = inset.params();
1875 d->macro_lock = true;
1876 Buffer * child = loadIfNeeded(*this, ip);
1877 d->macro_lock = false;
1881 // register its position, but only when it is
1882 // included first in the buffer
1883 if (d->children_positions.find(child)
1884 == d->children_positions.end())
1885 d->children_positions[child] = it;
1887 // register child with its scope
1888 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
1892 if (iit->inset->lyxCode() != MATHMACRO_CODE)
1896 MathMacroTemplate & macroTemplate
1897 = static_cast<MathMacroTemplate &>(*iit->inset);
1898 MacroContext mc(*this, it);
1899 macroTemplate.updateToContext(mc);
1902 bool valid = macroTemplate.validMacro();
1903 // FIXME: Should be fixNameAndCheckIfValid() in fact,
1904 // then the BufferView's cursor will be invalid in
1905 // some cases which leads to crashes.
1910 d->macros[macroTemplate.name()][it] =
1911 Impl::ScopeMacro(scope, MacroData(*this, it));
1921 void Buffer::updateMacros() const
1926 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
1928 // start with empty table
1930 d->children_positions.clear();
1931 d->position_to_children.clear();
1933 // Iterate over buffer, starting with first paragraph
1934 // The scope must be bigger than any lookup DocIterator
1935 // later. For the global lookup, lastpit+1 is used, hence
1936 // we use lastpit+2 here.
1937 DocIterator it = par_iterator_begin();
1938 DocIterator outerScope = it;
1939 outerScope.pit() = outerScope.lastpit() + 2;
1940 updateMacros(it, outerScope);
1944 void Buffer::updateMacroInstances() const
1946 LYXERR(Debug::MACROS, "updateMacroInstances for "
1947 << d->filename.onlyFileName());
1948 DocIterator it = doc_iterator_begin(inset());
1949 DocIterator end = doc_iterator_end(inset());
1950 for (; it != end; it.forwardPos()) {
1951 // look for MathData cells in InsetMathNest insets
1952 Inset * inset = it.nextInset();
1956 InsetMath * minset = inset->asInsetMath();
1960 // update macro in all cells of the InsetMathNest
1961 DocIterator::idx_type n = minset->nargs();
1962 MacroContext mc = MacroContext(*this, it);
1963 for (DocIterator::idx_type i = 0; i < n; ++i) {
1964 MathData & data = minset->cell(i);
1965 data.updateMacros(0, mc);
1971 void Buffer::listMacroNames(MacroNameSet & macros) const
1976 d->macro_lock = true;
1978 // loop over macro names
1979 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
1980 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
1981 for (; nameIt != nameEnd; ++nameIt)
1982 macros.insert(nameIt->first);
1984 // loop over children
1985 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
1986 Impl::BufferPositionMap::iterator end = d->children_positions.end();
1987 for (; it != end; ++it)
1988 it->first->listMacroNames(macros);
1991 if (d->parent_buffer)
1992 d->parent_buffer->listMacroNames(macros);
1994 d->macro_lock = false;
1998 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2000 if (!d->parent_buffer)
2004 d->parent_buffer->listMacroNames(names);
2007 MacroNameSet::iterator it = names.begin();
2008 MacroNameSet::iterator end = names.end();
2009 for (; it != end; ++it) {
2011 MacroData const * data =
2012 d->parent_buffer->getMacro(*it, *this, false);
2014 macros.insert(data);
2016 // we cannot access the original MathMacroTemplate anymore
2017 // here to calls validate method. So we do its work here manually.
2018 // FIXME: somehow make the template accessible here.
2019 if (data->optionals() > 0)
2020 features.require("xargs");
2026 Buffer::References & Buffer::references(docstring const & label)
2028 if (d->parent_buffer)
2029 return const_cast<Buffer *>(masterBuffer())->references(label);
2031 RefCache::iterator it = d->ref_cache_.find(label);
2032 if (it != d->ref_cache_.end())
2033 return it->second.second;
2035 static InsetLabel const * dummy_il = 0;
2036 static References const dummy_refs;
2037 it = d->ref_cache_.insert(
2038 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2039 return it->second.second;
2043 Buffer::References const & Buffer::references(docstring const & label) const
2045 return const_cast<Buffer *>(this)->references(label);
2049 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2051 masterBuffer()->d->ref_cache_[label].first = il;
2055 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2057 return masterBuffer()->d->ref_cache_[label].first;
2061 void Buffer::clearReferenceCache() const
2063 if (!d->parent_buffer)
2064 d->ref_cache_.clear();
2068 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2071 //FIXME: This does not work for child documents yet.
2072 LASSERT(code == CITE_CODE, /**/);
2073 // Check if the label 'from' appears more than once
2074 vector<docstring> labels;
2076 BiblioInfo const & keys = masterBibInfo();
2077 BiblioInfo::const_iterator bit = keys.begin();
2078 BiblioInfo::const_iterator bend = keys.end();
2080 for (; bit != bend; ++bit)
2082 labels.push_back(bit->first);
2085 if (count(labels.begin(), labels.end(), from) > 1)
2088 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2089 if (it->lyxCode() == code) {
2090 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2091 docstring const oldValue = inset.getParam(paramName);
2092 if (oldValue == from)
2093 inset.setParam(paramName, to);
2099 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2100 pit_type par_end, bool full_source)
2102 OutputParams runparams(¶ms().encoding());
2103 runparams.nice = true;
2104 runparams.flavor = OutputParams::LATEX;
2105 runparams.linelen = lyxrc.plaintext_linelen;
2106 // No side effect of file copying and image conversion
2107 runparams.dryrun = true;
2111 os << "% " << _("Preview source code") << "\n\n";
2112 d->texrow.newline();
2113 d->texrow.newline();
2115 writeLaTeXSource(os, filePath(), runparams, true, true);
2117 writeDocBookSource(os, absFileName(), runparams, false);
2119 runparams.par_begin = par_begin;
2120 runparams.par_end = par_end;
2121 if (par_begin + 1 == par_end) {
2123 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2127 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2128 convert<docstring>(par_begin),
2129 convert<docstring>(par_end - 1))
2132 d->texrow.newline();
2133 d->texrow.newline();
2134 // output paragraphs
2136 latexParagraphs(*this, text(), os, d->texrow, runparams);
2139 docbookParagraphs(paragraphs(), *this, os, runparams);
2144 ErrorList & Buffer::errorList(string const & type) const
2146 static ErrorList emptyErrorList;
2147 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2148 if (I == d->errorLists.end())
2149 return emptyErrorList;
2155 void Buffer::structureChanged() const
2158 gui_->structureChanged();
2162 void Buffer::errors(string const & err) const
2169 void Buffer::message(docstring const & msg) const
2176 void Buffer::setBusy(bool on) const
2183 void Buffer::setReadOnly(bool on) const
2186 d->wa_->setReadOnly(on);
2190 void Buffer::updateTitles() const
2193 d->wa_->updateTitles();
2197 void Buffer::resetAutosaveTimers() const
2200 gui_->resetAutosaveTimers();
2204 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2213 class AutoSaveBuffer : public ForkedProcess {
2216 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2217 : buffer_(buffer), fname_(fname) {}
2219 virtual boost::shared_ptr<ForkedProcess> clone() const
2221 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2226 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2227 from_utf8(fname_.absFilename())));
2228 return run(DontWait);
2232 virtual int generateChild();
2234 Buffer const & buffer_;
2239 int AutoSaveBuffer::generateChild()
2241 // tmp_ret will be located (usually) in /tmp
2242 // will that be a problem?
2243 // Note that this calls ForkedCalls::fork(), so it's
2244 // ok cross-platform.
2245 pid_t const pid = fork();
2246 // If you want to debug the autosave
2247 // you should set pid to -1, and comment out the fork.
2248 if (pid != 0 && pid != -1)
2251 // pid = -1 signifies that lyx was unable
2252 // to fork. But we will do the save
2254 bool failed = false;
2255 FileName const tmp_ret = FileName::tempName("lyxauto");
2256 if (!tmp_ret.empty()) {
2257 buffer_.writeFile(tmp_ret);
2258 // assume successful write of tmp_ret
2259 if (!tmp_ret.moveTo(fname_))
2265 // failed to write/rename tmp_ret so try writing direct
2266 if (!buffer_.writeFile(fname_)) {
2267 // It is dangerous to do this in the child,
2268 // but safe in the parent, so...
2269 if (pid == -1) // emit message signal.
2270 buffer_.message(_("Autosave failed!"));
2274 if (pid == 0) // we are the child so...
2283 // Perfect target for a thread...
2284 void Buffer::autoSave() const
2286 if (isBakClean() || isReadonly()) {
2287 // We don't save now, but we'll try again later
2288 resetAutosaveTimers();
2292 // emit message signal.
2293 message(_("Autosaving current document..."));
2295 // create autosave filename
2296 string fname = filePath();
2298 fname += d->filename.onlyFileName();
2301 AutoSaveBuffer autosave(*this, FileName(fname));
2305 resetAutosaveTimers();
2309 string Buffer::bufferFormat() const
2319 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2320 string & result_file) const
2322 string backend_format;
2323 OutputParams runparams(¶ms().encoding());
2324 runparams.flavor = OutputParams::LATEX;
2325 runparams.linelen = lyxrc.plaintext_linelen;
2326 vector<string> backs = backends();
2327 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2328 // Get shortest path to format
2329 Graph::EdgePath path;
2330 for (vector<string>::const_iterator it = backs.begin();
2331 it != backs.end(); ++it) {
2332 Graph::EdgePath p = theConverters().getPath(*it, format);
2333 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2334 backend_format = *it;
2339 runparams.flavor = theConverters().getFlavor(path);
2341 Alert::error(_("Couldn't export file"),
2342 bformat(_("No information for exporting the format %1$s."),
2343 formats.prettyName(format)));
2347 backend_format = format;
2348 // FIXME: Don't hardcode format names here, but use a flag
2349 if (backend_format == "pdflatex")
2350 runparams.flavor = OutputParams::PDFLATEX;
2353 string filename = latexName(false);
2354 filename = addName(temppath(), filename);
2355 filename = changeExtension(filename,
2356 formats.extension(backend_format));
2359 updateMacroInstances();
2361 // Plain text backend
2362 if (backend_format == "text")
2363 writePlaintextFile(*this, FileName(filename), runparams);
2365 else if (backend_format == "lyx")
2366 writeFile(FileName(filename));
2368 else if (isDocBook()) {
2369 runparams.nice = !put_in_tempdir;
2370 makeDocBookFile(FileName(filename), runparams);
2373 else if (backend_format == format) {
2374 runparams.nice = true;
2375 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2377 } else if (!lyxrc.tex_allows_spaces
2378 && contains(filePath(), ' ')) {
2379 Alert::error(_("File name error"),
2380 _("The directory path to the document cannot contain spaces."));
2383 runparams.nice = false;
2384 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2388 string const error_type = (format == "program")
2389 ? "Build" : bufferFormat();
2390 ErrorList & error_list = d->errorLists[error_type];
2391 string const ext = formats.extension(format);
2392 FileName const tmp_result_file(changeExtension(filename, ext));
2393 bool const success = theConverters().convert(this, FileName(filename),
2394 tmp_result_file, FileName(absFileName()), backend_format, format,
2396 // Emit the signal to show the error list.
2397 if (format != backend_format)
2402 if (put_in_tempdir) {
2403 result_file = tmp_result_file.absFilename();
2407 result_file = changeExtension(absFileName(), ext);
2408 // We need to copy referenced files (e. g. included graphics
2409 // if format == "dvi") to the result dir.
2410 vector<ExportedFile> const files =
2411 runparams.exportdata->externalFiles(format);
2412 string const dest = onlyPath(result_file);
2413 CopyStatus status = SUCCESS;
2414 for (vector<ExportedFile>::const_iterator it = files.begin();
2415 it != files.end() && status != CANCEL; ++it) {
2416 string const fmt = formats.getFormatFromFile(it->sourceName);
2417 status = copyFile(fmt, it->sourceName,
2418 makeAbsPath(it->exportName, dest),
2419 it->exportName, status == FORCE);
2421 if (status == CANCEL) {
2422 message(_("Document export cancelled."));
2423 } else if (tmp_result_file.exists()) {
2424 // Finally copy the main file
2425 status = copyFile(format, tmp_result_file,
2426 FileName(result_file), result_file,
2428 message(bformat(_("Document exported as %1$s "
2430 formats.prettyName(format),
2431 makeDisplayPath(result_file)));
2433 // This must be a dummy converter like fax (bug 1888)
2434 message(bformat(_("Document exported as %1$s"),
2435 formats.prettyName(format)));
2442 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2445 return doExport(format, put_in_tempdir, result_file);
2449 bool Buffer::preview(string const & format) const
2452 if (!doExport(format, true, result_file))
2454 return formats.view(*this, FileName(result_file), format);
2458 bool Buffer::isExportable(string const & format) const
2460 vector<string> backs = backends();
2461 for (vector<string>::const_iterator it = backs.begin();
2462 it != backs.end(); ++it)
2463 if (theConverters().isReachable(*it, format))
2469 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2471 vector<string> backs = backends();
2472 vector<Format const *> result =
2473 theConverters().getReachable(backs[0], only_viewable, true);
2474 for (vector<string>::const_iterator it = backs.begin() + 1;
2475 it != backs.end(); ++it) {
2476 vector<Format const *> r =
2477 theConverters().getReachable(*it, only_viewable, false);
2478 result.insert(result.end(), r.begin(), r.end());
2484 vector<string> Buffer::backends() const
2487 if (params().baseClass()->isTeXClassAvailable()) {
2488 v.push_back(bufferFormat());
2489 // FIXME: Don't hardcode format names here, but use a flag
2490 if (v.back() == "latex")
2491 v.push_back("pdflatex");
2493 v.push_back("text");
2499 bool Buffer::readFileHelper(FileName const & s)
2501 // File information about normal file
2503 docstring const file = makeDisplayPath(s.absFilename(), 50);
2504 docstring text = bformat(_("The specified document\n%1$s"
2505 "\ncould not be read."), file);
2506 Alert::error(_("Could not read document"), text);
2510 // Check if emergency save file exists and is newer.
2511 FileName const e(s.absFilename() + ".emergency");
2513 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2514 docstring const file = makeDisplayPath(s.absFilename(), 20);
2515 docstring const text =
2516 bformat(_("An emergency save of the document "
2518 "Recover emergency save?"), file);
2519 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2520 _("&Recover"), _("&Load Original"),
2524 // the file is not saved if we load the emergency file.
2534 // Now check if autosave file is newer.
2535 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2537 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2538 docstring const file = makeDisplayPath(s.absFilename(), 20);
2539 docstring const text =
2540 bformat(_("The backup of the document "
2541 "%1$s is newer.\n\nLoad the "
2542 "backup instead?"), file);
2543 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2544 _("&Load backup"), _("Load &original"),
2548 // the file is not saved if we load the autosave file.
2552 // Here we delete the autosave
2563 bool Buffer::loadLyXFile(FileName const & s)
2565 if (s.isReadableFile()) {
2566 if (readFileHelper(s)) {
2567 lyxvc().file_found_hook(s);
2568 if (!s.isWritable())
2573 docstring const file = makeDisplayPath(s.absFilename(), 20);
2574 // Here we probably should run
2575 if (LyXVC::file_not_found_hook(s)) {
2576 docstring const text =
2577 bformat(_("Do you want to retrieve the document"
2578 " %1$s from version control?"), file);
2579 int const ret = Alert::prompt(_("Retrieve from version control?"),
2580 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2583 // How can we know _how_ to do the checkout?
2584 // With the current VC support it has to be,
2585 // a RCS file since CVS do not have special ,v files.
2587 return loadLyXFile(s);
2595 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2597 TeXErrors::Errors::const_iterator cit = terr.begin();
2598 TeXErrors::Errors::const_iterator end = terr.end();
2600 for (; cit != end; ++cit) {
2603 int errorRow = cit->error_in_line;
2604 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2610 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2611 } while (found && id_start == id_end && pos_start == pos_end);
2613 errorList.push_back(ErrorItem(cit->error_desc,
2614 cit->error_text, id_start, pos_start, pos_end));