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"
28 #include "EmbeddedFiles.h"
30 #include "ErrorList.h"
33 #include "FuncRequest.h"
34 #include "InsetIterator.h"
35 #include "InsetList.h"
37 #include "LaTeXFeatures.h"
41 #include "LyXAction.h"
45 #include "output_docbook.h"
47 #include "output_latex.h"
48 #include "output_plaintext.h"
49 #include "paragraph_funcs.h"
50 #include "Paragraph.h"
51 #include "ParagraphParameters.h"
52 #include "ParIterator.h"
53 #include "PDFOptions.h"
57 #include "TexStream.h"
59 #include "TextClass.h"
60 #include "TocBackend.h"
62 #include "VCBackend.h"
66 #include "insets/InsetBibitem.h"
67 #include "insets/InsetBibtex.h"
68 #include "insets/InsetInclude.h"
69 #include "insets/InsetText.h"
71 #include "mathed/MacroTable.h"
72 #include "mathed/MathMacroTemplate.h"
73 #include "mathed/MathSupport.h"
75 #include "frontends/alert.h"
76 #include "frontends/Delegates.h"
77 #include "frontends/WorkAreaManager.h"
79 #include "graphics/Previews.h"
81 #include "support/convert.h"
82 #include "support/debug.h"
83 #include "support/ExceptionMessage.h"
84 #include "support/FileName.h"
85 #include "support/FileNameList.h"
86 #include "support/filetools.h"
87 #include "support/ForkedCalls.h"
88 #include "support/gettext.h"
89 #include "support/gzstream.h"
90 #include "support/lstrings.h"
91 #include "support/lyxalgo.h"
92 #include "support/os.h"
93 #include "support/Package.h"
94 #include "support/Path.h"
95 #include "support/textutils.h"
96 #include "support/types.h"
97 #include "support/FileZipListDir.h"
99 #include <boost/bind.hpp>
100 #include <boost/shared_ptr.hpp>
111 using namespace lyx::support;
115 namespace Alert = frontend::Alert;
116 namespace os = support::os;
120 int const LYX_FORMAT = 317; // Uwe Stöhr: float placement support for wrap floats
122 typedef map<string, bool> DepClean;
123 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
130 Impl(Buffer & parent, FileName const & file, bool readonly);
143 mutable TexRow texrow;
144 Buffer const * parent_buffer;
146 /// need to regenerate .tex?
150 mutable bool lyx_clean;
152 /// is autosave needed?
153 mutable bool bak_clean;
155 /// is this a unnamed file (New...)?
161 /// name of the file the buffer is associated with.
164 /** Set to true only when the file is fully loaded.
165 * Used to prevent the premature generation of previews
166 * and by the citation inset.
168 bool file_fully_loaded;
171 mutable TocBackend toc_backend;
174 typedef pair<DocIterator, MacroData> ScopeMacro;
175 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
176 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
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 BufferPositionMap children_positions;
185 PositionScopeBufferMap position_to_children;
187 /// Container for all sort of Buffer dependant errors.
188 map<string, ErrorList> errorLists;
190 /// all embedded files of this buffer
191 EmbeddedFileList embedded_files;
193 /// timestamp and checksum used to test if the file has been externally
194 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
196 unsigned long checksum_;
199 frontend::WorkAreaManager * wa_;
204 /// A cache for the bibfiles (including bibfiles of loaded child
205 /// documents), needed for appropriate update of natbib labels.
206 mutable EmbeddedFileList bibfilesCache_;
208 mutable RefCache ref_cache_;
210 /// our Text that should be wrapped in an InsetText
214 /// Creates the per buffer temporary directory
215 static FileName createBufferTmpDir()
218 // We are in our own directory. Why bother to mangle name?
219 // In fact I wrote this code to circumvent a problematic behaviour
220 // (bug?) of EMX mkstemp().
221 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
222 convert<string>(count++));
224 if (!tmpfl.createDirectory(0777)) {
225 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
226 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
227 from_utf8(tmpfl.absFilename())));
233 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
234 : parent_buffer(0), lyx_clean(true), bak_clean(true), unnamed(false),
235 read_only(readonly_), filename(file), file_fully_loaded(false),
236 toc_backend(&parent), macro_lock(false),
237 embedded_files(), timestamp_(0), checksum_(0), wa_(0),
240 temppath = createBufferTmpDir();
241 lyxvc.setBuffer(&parent);
243 wa_ = new frontend::WorkAreaManager;
247 Buffer::Buffer(string const & file, bool readonly)
248 : d(new Impl(*this, FileName(file), readonly)), gui_(0)
250 LYXERR(Debug::INFO, "Buffer::Buffer()");
252 d->inset.setBuffer(*this);
253 d->inset.initParagraphs(*this);
254 d->inset.setAutoBreakRows(true);
255 d->inset.getText(0)->setMacrocontextPosition(par_iterator_begin());
261 LYXERR(Debug::INFO, "Buffer::~Buffer()");
262 // here the buffer should take care that it is
263 // saved properly, before it goes into the void.
265 // GuiView already destroyed
268 // clear references to children in macro tables
269 d->children_positions.clear();
270 d->position_to_children.clear();
272 if (!d->temppath.destroyDirectory()) {
273 Alert::warning(_("Could not remove temporary directory"),
274 bformat(_("Could not remove the temporary directory %1$s"),
275 from_utf8(d->temppath.absFilename())));
278 // Remove any previewed LaTeX snippets associated with this buffer.
279 graphics::Previews::get().removeLoader(*this);
285 void Buffer::changed() const
292 frontend::WorkAreaManager & Buffer::workAreaManager() const
294 BOOST_ASSERT(d->wa_);
299 Text & Buffer::text() const
301 return const_cast<Text &>(d->inset.text_);
305 Inset & Buffer::inset() const
307 return const_cast<InsetText &>(d->inset);
311 BufferParams & Buffer::params()
317 BufferParams const & Buffer::params() const
323 ParagraphList & Buffer::paragraphs()
325 return text().paragraphs();
329 ParagraphList const & Buffer::paragraphs() const
331 return text().paragraphs();
335 LyXVC & Buffer::lyxvc()
341 LyXVC const & Buffer::lyxvc() const
347 string const Buffer::temppath() const
349 return d->temppath.absFilename();
353 TexRow const & Buffer::texrow() const
359 TocBackend & Buffer::tocBackend() const
361 return d->toc_backend;
365 EmbeddedFileList & Buffer::embeddedFiles()
367 return d->embedded_files;
371 EmbeddedFileList const & Buffer::embeddedFiles() const
373 return d->embedded_files;
377 bool Buffer::embedded() const
379 return params().embedded;
383 Undo & Buffer::undo()
389 string Buffer::latexName(bool const no_path) const
391 FileName latex_name = makeLatexName(d->filename);
392 return no_path ? latex_name.onlyFileName()
393 : latex_name.absFilename();
397 string Buffer::logName(LogType * type) const
399 string const filename = latexName(false);
401 if (filename.empty()) {
407 string const path = temppath();
409 FileName const fname(addName(temppath(),
410 onlyFilename(changeExtension(filename,
412 FileName const bname(
413 addName(path, onlyFilename(
414 changeExtension(filename,
415 formats.extension("literate") + ".out"))));
417 // If no Latex log or Build log is newer, show Build log
419 if (bname.exists() &&
420 (!fname.exists() || fname.lastModified() < bname.lastModified())) {
421 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
424 return bname.absFilename();
426 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
429 return fname.absFilename();
433 void Buffer::setReadonly(bool const flag)
435 if (d->read_only != flag) {
442 void Buffer::setFileName(string const & newfile)
444 d->filename = makeAbsPath(newfile);
445 setReadonly(d->filename.isReadOnly());
450 int Buffer::readHeader(Lexer & lex)
452 int unknown_tokens = 0;
454 int begin_header_line = -1;
456 // Initialize parameters that may be/go lacking in header:
457 params().branchlist().clear();
458 params().preamble.erase();
459 params().options.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().listings_params.clear();
472 params().clearLayoutModules();
473 params().pdfoptions().clear();
475 for (int i = 0; i < 4; ++i) {
476 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
477 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
480 ErrorList & errorList = d->errorLists["Parse"];
484 string const token = lex.getString();
489 if (token == "\\end_header")
493 if (token == "\\begin_header") {
494 begin_header_line = line;
498 LYXERR(Debug::PARSER, "Handling document header token: `"
501 string unknown = params().readToken(lex, token, d->filename.onlyPath());
502 if (!unknown.empty()) {
503 if (unknown[0] != '\\' && token == "\\textclass") {
504 Alert::warning(_("Unknown document class"),
505 bformat(_("Using the default document class, because the "
506 "class %1$s is unknown."), from_utf8(unknown)));
509 docstring const s = bformat(_("Unknown token: "
513 errorList.push_back(ErrorItem(_("Document header error"),
518 if (begin_header_line) {
519 docstring const s = _("\\begin_header is missing");
520 errorList.push_back(ErrorItem(_("Document header error"),
524 params().makeDocumentClass();
526 return unknown_tokens;
531 // changed to be public and have one parameter
532 // Returns false if "\end_document" is not read (Asger)
533 bool Buffer::readDocument(Lexer & lex)
535 ErrorList & errorList = d->errorLists["Parse"];
539 string const token = lex.getString();
540 if (token != "\\begin_document") {
541 docstring const s = _("\\begin_document is missing");
542 errorList.push_back(ErrorItem(_("Document header error"),
546 // we are reading in a brand new document
547 BOOST_ASSERT(paragraphs().empty());
551 if (params().outputChanges) {
552 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
553 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
554 LaTeXFeatures::isAvailable("xcolor");
556 if (!dvipost && !xcolorsoul) {
557 Alert::warning(_("Changes not shown in LaTeX output"),
558 _("Changes will not be highlighted in LaTeX output, "
559 "because neither dvipost nor xcolor/soul are installed.\n"
560 "Please install these packages or redefine "
561 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
562 } else if (!xcolorsoul) {
563 Alert::warning(_("Changes not shown in LaTeX output"),
564 _("Changes will not be highlighted in LaTeX output "
565 "when using pdflatex, because xcolor and soul are not installed.\n"
566 "Please install both packages or redefine "
567 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
572 bool const res = text().read(*this, lex, errorList, &(d->inset));
575 updateMacroInstances();
580 // needed to insert the selection
581 void Buffer::insertStringAsLines(ParagraphList & pars,
582 pit_type & pit, pos_type & pos,
583 Font const & fn, docstring const & str, bool autobreakrows)
587 // insert the string, don't insert doublespace
588 bool space_inserted = true;
589 for (docstring::const_iterator cit = str.begin();
590 cit != str.end(); ++cit) {
591 Paragraph & par = pars[pit];
593 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
594 breakParagraph(params(), pars, pit, pos,
595 par.layout().isEnvironment());
598 space_inserted = true;
602 // do not insert consecutive spaces if !free_spacing
603 } else if ((*cit == ' ' || *cit == '\t') &&
604 space_inserted && !par.isFreeSpacing()) {
606 } else if (*cit == '\t') {
607 if (!par.isFreeSpacing()) {
608 // tabs are like spaces here
609 par.insertChar(pos, ' ', font, params().trackChanges);
611 space_inserted = true;
613 const pos_type n = 8 - pos % 8;
614 for (pos_type i = 0; i < n; ++i) {
615 par.insertChar(pos, ' ', font, params().trackChanges);
618 space_inserted = true;
620 } else if (!isPrintable(*cit)) {
621 // Ignore unprintables
624 // just insert the character
625 par.insertChar(pos, *cit, font, params().trackChanges);
627 space_inserted = (*cit == ' ');
634 bool Buffer::readString(string const & s)
636 params().compressed = false;
638 // remove dummy empty par
639 paragraphs().clear();
643 FileName const name = FileName::tempName();
644 switch (readFile(lex, name, true)) {
648 // We need to call lyx2lyx, so write the input to a file
649 ofstream os(name.toFilesystemEncoding().c_str());
652 return readFile(name);
662 bool Buffer::readFile(FileName const & filename)
664 FileName fname(filename);
665 // Check if the file is compressed.
666 string format = filename.guessFormatFromContents();
667 if (format == "zip") {
668 // decompress to a temp directory
669 LYXERR(Debug::FILES, filename << " is in zip format. Unzip to " << temppath());
670 ::unzipToDir(filename.toFilesystemEncoding(), temppath());
672 FileName lyxfile(addName(temppath(), "content.lyx"));
673 // if both manifest.txt and file.lyx exist, this is am embedded file
674 if (lyxfile.exists()) {
675 // if in bundled format, save checksum of the compressed file, not content.lyx
676 saveCheckSum(filename);
677 params().embedded = true;
681 // The embedded lyx file can also be compressed, for backward compatibility
682 format = fname.guessFormatFromContents();
683 if (format == "gzip" || format == "zip" || format == "compress")
684 params().compressed = true;
686 // remove dummy empty par
687 paragraphs().clear();
690 if (readFile(lex, fname) != success)
697 bool Buffer::isFullyLoaded() const
699 return d->file_fully_loaded;
703 void Buffer::setFullyLoaded(bool value)
705 d->file_fully_loaded = value;
709 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
712 BOOST_ASSERT(!filename.empty());
715 Alert::error(_("Document could not be read"),
716 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
721 string const token = lex.getString();
724 Alert::error(_("Document could not be read"),
725 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
729 // the first token _must_ be...
730 if (token != "\\lyxformat") {
731 lyxerr << "Token: " << token << endl;
733 Alert::error(_("Document format failure"),
734 bformat(_("%1$s is not a LyX document."),
735 from_utf8(filename.absFilename())));
740 string tmp_format = lex.getString();
741 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
742 // if present remove ".," from string.
743 string::size_type dot = tmp_format.find_first_of(".,");
744 //lyxerr << " dot found at " << dot << endl;
745 if (dot != string::npos)
746 tmp_format.erase(dot, 1);
747 int const file_format = convert<int>(tmp_format);
748 //lyxerr << "format: " << file_format << endl;
750 // save timestamp and checksum of the original disk file, making sure
751 // to not overwrite them with those of the file created in the tempdir
752 // when it has to be converted to the current format.
754 // Save the timestamp and checksum of disk file. If filename is an
755 // emergency file, save the timestamp and checksum of the original lyx file
756 // because isExternallyModified will check for this file. (BUG4193)
757 string diskfile = filename.absFilename();
758 if (suffixIs(diskfile, ".emergency"))
759 diskfile = diskfile.substr(0, diskfile.size() - 10);
760 saveCheckSum(FileName(diskfile));
763 if (file_format != LYX_FORMAT) {
766 // lyx2lyx would fail
769 FileName const tmpfile = FileName::tempName();
770 if (tmpfile.empty()) {
771 Alert::error(_("Conversion failed"),
772 bformat(_("%1$s is from a different"
773 " version of LyX, but a temporary"
774 " file for converting it could"
776 from_utf8(filename.absFilename())));
779 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
780 if (lyx2lyx.empty()) {
781 Alert::error(_("Conversion script not found"),
782 bformat(_("%1$s is from a different"
783 " version of LyX, but the"
784 " conversion script lyx2lyx"
785 " could not be found."),
786 from_utf8(filename.absFilename())));
789 ostringstream command;
790 command << os::python()
791 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
792 << " -t " << convert<string>(LYX_FORMAT)
793 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
794 << ' ' << quoteName(filename.toFilesystemEncoding());
795 string const command_str = command.str();
797 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
799 cmd_ret const ret = runCommand(command_str);
800 if (ret.first != 0) {
801 Alert::error(_("Conversion script failed"),
802 bformat(_("%1$s is from a different version"
803 " of LyX, but the lyx2lyx script"
804 " failed to convert it."),
805 from_utf8(filename.absFilename())));
808 bool const ret = readFile(tmpfile);
809 // Do stuff with tmpfile name and buffer name here.
810 return ret ? success : failure;
815 if (readDocument(lex)) {
816 Alert::error(_("Document format failure"),
817 bformat(_("%1$s ended unexpectedly, which means"
818 " that it is probably corrupted."),
819 from_utf8(filename.absFilename())));
822 d->file_fully_loaded = true;
827 // Should probably be moved to somewhere else: BufferView? LyXView?
828 bool Buffer::save() const
830 // We don't need autosaves in the immediate future. (Asger)
831 resetAutosaveTimers();
833 string const encodedFilename = d->filename.toFilesystemEncoding();
836 bool madeBackup = false;
838 // make a backup if the file already exists
839 if (lyxrc.make_backup && fileName().exists()) {
840 backupName = FileName(absFileName() + '~');
841 if (!lyxrc.backupdir_path.empty()) {
842 string const mangledName =
843 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
844 backupName = FileName(addName(lyxrc.backupdir_path,
847 if (fileName().copyTo(backupName)) {
850 Alert::error(_("Backup failure"),
851 bformat(_("Cannot create backup file %1$s.\n"
852 "Please check whether the directory exists and is writeable."),
853 from_utf8(backupName.absFilename())));
854 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
858 // ask if the disk file has been externally modified (use checksum method)
859 if (fileName().exists() && isExternallyModified(checksum_method)) {
860 docstring const file = makeDisplayPath(absFileName(), 20);
861 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
862 "you want to overwrite this file?"), file);
863 int const ret = Alert::prompt(_("Overwrite modified file?"),
864 text, 1, 1, _("&Overwrite"), _("&Cancel"));
869 if (writeFile(d->filename)) {
873 // Saving failed, so backup is not backup
875 backupName.moveTo(d->filename);
881 bool Buffer::writeFile(FileName const & fname) const
883 if (d->read_only && fname == d->filename)
889 if (params().embedded)
890 // first write the .lyx file to the temporary directory
891 content = FileName(addName(temppath(), "content.lyx"));
895 docstring const str = bformat(_("Saving document %1$s..."),
896 makeDisplayPath(content.absFilename()));
899 if (params().compressed) {
900 gz::ogzstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
901 retval = ofs && write(ofs);
903 ofstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
904 retval = ofs && write(ofs);
908 message(str + _(" could not write file!."));
912 removeAutosaveFile(d->filename.absFilename());
914 if (params().embedded) {
915 message(str + _(" writing embedded files!."));
916 // if embedding is enabled, write file.lyx and all the embedded files
917 // to the zip file fname.
918 if (!d->embedded_files.writeFile(fname, *this)) {
919 message(str + _(" could not write embedded files!."));
923 saveCheckSum(d->filename);
924 message(str + _(" done."));
930 bool Buffer::write(ostream & ofs) const
933 // Use the standard "C" locale for file output.
934 ofs.imbue(locale::classic());
937 // The top of the file should not be written by params().
939 // write out a comment in the top of the file
940 ofs << "#LyX " << lyx_version
941 << " created this file. For more info see http://www.lyx.org/\n"
942 << "\\lyxformat " << LYX_FORMAT << "\n"
943 << "\\begin_document\n";
945 /// For each author, set 'used' to true if there is a change
946 /// by this author in the document; otherwise set it to 'false'.
947 AuthorList::Authors::const_iterator a_it = params().authors().begin();
948 AuthorList::Authors::const_iterator a_end = params().authors().end();
949 for (; a_it != a_end; ++a_it)
950 a_it->second.setUsed(false);
952 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
953 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
954 for ( ; it != end; ++it)
955 it->checkAuthors(params().authors());
957 // now write out the buffer parameters.
958 ofs << "\\begin_header\n";
959 params().writeFile(ofs);
960 ofs << "\\end_header\n";
963 ofs << "\n\\begin_body\n";
964 text().write(*this, ofs);
965 ofs << "\n\\end_body\n";
967 // Write marker that shows file is complete
968 ofs << "\\end_document" << endl;
970 // Shouldn't really be needed....
973 // how to check if close went ok?
974 // Following is an attempt... (BE 20001011)
976 // good() returns false if any error occured, including some
978 // bad() returns true if something bad happened in the buffer,
979 // which should include file system full errors.
984 lyxerr << "File was not closed properly." << endl;
991 bool Buffer::makeLaTeXFile(FileName const & fname,
992 string const & original_path,
993 OutputParams const & runparams,
994 bool output_preamble, bool output_body) const
996 string const encoding = runparams.encoding->iconvName();
997 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1000 try { ofs.reset(encoding); }
1001 catch (iconv_codecvt_facet_exception & e) {
1002 lyxerr << "Caught iconv exception: " << e.what() << endl;
1003 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1004 "verify that the support software for your encoding (%1$s) is "
1005 "properly installed"), from_ascii(encoding)));
1008 if (!openFileWrite(ofs, fname))
1011 //TexStream ts(ofs.rdbuf(), &texrow());
1012 ErrorList & errorList = d->errorLists["Export"];
1014 bool failed_export = false;
1017 writeLaTeXSource(ofs, original_path,
1018 runparams, output_preamble, output_body);
1020 catch (EncodingException & e) {
1021 odocstringstream ods;
1022 ods.put(e.failed_char);
1024 oss << "0x" << hex << e.failed_char << dec;
1025 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1026 " (code point %2$s)"),
1027 ods.str(), from_utf8(oss.str()));
1028 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1029 "representable in the chosen encoding.\n"
1030 "Changing the document encoding to utf8 could help."),
1031 e.par_id, e.pos, e.pos + 1));
1032 failed_export = true;
1034 catch (iconv_codecvt_facet_exception & e) {
1035 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1036 _(e.what()), -1, 0, 0));
1037 failed_export = true;
1039 catch (exception const & e) {
1040 errorList.push_back(ErrorItem(_("conversion failed"),
1041 _(e.what()), -1, 0, 0));
1042 failed_export = true;
1045 lyxerr << "Caught some really weird exception..." << endl;
1046 LyX::cref().exit(1);
1051 failed_export = true;
1052 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1056 return !failed_export;
1060 void Buffer::writeLaTeXSource(odocstream & os,
1061 string const & original_path,
1062 OutputParams const & runparams_in,
1063 bool const output_preamble, bool const output_body) const
1065 // The child documents, if any, shall be already loaded at this point.
1067 OutputParams runparams = runparams_in;
1069 // validate the buffer.
1070 LYXERR(Debug::LATEX, " Validating buffer...");
1071 LaTeXFeatures features(*this, params(), runparams);
1073 LYXERR(Debug::LATEX, " Buffer validation done.");
1075 // The starting paragraph of the coming rows is the
1076 // first paragraph of the document. (Asger)
1077 if (output_preamble && runparams.nice) {
1078 os << "%% LyX " << lyx_version << " created this file. "
1079 "For more info, see http://www.lyx.org/.\n"
1080 "%% Do not edit unless you really know what "
1082 d->texrow.newline();
1083 d->texrow.newline();
1085 LYXERR(Debug::INFO, "lyx document header finished");
1086 // There are a few differences between nice LaTeX and usual files:
1087 // usual is \batchmode and has a
1088 // special input@path to allow the including of figures
1089 // with either \input or \includegraphics (what figinsets do).
1090 // input@path is set when the actual parameter
1091 // original_path is set. This is done for usual tex-file, but not
1092 // for nice-latex-file. (Matthias 250696)
1093 // Note that input@path is only needed for something the user does
1094 // in the preamble, included .tex files or ERT, files included by
1095 // LyX work without it.
1096 if (output_preamble) {
1097 if (!runparams.nice) {
1098 // code for usual, NOT nice-latex-file
1099 os << "\\batchmode\n"; // changed
1100 // from \nonstopmode
1101 d->texrow.newline();
1103 if (!original_path.empty()) {
1105 // We don't know the encoding of inputpath
1106 docstring const inputpath = from_utf8(latex_path(original_path));
1107 os << "\\makeatletter\n"
1108 << "\\def\\input@path{{"
1109 << inputpath << "/}}\n"
1110 << "\\makeatother\n";
1111 d->texrow.newline();
1112 d->texrow.newline();
1113 d->texrow.newline();
1116 // Write the preamble
1117 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1123 os << "\\begin{document}\n";
1124 d->texrow.newline();
1125 } // output_preamble
1127 d->texrow.start(paragraphs().begin()->id(), 0);
1129 LYXERR(Debug::INFO, "preamble finished, now the body.");
1131 // Don't move this behind the parent_buffer=0 code below,
1132 // because then the macros will not get the right "redefinition"
1133 // flag as they don't see the parent macros which are output before.
1136 // fold macros if possible, still with parent buffer as the
1137 // macros will be put in the prefix anyway.
1138 updateMacroInstances();
1140 // if we are doing a real file with body, even if this is the
1141 // child of some other buffer, let's cut the link here.
1142 // This happens for example if only a child document is printed.
1143 Buffer const * save_parent = 0;
1144 if (output_preamble) {
1145 // output the macros visible for this buffer
1146 writeParentMacros(os);
1148 save_parent = d->parent_buffer;
1149 d->parent_buffer = 0;
1153 latexParagraphs(*this, text(), os, d->texrow, runparams);
1155 // Restore the parenthood if needed
1156 if (output_preamble) {
1157 d->parent_buffer = save_parent;
1159 // restore macros with correct parent buffer (especially
1160 // important for the redefinition flag which depends on the
1165 // add this just in case after all the paragraphs
1167 d->texrow.newline();
1169 if (output_preamble) {
1170 os << "\\end{document}\n";
1171 d->texrow.newline();
1172 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1174 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1176 runparams_in.encoding = runparams.encoding;
1178 // Just to be sure. (Asger)
1179 d->texrow.newline();
1181 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1182 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1186 bool Buffer::isLatex() const
1188 return params().documentClass().outputType() == LATEX;
1192 bool Buffer::isLiterate() const
1194 return params().documentClass().outputType() == LITERATE;
1198 bool Buffer::isDocBook() const
1200 return params().documentClass().outputType() == DOCBOOK;
1204 void Buffer::makeDocBookFile(FileName const & fname,
1205 OutputParams const & runparams,
1206 bool const body_only) const
1208 LYXERR(Debug::LATEX, "makeDocBookFile...");
1211 if (!openFileWrite(ofs, fname))
1214 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1218 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1222 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1223 OutputParams const & runparams,
1224 bool const only_body) const
1226 LaTeXFeatures features(*this, params(), runparams);
1231 DocumentClass const & tclass = params().documentClass();
1232 string const top_element = tclass.latexname();
1235 if (runparams.flavor == OutputParams::XML)
1236 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1239 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1242 if (! tclass.class_header().empty())
1243 os << from_ascii(tclass.class_header());
1244 else if (runparams.flavor == OutputParams::XML)
1245 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1246 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1248 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1250 docstring preamble = from_utf8(params().preamble);
1251 if (runparams.flavor != OutputParams::XML ) {
1252 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1253 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1254 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1255 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1258 string const name = runparams.nice
1259 ? changeExtension(absFileName(), ".sgml") : fname;
1260 preamble += features.getIncludedFiles(name);
1261 preamble += features.getLyXSGMLEntities();
1263 if (!preamble.empty()) {
1264 os << "\n [ " << preamble << " ]";
1269 string top = top_element;
1271 if (runparams.flavor == OutputParams::XML)
1272 top += params().language->code();
1274 top += params().language->code().substr(0,2);
1277 if (!params().options.empty()) {
1279 top += params().options;
1282 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1283 << " file was created by LyX " << lyx_version
1284 << "\n See http://www.lyx.org/ for more information -->\n";
1286 params().documentClass().counters().reset();
1290 sgml::openTag(os, top);
1292 docbookParagraphs(paragraphs(), *this, os, runparams);
1293 sgml::closeTag(os, top_element);
1297 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1298 // Other flags: -wall -v0 -x
1299 int Buffer::runChktex()
1303 // get LaTeX-Filename
1304 FileName const path(temppath());
1305 string const name = addName(path.absFilename(), latexName());
1306 string const org_path = filePath();
1308 PathChanger p(path); // path to LaTeX file
1309 message(_("Running chktex..."));
1311 // Generate the LaTeX file if neccessary
1312 OutputParams runparams(¶ms().encoding());
1313 runparams.flavor = OutputParams::LATEX;
1314 runparams.nice = false;
1315 makeLaTeXFile(FileName(name), org_path, runparams);
1318 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1319 int const res = chktex.run(terr); // run chktex
1322 Alert::error(_("chktex failure"),
1323 _("Could not run chktex successfully."));
1324 } else if (res > 0) {
1325 ErrorList & errlist = d->errorLists["ChkTeX"];
1327 bufferErrors(terr, errlist);
1338 void Buffer::validate(LaTeXFeatures & features) const
1340 params().validate(features);
1344 for_each(paragraphs().begin(), paragraphs().end(),
1345 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1347 if (lyxerr.debugging(Debug::LATEX)) {
1348 features.showStruct();
1353 void Buffer::getLabelList(vector<docstring> & list) const
1355 // If this is a child document, use the parent's list instead.
1356 if (d->parent_buffer) {
1357 d->parent_buffer->getLabelList(list);
1362 Toc & toc = d->toc_backend.toc("label");
1363 TocIterator toc_it = toc.begin();
1364 TocIterator end = toc.end();
1365 for (; toc_it != end; ++toc_it) {
1366 if (toc_it->depth() == 0)
1367 list.push_back(toc_it->str());
1372 void Buffer::updateBibfilesCache() const
1374 // If this is a child document, use the parent's cache instead.
1375 if (d->parent_buffer) {
1376 d->parent_buffer->updateBibfilesCache();
1380 d->bibfilesCache_.clear();
1381 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1382 if (it->lyxCode() == BIBTEX_CODE) {
1383 InsetBibtex const & inset =
1384 static_cast<InsetBibtex const &>(*it);
1385 EmbeddedFileList const bibfiles = inset.embeddedFiles();
1386 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1389 } else if (it->lyxCode() == INCLUDE_CODE) {
1390 InsetInclude & inset =
1391 static_cast<InsetInclude &>(*it);
1392 inset.updateBibfilesCache();
1393 EmbeddedFileList const & bibfiles =
1394 inset.getBibfilesCache(*this);
1395 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1403 EmbeddedFileList const & Buffer::getBibfilesCache() const
1405 // If this is a child document, use the parent's cache instead.
1406 if (d->parent_buffer)
1407 return d->parent_buffer->getBibfilesCache();
1409 // We update the cache when first used instead of at loading time.
1410 if (d->bibfilesCache_.empty())
1411 const_cast<Buffer *>(this)->updateBibfilesCache();
1413 return d->bibfilesCache_;
1417 bool Buffer::isDepClean(string const & name) const
1419 DepClean::const_iterator const it = d->dep_clean.find(name);
1420 if (it == d->dep_clean.end())
1426 void Buffer::markDepClean(string const & name)
1428 d->dep_clean[name] = true;
1432 bool Buffer::dispatch(string const & command, bool * result)
1434 return dispatch(lyxaction.lookupFunc(command), result);
1438 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1440 bool dispatched = true;
1442 switch (func.action) {
1443 case LFUN_BUFFER_EXPORT: {
1444 bool const tmp = doExport(to_utf8(func.argument()), false);
1457 void Buffer::changeLanguage(Language const * from, Language const * to)
1462 for_each(par_iterator_begin(),
1464 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1468 bool Buffer::isMultiLingual() const
1470 ParConstIterator end = par_iterator_end();
1471 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1472 if (it->isMultiLingual(params()))
1479 DocIterator Buffer::getParFromID(int const id) const
1482 // John says this is called with id == -1 from undo
1483 lyxerr << "getParFromID(), id: " << id << endl;
1484 return doc_iterator_end(inset());
1487 for (DocIterator it = doc_iterator_begin(inset()); !it.atEnd(); it.forwardPar())
1488 if (it.paragraph().id() == id)
1491 return doc_iterator_end(inset());
1495 bool Buffer::hasParWithID(int const id) const
1497 return !getParFromID(id).atEnd();
1501 ParIterator Buffer::par_iterator_begin()
1503 return ParIterator(doc_iterator_begin(inset()));
1507 ParIterator Buffer::par_iterator_end()
1509 return ParIterator(doc_iterator_end(inset()));
1513 ParConstIterator Buffer::par_iterator_begin() const
1515 return lyx::par_const_iterator_begin(inset());
1519 ParConstIterator Buffer::par_iterator_end() const
1521 return lyx::par_const_iterator_end(inset());
1525 Language const * Buffer::language() const
1527 return params().language;
1531 docstring const Buffer::B_(string const & l10n) const
1533 return params().B_(l10n);
1537 bool Buffer::isClean() const
1539 return d->lyx_clean;
1543 bool Buffer::isBakClean() const
1545 return d->bak_clean;
1549 bool Buffer::isExternallyModified(CheckMethod method) const
1551 BOOST_ASSERT(d->filename.exists());
1552 // if method == timestamp, check timestamp before checksum
1553 return (method == checksum_method
1554 || d->timestamp_ != d->filename.lastModified())
1555 && d->checksum_ != d->filename.checksum();
1559 void Buffer::saveCheckSum(FileName const & file) const
1561 if (file.exists()) {
1562 d->timestamp_ = file.lastModified();
1563 d->checksum_ = file.checksum();
1565 // in the case of save to a new file.
1572 void Buffer::markClean() const
1574 if (!d->lyx_clean) {
1575 d->lyx_clean = true;
1578 // if the .lyx file has been saved, we don't need an
1580 d->bak_clean = true;
1584 void Buffer::markBakClean() const
1586 d->bak_clean = true;
1590 void Buffer::setUnnamed(bool flag)
1596 bool Buffer::isUnnamed() const
1602 // FIXME: this function should be moved to buffer_pimpl.C
1603 void Buffer::markDirty()
1606 d->lyx_clean = false;
1609 d->bak_clean = false;
1611 DepClean::iterator it = d->dep_clean.begin();
1612 DepClean::const_iterator const end = d->dep_clean.end();
1614 for (; it != end; ++it)
1619 FileName Buffer::fileName() const
1625 string Buffer::absFileName() const
1627 return d->filename.absFilename();
1631 string Buffer::filePath() const
1633 return d->filename.onlyPath().absFilename() + "/";
1637 bool Buffer::isReadonly() const
1639 return d->read_only;
1643 void Buffer::setParent(Buffer const * buffer)
1645 // Avoids recursive include.
1646 d->parent_buffer = buffer == this ? 0 : buffer;
1651 Buffer const * Buffer::parent()
1653 return d->parent_buffer;
1657 Buffer const * Buffer::masterBuffer() const
1659 if (!d->parent_buffer)
1662 return d->parent_buffer->masterBuffer();
1666 template<typename M>
1667 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
1672 typename M::iterator it = m.lower_bound(x);
1673 if (it == m.begin())
1681 MacroData const * Buffer::getBufferMacro(docstring const & name,
1682 DocIterator const & pos) const
1684 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
1686 // if paragraphs have no macro context set, pos will be empty
1690 // we haven't found anything yet
1691 DocIterator bestPos = par_iterator_begin();
1692 MacroData const * bestData = 0;
1694 // find macro definitions for name
1695 Impl::NamePositionScopeMacroMap::iterator nameIt
1696 = d->macros.find(name);
1697 if (nameIt != d->macros.end()) {
1698 // find last definition in front of pos or at pos itself
1699 Impl::PositionScopeMacroMap::const_iterator it
1700 = greatest_below(nameIt->second, pos);
1701 if (it != nameIt->second.end()) {
1703 // scope ends behind pos?
1704 if (pos < it->second.first) {
1705 // Looks good, remember this. If there
1706 // is no external macro behind this,
1707 // we found the right one already.
1708 bestPos = it->first;
1709 bestData = &it->second.second;
1713 // try previous macro if there is one
1714 if (it == nameIt->second.begin())
1721 // find macros in included files
1722 Impl::PositionScopeBufferMap::const_iterator it
1723 = greatest_below(d->position_to_children, pos);
1724 if (it == d->position_to_children.end())
1725 // no children before
1729 // do we know something better (i.e. later) already?
1730 if (it->first < bestPos )
1733 // scope ends behind pos?
1734 if (pos < it->second.first) {
1735 // look for macro in external file
1736 d->macro_lock = true;
1737 MacroData const * data
1738 = it->second.second->getMacro(name, false);
1739 d->macro_lock = false;
1741 bestPos = it->first;
1747 // try previous file if there is one
1748 if (it == d->position_to_children.begin())
1753 // return the best macro we have found
1758 MacroData const * Buffer::getMacro(docstring const & name,
1759 DocIterator const & pos, bool global) const
1764 // query buffer macros
1765 MacroData const * data = getBufferMacro(name, pos);
1769 // If there is a master buffer, query that
1770 if (d->parent_buffer) {
1771 d->macro_lock = true;
1772 MacroData const * macro = d->parent_buffer->getMacro(
1773 name, *this, false);
1774 d->macro_lock = false;
1780 data = MacroTable::globalMacros().get(name);
1789 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
1791 // set scope end behind the last paragraph
1792 DocIterator scope = par_iterator_begin();
1793 scope.pit() = scope.lastpit() + 1;
1795 return getMacro(name, scope, global);
1799 MacroData const * Buffer::getMacro(docstring const & name,
1800 Buffer const & child, bool global) const
1802 // look where the child buffer is included first
1803 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
1804 if (it == d->children_positions.end())
1807 // check for macros at the inclusion position
1808 return getMacro(name, it->second, global);
1812 void Buffer::updateEnvironmentMacros(DocIterator & it, pit_type lastpit,
1813 DocIterator & scope) const
1815 Paragraph & par = it.paragraph();
1816 depth_type depth = par.params().depth();
1817 Length const & leftIndent = par.params().leftIndent();
1819 // look for macros in each paragraph
1820 while (it.pit() <= lastpit) {
1821 Paragraph & par = it.paragraph();
1824 if ((par.params().depth() > depth
1825 || par.params().leftIndent() != leftIndent)
1826 && par.layout().isEnvironment()) {
1827 updateBlockMacros(it, scope);
1831 // iterate over the insets of the current paragraph
1832 InsetList const & insets = par.insetList();
1833 InsetList::const_iterator iit = insets.begin();
1834 InsetList::const_iterator end = insets.end();
1835 for (; iit != end; ++iit) {
1836 it.pos() = iit->pos;
1838 // is it a nested text inset?
1839 if (iit->inset->asInsetText()) {
1840 // Inset needs its own scope?
1841 InsetText const * itext
1842 = iit->inset->asInsetText();
1843 bool newScope = itext->isMacroScope();
1845 // scope which ends just behind the inset
1846 DocIterator insetScope = it;
1849 // collect macros in inset
1850 it.push_back(CursorSlice(*iit->inset));
1851 updateInsetMacros(it, newScope ? insetScope : scope);
1856 // is it an external file?
1857 if (iit->inset->lyxCode() == INCLUDE_CODE) {
1858 // get buffer of external file
1859 InsetCommand const & inset
1860 = static_cast<InsetCommand const &>(*iit->inset);
1861 InsetCommandParams const & ip = inset.params();
1862 d->macro_lock = true;
1863 Buffer * child = loadIfNeeded(*this, ip);
1864 d->macro_lock = false;
1868 // register its position, but only when it is
1869 // included first in the buffer
1870 if (d->children_positions.find(child)
1871 == d->children_positions.end())
1872 d->children_positions[child] = it;
1874 // register child with its scope
1875 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
1879 if (iit->inset->lyxCode() != MATHMACRO_CODE)
1883 MathMacroTemplate & macroTemplate
1884 = static_cast<MathMacroTemplate &>(*iit->inset);
1885 MacroContext mc(*this, it);
1886 macroTemplate.updateToContext(mc);
1889 bool valid = macroTemplate.validMacro();
1890 // FIXME: Should be fixNameAndCheckIfValid() in fact,
1891 // then the BufferView's cursor will be invalid in
1892 // some cases which leads to crashes.
1897 d->macros[macroTemplate.name()][it] =
1898 Impl::ScopeMacro(scope, MacroData(*this, it));
1908 void Buffer::updateBlockMacros(DocIterator & it, DocIterator & scope) const
1910 Paragraph & par = it.paragraph();
1912 // set scope for macros in this paragraph:
1913 // * either the "old" outer scope
1914 // * or the scope ending after the environment
1915 if (par.layout().isEnvironment()) {
1916 // find end of environment block,
1917 DocIterator envEnd = it;
1918 pit_type n = it.lastpit() + 1;
1919 depth_type depth = par.params().depth();
1920 Length const & length = par.params().leftIndent();
1921 // looping through the paragraph, basically until
1922 // the layout changes or the depth gets smaller.
1923 // (the logic of output_latex.cpp's TeXEnvironment)
1926 if (envEnd.pit() == n)
1928 } while (par.layout() == envEnd.paragraph().layout()
1929 || depth < envEnd.paragraph().params().depth()
1930 || length != envEnd.paragraph().params().leftIndent());
1932 // collect macros from environment block
1933 updateEnvironmentMacros(it, envEnd.pit() - 1, envEnd);
1935 // collect macros from paragraph
1936 updateEnvironmentMacros(it, it.pit(), scope);
1941 void Buffer::updateInsetMacros(DocIterator & it, DocIterator & scope) const
1943 // look for macros in each paragraph
1944 pit_type n = it.lastpit() + 1;
1945 while (it.pit() < n)
1946 updateBlockMacros(it, scope);
1950 void Buffer::updateMacros() const
1955 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
1957 // start with empty table
1959 d->children_positions.clear();
1960 d->position_to_children.clear();
1962 // Iterate over buffer, starting with first paragraph
1963 // The scope must be bigger than any lookup DocIterator
1964 // later. For the global lookup, lastpit+1 is used, hence
1965 // we use lastpit+2 here.
1966 DocIterator it = par_iterator_begin();
1967 DocIterator outerScope = it;
1968 outerScope.pit() = outerScope.lastpit() + 2;
1969 updateInsetMacros(it, outerScope);
1973 void Buffer::updateMacroInstances() const
1975 LYXERR(Debug::MACROS, "updateMacroInstances for "
1976 << d->filename.onlyFileName());
1977 DocIterator it = doc_iterator_begin(inset());
1978 DocIterator end = doc_iterator_end(inset());
1979 for (; it != end; it.forwardPos()) {
1980 // look for MathData cells in InsetMathNest insets
1981 Inset * inset = it.nextInset();
1985 InsetMath * minset = inset->asInsetMath();
1989 // update macro in all cells of the InsetMathNest
1990 DocIterator::idx_type n = minset->nargs();
1991 MacroContext mc = MacroContext(*this, it);
1992 for (DocIterator::idx_type i = 0; i < n; ++i) {
1993 MathData & data = minset->cell(i);
1994 data.updateMacros(0, mc);
2000 void Buffer::listMacroNames(MacroNameSet & macros) const
2005 d->macro_lock = true;
2007 // loop over macro names
2008 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2009 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2010 for (; nameIt != nameEnd; ++nameIt)
2011 macros.insert(nameIt->first);
2013 // loop over children
2014 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2015 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2016 for (; it != end; ++it)
2017 it->first->listMacroNames(macros);
2020 if (d->parent_buffer)
2021 d->parent_buffer->listMacroNames(macros);
2023 d->macro_lock = false;
2027 void Buffer::writeParentMacros(odocstream & os) const
2029 if (!d->parent_buffer)
2032 // collect macro names
2034 d->parent_buffer->listMacroNames(names);
2036 // resolve and output them
2037 MacroNameSet::iterator it = names.begin();
2038 MacroNameSet::iterator end = names.end();
2039 for (; it != end; ++it) {
2041 MacroData const * data =
2042 d->parent_buffer->getMacro(*it, *this, false);
2044 data->write(os, true);
2049 Buffer::References & Buffer::references(docstring const & label)
2051 if (d->parent_buffer)
2052 return const_cast<Buffer *>(masterBuffer())->references(label);
2054 RefCache::iterator it = d->ref_cache_.find(label);
2055 if (it != d->ref_cache_.end())
2056 return it->second.second;
2058 static InsetLabel const * dummy_il = 0;
2059 static References const dummy_refs;
2060 it = d->ref_cache_.insert(
2061 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2062 return it->second.second;
2066 Buffer::References const & Buffer::references(docstring const & label) const
2068 return const_cast<Buffer *>(this)->references(label);
2072 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2074 masterBuffer()->d->ref_cache_[label].first = il;
2078 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2080 return masterBuffer()->d->ref_cache_[label].first;
2084 void Buffer::clearReferenceCache() const
2086 if (!d->parent_buffer)
2087 d->ref_cache_.clear();
2091 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2094 //FIXME: This does not work for child documents yet.
2095 BOOST_ASSERT(code == CITE_CODE);
2096 // Check if the label 'from' appears more than once
2097 vector<docstring> labels;
2100 keys.fillWithBibKeys(this);
2101 BiblioInfo::const_iterator bit = keys.begin();
2102 BiblioInfo::const_iterator bend = keys.end();
2104 for (; bit != bend; ++bit)
2106 labels.push_back(bit->first);
2109 if (count(labels.begin(), labels.end(), from) > 1)
2112 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2113 if (it->lyxCode() == code) {
2114 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2115 docstring const oldValue = inset.getParam(paramName);
2116 if (oldValue == from)
2117 inset.setParam(paramName, to);
2123 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2124 pit_type par_end, bool full_source)
2126 OutputParams runparams(¶ms().encoding());
2127 runparams.nice = true;
2128 runparams.flavor = OutputParams::LATEX;
2129 runparams.linelen = lyxrc.plaintext_linelen;
2130 // No side effect of file copying and image conversion
2131 runparams.dryrun = true;
2135 os << "% " << _("Preview source code") << "\n\n";
2136 d->texrow.newline();
2137 d->texrow.newline();
2139 writeLaTeXSource(os, filePath(), runparams, true, true);
2141 writeDocBookSource(os, absFileName(), runparams, false);
2143 runparams.par_begin = par_begin;
2144 runparams.par_end = par_end;
2145 if (par_begin + 1 == par_end) {
2147 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2151 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2152 convert<docstring>(par_begin),
2153 convert<docstring>(par_end - 1))
2156 d->texrow.newline();
2157 d->texrow.newline();
2158 // output paragraphs
2160 latexParagraphs(*this, text(), os, d->texrow, runparams);
2163 docbookParagraphs(paragraphs(), *this, os, runparams);
2168 ErrorList & Buffer::errorList(string const & type) const
2170 static ErrorList emptyErrorList;
2171 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2172 if (I == d->errorLists.end())
2173 return emptyErrorList;
2179 void Buffer::structureChanged() const
2182 gui_->structureChanged();
2186 void Buffer::errors(string const & err) const
2193 void Buffer::message(docstring const & msg) const
2200 void Buffer::setBusy(bool on) const
2207 void Buffer::setReadOnly(bool on) const
2210 d->wa_->setReadOnly(on);
2214 void Buffer::updateTitles() const
2217 d->wa_->updateTitles();
2221 void Buffer::resetAutosaveTimers() const
2224 gui_->resetAutosaveTimers();
2228 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2237 class AutoSaveBuffer : public ForkedProcess {
2240 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2241 : buffer_(buffer), fname_(fname) {}
2243 virtual boost::shared_ptr<ForkedProcess> clone() const
2245 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2250 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2251 from_utf8(fname_.absFilename())));
2252 return run(DontWait);
2256 virtual int generateChild();
2258 Buffer const & buffer_;
2263 int AutoSaveBuffer::generateChild()
2265 // tmp_ret will be located (usually) in /tmp
2266 // will that be a problem?
2267 // Note that this calls ForkedCalls::fork(), so it's
2268 // ok cross-platform.
2269 pid_t const pid = fork();
2270 // If you want to debug the autosave
2271 // you should set pid to -1, and comment out the fork.
2272 if (pid != 0 && pid != -1)
2275 // pid = -1 signifies that lyx was unable
2276 // to fork. But we will do the save
2278 bool failed = false;
2279 FileName const tmp_ret = FileName::tempName("lyxauto");
2280 if (!tmp_ret.empty()) {
2281 buffer_.writeFile(tmp_ret);
2282 // assume successful write of tmp_ret
2283 if (!tmp_ret.moveTo(fname_))
2289 // failed to write/rename tmp_ret so try writing direct
2290 if (!buffer_.writeFile(fname_)) {
2291 // It is dangerous to do this in the child,
2292 // but safe in the parent, so...
2293 if (pid == -1) // emit message signal.
2294 buffer_.message(_("Autosave failed!"));
2298 if (pid == 0) // we are the child so...
2307 // Perfect target for a thread...
2308 void Buffer::autoSave() const
2310 if (isBakClean() || isReadonly()) {
2311 // We don't save now, but we'll try again later
2312 resetAutosaveTimers();
2316 // emit message signal.
2317 message(_("Autosaving current document..."));
2319 // create autosave filename
2320 string fname = filePath();
2322 fname += d->filename.onlyFileName();
2325 AutoSaveBuffer autosave(*this, FileName(fname));
2329 resetAutosaveTimers();
2333 string Buffer::bufferFormat() const
2343 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2344 string & result_file) const
2346 string backend_format;
2347 OutputParams runparams(¶ms().encoding());
2348 runparams.flavor = OutputParams::LATEX;
2349 runparams.linelen = lyxrc.plaintext_linelen;
2350 vector<string> backs = backends();
2351 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2352 // Get shortest path to format
2353 Graph::EdgePath path;
2354 for (vector<string>::const_iterator it = backs.begin();
2355 it != backs.end(); ++it) {
2356 Graph::EdgePath p = theConverters().getPath(*it, format);
2357 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2358 backend_format = *it;
2363 runparams.flavor = theConverters().getFlavor(path);
2365 Alert::error(_("Couldn't export file"),
2366 bformat(_("No information for exporting the format %1$s."),
2367 formats.prettyName(format)));
2371 backend_format = format;
2372 // FIXME: Don't hardcode format names here, but use a flag
2373 if (backend_format == "pdflatex")
2374 runparams.flavor = OutputParams::PDFLATEX;
2377 string filename = latexName(false);
2378 filename = addName(temppath(), filename);
2379 filename = changeExtension(filename,
2380 formats.extension(backend_format));
2383 updateMacroInstances();
2385 // Plain text backend
2386 if (backend_format == "text")
2387 writePlaintextFile(*this, FileName(filename), runparams);
2389 else if (backend_format == "lyx")
2390 writeFile(FileName(filename));
2392 else if (isDocBook()) {
2393 runparams.nice = !put_in_tempdir;
2394 makeDocBookFile(FileName(filename), runparams);
2397 else if (backend_format == format) {
2398 runparams.nice = true;
2399 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2401 } else if (!lyxrc.tex_allows_spaces
2402 && contains(filePath(), ' ')) {
2403 Alert::error(_("File name error"),
2404 _("The directory path to the document cannot contain spaces."));
2407 runparams.nice = false;
2408 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2412 string const error_type = (format == "program")
2413 ? "Build" : bufferFormat();
2414 string const ext = formats.extension(format);
2415 FileName const tmp_result_file(changeExtension(filename, ext));
2416 bool const success = theConverters().convert(this, FileName(filename),
2417 tmp_result_file, FileName(absFileName()), backend_format, format,
2418 errorList(error_type));
2419 // Emit the signal to show the error list.
2420 if (format != backend_format)
2425 if (put_in_tempdir) {
2426 result_file = tmp_result_file.absFilename();
2430 result_file = changeExtension(absFileName(), ext);
2431 // We need to copy referenced files (e. g. included graphics
2432 // if format == "dvi") to the result dir.
2433 vector<ExportedFile> const files =
2434 runparams.exportdata->externalFiles(format);
2435 string const dest = onlyPath(result_file);
2436 CopyStatus status = SUCCESS;
2437 for (vector<ExportedFile>::const_iterator it = files.begin();
2438 it != files.end() && status != CANCEL; ++it) {
2439 string const fmt = formats.getFormatFromFile(it->sourceName);
2440 status = copyFile(fmt, it->sourceName,
2441 makeAbsPath(it->exportName, dest),
2442 it->exportName, status == FORCE);
2444 if (status == CANCEL) {
2445 message(_("Document export cancelled."));
2446 } else if (tmp_result_file.exists()) {
2447 // Finally copy the main file
2448 status = copyFile(format, tmp_result_file,
2449 FileName(result_file), result_file,
2451 message(bformat(_("Document exported as %1$s "
2453 formats.prettyName(format),
2454 makeDisplayPath(result_file)));
2456 // This must be a dummy converter like fax (bug 1888)
2457 message(bformat(_("Document exported as %1$s"),
2458 formats.prettyName(format)));
2465 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2468 return doExport(format, put_in_tempdir, result_file);
2472 bool Buffer::preview(string const & format) const
2475 if (!doExport(format, true, result_file))
2477 return formats.view(*this, FileName(result_file), format);
2481 bool Buffer::isExportable(string const & format) const
2483 vector<string> backs = backends();
2484 for (vector<string>::const_iterator it = backs.begin();
2485 it != backs.end(); ++it)
2486 if (theConverters().isReachable(*it, format))
2492 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2494 vector<string> backs = backends();
2495 vector<Format const *> result =
2496 theConverters().getReachable(backs[0], only_viewable, true);
2497 for (vector<string>::const_iterator it = backs.begin() + 1;
2498 it != backs.end(); ++it) {
2499 vector<Format const *> r =
2500 theConverters().getReachable(*it, only_viewable, false);
2501 result.insert(result.end(), r.begin(), r.end());
2507 vector<string> Buffer::backends() const
2510 if (params().baseClass()->isTeXClassAvailable()) {
2511 v.push_back(bufferFormat());
2512 // FIXME: Don't hardcode format names here, but use a flag
2513 if (v.back() == "latex")
2514 v.push_back("pdflatex");
2516 v.push_back("text");
2522 bool Buffer::readFileHelper(FileName const & s)
2524 // File information about normal file
2526 docstring const file = makeDisplayPath(s.absFilename(), 50);
2527 docstring text = bformat(_("The specified document\n%1$s"
2528 "\ncould not be read."), file);
2529 Alert::error(_("Could not read document"), text);
2533 // Check if emergency save file exists and is newer.
2534 FileName const e(s.absFilename() + ".emergency");
2536 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2537 docstring const file = makeDisplayPath(s.absFilename(), 20);
2538 docstring const text =
2539 bformat(_("An emergency save of the document "
2541 "Recover emergency save?"), file);
2542 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2543 _("&Recover"), _("&Load Original"),
2547 // the file is not saved if we load the emergency file.
2557 // Now check if autosave file is newer.
2558 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2560 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2561 docstring const file = makeDisplayPath(s.absFilename(), 20);
2562 docstring const text =
2563 bformat(_("The backup of the document "
2564 "%1$s is newer.\n\nLoad the "
2565 "backup instead?"), file);
2566 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2567 _("&Load backup"), _("Load &original"),
2571 // the file is not saved if we load the autosave file.
2575 // Here we delete the autosave
2586 bool Buffer::loadLyXFile(FileName const & s)
2588 if (s.isReadableFile()) {
2589 if (readFileHelper(s)) {
2590 lyxvc().file_found_hook(s);
2591 if (!s.isWritable())
2596 docstring const file = makeDisplayPath(s.absFilename(), 20);
2597 // Here we probably should run
2598 if (LyXVC::file_not_found_hook(s)) {
2599 docstring const text =
2600 bformat(_("Do you want to retrieve the document"
2601 " %1$s from version control?"), file);
2602 int const ret = Alert::prompt(_("Retrieve from version control?"),
2603 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2606 // How can we know _how_ to do the checkout?
2607 // With the current VC support it has to be,
2608 // a RCS file since CVS do not have special ,v files.
2610 return loadLyXFile(s);
2618 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2620 TeXErrors::Errors::const_iterator cit = terr.begin();
2621 TeXErrors::Errors::const_iterator end = terr.end();
2623 for (; cit != end; ++cit) {
2626 int errorRow = cit->error_in_line;
2627 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2633 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2634 } while (found && id_start == id_end && pos_start == pos_end);
2636 errorList.push_back(ErrorItem(cit->error_desc,
2637 cit->error_text, id_start, pos_start, pos_end));