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 "BiblioInfo.h"
18 #include "BranchList.h"
19 #include "buffer_funcs.h"
20 #include "BufferList.h"
21 #include "BufferParams.h"
24 #include "Converter.h"
26 #include "DocIterator.h"
27 #include "EmbeddedFiles.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"
56 #include "TexStream.h"
57 #include "TextClassList.h"
59 #include "TocBackend.h"
61 #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/convert.h"
80 #include "support/debug.h"
81 #include "support/ExceptionMessage.h"
82 #include "support/FileName.h"
83 #include "support/FileNameList.h"
84 #include "support/filetools.h"
85 #include "support/ForkedCalls.h"
86 #include "support/gettext.h"
87 #include "support/gzstream.h"
88 #include "support/lstrings.h"
89 #include "support/lyxalgo.h"
90 #include "support/os.h"
91 #include "support/Package.h"
92 #include "support/Path.h"
93 #include "support/textutils.h"
94 #include "support/types.h"
95 #include "support/FileZipListDir.h"
97 #include <boost/bind.hpp>
98 #include <boost/shared_ptr.hpp>
107 using namespace lyx::support;
111 namespace Alert = frontend::Alert;
112 namespace os = support::os;
116 int const LYX_FORMAT = 315; // Richard Heck: column separation
121 typedef map<string, bool> DepClean;
126 Impl(Buffer & parent, FileName const & file, bool readonly);
139 mutable TexRow texrow;
140 Buffer const * parent_buffer;
142 /// need to regenerate .tex?
146 mutable bool lyx_clean;
148 /// is autosave needed?
149 mutable bool bak_clean;
151 /// is this a unnamed file (New...)?
157 /// name of the file the buffer is associated with.
160 /** Set to true only when the file is fully loaded.
161 * Used to prevent the premature generation of previews
162 * and by the citation inset.
164 bool file_fully_loaded;
166 /// our Text that should be wrapped in an InsetText
170 mutable TocBackend toc_backend;
173 typedef pair<DocIterator, MacroData> ScopeMacro;
174 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
175 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
176 NamePositionScopeMacroMap macros;
179 /// positions of child buffers in the buffer
180 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
181 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
182 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
183 BufferPositionMap children_positions;
184 PositionScopeBufferMap position_to_children;
186 /// Container for all sort of Buffer dependant errors.
187 map<string, ErrorList> errorLists;
189 /// all embedded files of this buffer
190 EmbeddedFileList embedded_files;
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 EmbeddedFileList bibfilesCache_;
208 /// Creates the per buffer temporary directory
209 static FileName createBufferTmpDir()
212 // We are in our own directory. Why bother to mangle name?
213 // In fact I wrote this code to circumvent a problematic behaviour
214 // (bug?) of EMX mkstemp().
215 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
216 convert<string>(count++));
218 if (!tmpfl.createDirectory(0777)) {
219 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
220 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
221 from_utf8(tmpfl.absFilename())));
227 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
228 : parent_buffer(0), lyx_clean(true), bak_clean(true), unnamed(false),
229 read_only(readonly_), filename(file), file_fully_loaded(false),
230 inset(params), toc_backend(&parent), macro_lock(false),
231 embedded_files(), timestamp_(0), checksum_(0), wa_(0),
234 temppath = createBufferTmpDir();
235 inset.setAutoBreakRows(true);
236 lyxvc.setBuffer(&parent);
238 wa_ = new frontend::WorkAreaManager;
242 Buffer::Buffer(string const & file, bool readonly)
243 : d(new Impl(*this, FileName(file), readonly)), gui_(0)
245 LYXERR(Debug::INFO, "Buffer::Buffer()");
247 d->inset.getText(0)->setMacrocontextPosition(par_iterator_begin());
253 LYXERR(Debug::INFO, "Buffer::~Buffer()");
254 // here the buffer should take care that it is
255 // saved properly, before it goes into the void.
257 // GuiView already destroyed
260 Buffer const * master = masterBuffer();
261 if (master != this && use_gui) {
262 // We are closing buf which was a child document so we
263 // must update the labels and section numbering of its master
265 updateLabels(*master);
266 master->updateMacros();
269 resetChildDocuments(false);
271 if (!d->temppath.destroyDirectory()) {
272 Alert::warning(_("Could not remove temporary directory"),
273 bformat(_("Could not remove the temporary directory %1$s"),
274 from_utf8(d->temppath.absFilename())));
277 // Remove any previewed LaTeX snippets associated with this buffer.
278 graphics::Previews::get().removeLoader(*this);
284 void Buffer::changed() const
291 frontend::WorkAreaManager & Buffer::workAreaManager() const
293 BOOST_ASSERT(d->wa_);
298 Text & Buffer::text() const
300 return const_cast<Text &>(d->inset.text_);
304 Inset & Buffer::inset() const
306 return const_cast<InsetText &>(d->inset);
310 BufferParams & Buffer::params()
316 BufferParams const & Buffer::params() const
322 ParagraphList & Buffer::paragraphs()
324 return text().paragraphs();
328 ParagraphList const & Buffer::paragraphs() const
330 return text().paragraphs();
334 LyXVC & Buffer::lyxvc()
340 LyXVC const & Buffer::lyxvc() const
346 string const Buffer::temppath() const
348 return d->temppath.absFilename();
352 TexRow const & Buffer::texrow() const
358 TocBackend & Buffer::tocBackend() const
360 return d->toc_backend;
364 EmbeddedFileList & Buffer::embeddedFiles()
366 return d->embedded_files;
370 EmbeddedFileList const & Buffer::embeddedFiles() const
372 return d->embedded_files;
376 bool Buffer::embedded() const
378 return params().embedded;
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().float_placement.erase();
460 params().paperwidth.erase();
461 params().paperheight.erase();
462 params().leftmargin.erase();
463 params().rightmargin.erase();
464 params().topmargin.erase();
465 params().bottommargin.erase();
466 params().headheight.erase();
467 params().headsep.erase();
468 params().footskip.erase();
469 params().columnsep.erase();
470 params().listings_params.clear();
471 params().clearLayoutModules();
472 params().pdfoptions().clear();
474 for (int i = 0; i < 4; ++i) {
475 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
476 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
479 ErrorList & errorList = d->errorLists["Parse"];
483 string const token = lex.getString();
488 if (token == "\\end_header")
492 if (token == "\\begin_header") {
493 begin_header_line = line;
497 LYXERR(Debug::PARSER, "Handling document header token: `"
500 string unknown = params().readToken(lex, token, d->filename.onlyPath());
501 if (!unknown.empty()) {
502 if (unknown[0] != '\\' && token == "\\textclass") {
503 Alert::warning(_("Unknown document class"),
504 bformat(_("Using the default document class, because the "
505 "class %1$s is unknown."), from_utf8(unknown)));
508 docstring const s = bformat(_("Unknown token: "
512 errorList.push_back(ErrorItem(_("Document header error"),
517 if (begin_header_line) {
518 docstring const s = _("\\begin_header is missing");
519 errorList.push_back(ErrorItem(_("Document header error"),
523 params().makeTextClass();
525 return unknown_tokens;
530 // changed to be public and have one parameter
531 // Returns false if "\end_document" is not read (Asger)
532 bool Buffer::readDocument(Lexer & lex)
534 ErrorList & errorList = d->errorLists["Parse"];
538 string const token = lex.getString();
539 if (token != "\\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 BOOST_ASSERT(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."));
571 bool const res = text().read(*this, lex, errorList, &(d->inset));
574 updateMacroInstances();
579 // needed to insert the selection
580 void Buffer::insertStringAsLines(ParagraphList & pars,
581 pit_type & pit, pos_type & pos,
582 Font const & fn, docstring const & str, bool autobreakrows)
586 // insert the string, don't insert doublespace
587 bool space_inserted = true;
588 for (docstring::const_iterator cit = str.begin();
589 cit != str.end(); ++cit) {
590 Paragraph & par = pars[pit];
592 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
593 breakParagraph(params(), pars, pit, pos,
594 par.layout()->isEnvironment());
597 space_inserted = true;
601 // do not insert consecutive spaces if !free_spacing
602 } else if ((*cit == ' ' || *cit == '\t') &&
603 space_inserted && !par.isFreeSpacing()) {
605 } else if (*cit == '\t') {
606 if (!par.isFreeSpacing()) {
607 // tabs are like spaces here
608 par.insertChar(pos, ' ', font, params().trackChanges);
610 space_inserted = true;
612 const pos_type n = 8 - pos % 8;
613 for (pos_type i = 0; i < n; ++i) {
614 par.insertChar(pos, ' ', font, params().trackChanges);
617 space_inserted = true;
619 } else if (!isPrintable(*cit)) {
620 // Ignore unprintables
623 // just insert the character
624 par.insertChar(pos, *cit, font, params().trackChanges);
626 space_inserted = (*cit == ' ');
633 bool Buffer::readString(string const & s)
635 params().compressed = false;
637 // remove dummy empty par
638 paragraphs().clear();
642 FileName const name = FileName::tempName();
643 switch (readFile(lex, name, true)) {
647 // We need to call lyx2lyx, so write the input to a file
648 ofstream os(name.toFilesystemEncoding().c_str());
651 return readFile(name);
661 bool Buffer::readFile(FileName const & filename)
663 FileName fname(filename);
664 // Check if the file is compressed.
665 string format = filename.guessFormatFromContents();
666 if (format == "zip") {
667 // decompress to a temp directory
668 LYXERR(Debug::FILES, filename << " is in zip format. Unzip to " << temppath());
669 ::unzipToDir(filename.toFilesystemEncoding(), temppath());
671 FileName lyxfile(addName(temppath(), "content.lyx"));
672 // if both manifest.txt and file.lyx exist, this is am embedded file
673 if (lyxfile.exists()) {
674 // if in bundled format, save checksum of the compressed file, not content.lyx
675 saveCheckSum(filename);
676 params().embedded = true;
680 // The embedded lyx file can also be compressed, for backward compatibility
681 format = fname.guessFormatFromContents();
682 if (format == "gzip" || format == "zip" || format == "compress")
683 params().compressed = true;
685 // remove dummy empty par
686 paragraphs().clear();
689 if (readFile(lex, fname) != success)
696 bool Buffer::isFullyLoaded() const
698 return d->file_fully_loaded;
702 void Buffer::setFullyLoaded(bool value)
704 d->file_fully_loaded = value;
708 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
711 BOOST_ASSERT(!filename.empty());
714 Alert::error(_("Document could not be read"),
715 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
720 string const token = lex.getString();
723 Alert::error(_("Document could not be read"),
724 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
728 // the first token _must_ be...
729 if (token != "\\lyxformat") {
730 lyxerr << "Token: " << token << endl;
732 Alert::error(_("Document format failure"),
733 bformat(_("%1$s is not a LyX document."),
734 from_utf8(filename.absFilename())));
739 string tmp_format = lex.getString();
740 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
741 // if present remove ".," from string.
742 string::size_type dot = tmp_format.find_first_of(".,");
743 //lyxerr << " dot found at " << dot << endl;
744 if (dot != string::npos)
745 tmp_format.erase(dot, 1);
746 int const file_format = convert<int>(tmp_format);
747 //lyxerr << "format: " << file_format << endl;
749 // save timestamp and checksum of the original disk file, making sure
750 // to not overwrite them with those of the file created in the tempdir
751 // when it has to be converted to the current format.
753 // Save the timestamp and checksum of disk file. If filename is an
754 // emergency file, save the timestamp and checksum of the original lyx file
755 // because isExternallyModified will check for this file. (BUG4193)
756 string diskfile = filename.absFilename();
757 if (suffixIs(diskfile, ".emergency"))
758 diskfile = diskfile.substr(0, diskfile.size() - 10);
759 saveCheckSum(FileName(diskfile));
762 if (file_format != LYX_FORMAT) {
765 // lyx2lyx would fail
768 FileName const tmpfile = FileName::tempName();
769 if (tmpfile.empty()) {
770 Alert::error(_("Conversion failed"),
771 bformat(_("%1$s is from a different"
772 " version of LyX, but a temporary"
773 " file for converting it could"
775 from_utf8(filename.absFilename())));
778 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
779 if (lyx2lyx.empty()) {
780 Alert::error(_("Conversion script not found"),
781 bformat(_("%1$s is from a different"
782 " version of LyX, but the"
783 " conversion script lyx2lyx"
784 " could not be found."),
785 from_utf8(filename.absFilename())));
788 ostringstream command;
789 command << os::python()
790 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
791 << " -t " << convert<string>(LYX_FORMAT)
792 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
793 << ' ' << quoteName(filename.toFilesystemEncoding());
794 string const command_str = command.str();
796 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
798 cmd_ret const ret = runCommand(command_str);
799 if (ret.first != 0) {
800 Alert::error(_("Conversion script failed"),
801 bformat(_("%1$s is from a different version"
802 " of LyX, but the lyx2lyx script"
803 " failed to convert it."),
804 from_utf8(filename.absFilename())));
807 bool const ret = readFile(tmpfile);
808 // Do stuff with tmpfile name and buffer name here.
809 return ret ? success : failure;
814 if (readDocument(lex)) {
815 Alert::error(_("Document format failure"),
816 bformat(_("%1$s ended unexpectedly, which means"
817 " that it is probably corrupted."),
818 from_utf8(filename.absFilename())));
821 d->file_fully_loaded = true;
826 // Should probably be moved to somewhere else: BufferView? LyXView?
827 bool Buffer::save() const
829 // We don't need autosaves in the immediate future. (Asger)
830 resetAutosaveTimers();
832 string const encodedFilename = d->filename.toFilesystemEncoding();
835 bool madeBackup = false;
837 // make a backup if the file already exists
838 if (lyxrc.make_backup && fileName().exists()) {
839 backupName = FileName(absFileName() + '~');
840 if (!lyxrc.backupdir_path.empty()) {
841 string const mangledName =
842 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
843 backupName = FileName(addName(lyxrc.backupdir_path,
846 if (fileName().copyTo(backupName)) {
849 Alert::error(_("Backup failure"),
850 bformat(_("Cannot create backup file %1$s.\n"
851 "Please check whether the directory exists and is writeable."),
852 from_utf8(backupName.absFilename())));
853 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
857 // ask if the disk file has been externally modified (use checksum method)
858 if (fileName().exists() && isExternallyModified(checksum_method)) {
859 docstring const file = makeDisplayPath(absFileName(), 20);
860 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
861 "you want to overwrite this file?"), file);
862 int const ret = Alert::prompt(_("Overwrite modified file?"),
863 text, 1, 1, _("&Overwrite"), _("&Cancel"));
868 if (writeFile(d->filename)) {
872 // Saving failed, so backup is not backup
874 backupName.moveTo(d->filename);
880 bool Buffer::writeFile(FileName const & fname) const
882 if (d->read_only && fname == d->filename)
888 if (params().embedded)
889 // first write the .lyx file to the temporary directory
890 content = FileName(addName(temppath(), "content.lyx"));
894 docstring const str = bformat(_("Saving document %1$s..."),
895 makeDisplayPath(content.absFilename()));
898 if (params().compressed) {
899 gz::ogzstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
900 retval = ofs && write(ofs);
902 ofstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
903 retval = ofs && write(ofs);
907 message(str + _(" could not write file!."));
911 removeAutosaveFile(d->filename.absFilename());
913 if (params().embedded) {
914 message(str + _(" writing embedded files!."));
915 // if embedding is enabled, write file.lyx and all the embedded files
916 // to the zip file fname.
917 if (!d->embedded_files.writeFile(fname, *this)) {
918 message(str + _(" could not write embedded files!."));
922 saveCheckSum(d->filename);
923 message(str + _(" done."));
929 bool Buffer::write(ostream & ofs) const
932 // Use the standard "C" locale for file output.
933 ofs.imbue(locale::classic());
936 // The top of the file should not be written by params().
938 // write out a comment in the top of the file
939 ofs << "#LyX " << lyx_version
940 << " created this file. For more info see http://www.lyx.org/\n"
941 << "\\lyxformat " << LYX_FORMAT << "\n"
942 << "\\begin_document\n";
944 /// For each author, set 'used' to true if there is a change
945 /// by this author in the document; otherwise set it to 'false'.
946 AuthorList::Authors::const_iterator a_it = params().authors().begin();
947 AuthorList::Authors::const_iterator a_end = params().authors().end();
948 for (; a_it != a_end; ++a_it)
949 a_it->second.setUsed(false);
951 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
952 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
953 for ( ; it != end; ++it)
954 it->checkAuthors(params().authors());
956 // now write out the buffer parameters.
957 ofs << "\\begin_header\n";
958 params().writeFile(ofs);
959 ofs << "\\end_header\n";
962 ofs << "\n\\begin_body\n";
963 text().write(*this, ofs);
964 ofs << "\n\\end_body\n";
966 // Write marker that shows file is complete
967 ofs << "\\end_document" << endl;
969 // Shouldn't really be needed....
972 // how to check if close went ok?
973 // Following is an attempt... (BE 20001011)
975 // good() returns false if any error occured, including some
977 // bad() returns true if something bad happened in the buffer,
978 // which should include file system full errors.
983 lyxerr << "File was not closed properly." << endl;
990 bool Buffer::makeLaTeXFile(FileName const & fname,
991 string const & original_path,
992 OutputParams const & runparams,
993 bool output_preamble, bool output_body) const
995 string const encoding = runparams.encoding->iconvName();
996 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
999 try { ofs.reset(encoding); }
1000 catch (iconv_codecvt_facet_exception & e) {
1001 lyxerr << "Caught iconv exception: " << e.what() << endl;
1002 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1003 "verify that the support software for your encoding (%1$s) is "
1004 "properly installed"), from_ascii(encoding)));
1007 if (!openFileWrite(ofs, fname))
1010 //TexStream ts(ofs.rdbuf(), &texrow());
1011 ErrorList & errorList = d->errorLists["Export"];
1013 bool failed_export = false;
1016 writeLaTeXSource(ofs, original_path,
1017 runparams, output_preamble, output_body);
1019 catch (EncodingException & e) {
1020 odocstringstream ods;
1021 ods.put(e.failed_char);
1023 oss << "0x" << hex << e.failed_char << dec;
1024 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1025 " (code point %2$s)"),
1026 ods.str(), from_utf8(oss.str()));
1027 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1028 "representable in the chosen encoding.\n"
1029 "Changing the document encoding to utf8 could help."),
1030 e.par_id, e.pos, e.pos + 1));
1031 failed_export = true;
1033 catch (iconv_codecvt_facet_exception & e) {
1034 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1035 _(e.what()), -1, 0, 0));
1036 failed_export = true;
1038 catch (exception const & e) {
1039 errorList.push_back(ErrorItem(_("conversion failed"),
1040 _(e.what()), -1, 0, 0));
1041 failed_export = true;
1044 lyxerr << "Caught some really weird exception..." << endl;
1045 LyX::cref().exit(1);
1050 failed_export = true;
1051 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1055 return !failed_export;
1059 void Buffer::writeLaTeXSource(odocstream & os,
1060 string const & original_path,
1061 OutputParams const & runparams_in,
1062 bool const output_preamble, bool const output_body) const
1064 OutputParams runparams = runparams_in;
1066 // validate the buffer.
1067 LYXERR(Debug::LATEX, " Validating buffer...");
1068 LaTeXFeatures features(*this, params(), runparams);
1070 LYXERR(Debug::LATEX, " Buffer validation done.");
1072 // The starting paragraph of the coming rows is the
1073 // first paragraph of the document. (Asger)
1074 if (output_preamble && runparams.nice) {
1075 os << "%% LyX " << lyx_version << " created this file. "
1076 "For more info, see http://www.lyx.org/.\n"
1077 "%% Do not edit unless you really know what "
1079 d->texrow.newline();
1080 d->texrow.newline();
1082 LYXERR(Debug::INFO, "lyx document header finished");
1083 // There are a few differences between nice LaTeX and usual files:
1084 // usual is \batchmode and has a
1085 // special input@path to allow the including of figures
1086 // with either \input or \includegraphics (what figinsets do).
1087 // input@path is set when the actual parameter
1088 // original_path is set. This is done for usual tex-file, but not
1089 // for nice-latex-file. (Matthias 250696)
1090 // Note that input@path is only needed for something the user does
1091 // in the preamble, included .tex files or ERT, files included by
1092 // LyX work without it.
1093 if (output_preamble) {
1094 if (!runparams.nice) {
1095 // code for usual, NOT nice-latex-file
1096 os << "\\batchmode\n"; // changed
1097 // from \nonstopmode
1098 d->texrow.newline();
1100 if (!original_path.empty()) {
1102 // We don't know the encoding of inputpath
1103 docstring const inputpath = from_utf8(latex_path(original_path));
1104 os << "\\makeatletter\n"
1105 << "\\def\\input@path{{"
1106 << inputpath << "/}}\n"
1107 << "\\makeatother\n";
1108 d->texrow.newline();
1109 d->texrow.newline();
1110 d->texrow.newline();
1113 // Write the preamble
1114 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1120 os << "\\begin{document}\n";
1121 d->texrow.newline();
1122 } // output_preamble
1124 d->texrow.start(paragraphs().begin()->id(), 0);
1126 LYXERR(Debug::INFO, "preamble finished, now the body.");
1128 // load children, if not already done.
1129 // This includes an updateMacro() call.
1130 // Don't move this behind the parent_buffer=0 code below,
1131 // because then the macros will not get the right "redefinition"
1132 // flag as they don't see the parent macros which are output before.
1133 loadChildDocuments();
1135 // fold macros if possible, still with parent buffer as the
1136 // macros will be put in the prefix anyway.
1137 updateMacroInstances();
1139 // if we are doing a real file with body, even if this is the
1140 // child of some other buffer, let's cut the link here.
1141 // This happens for example if only a child document is printed.
1142 Buffer const * save_parent = 0;
1143 if (output_preamble) {
1144 // output the macros visible for this buffer
1145 writeParentMacros(os);
1147 save_parent = d->parent_buffer;
1148 d->parent_buffer = 0;
1152 latexParagraphs(*this, text(), os, d->texrow, runparams);
1154 // Restore the parenthood if needed
1155 if (output_preamble) {
1156 d->parent_buffer = save_parent;
1158 // restore macros with correct parent buffer (especially
1159 // important for the redefinition flag which depends on the
1164 // add this just in case after all the paragraphs
1166 d->texrow.newline();
1168 if (output_preamble) {
1169 os << "\\end{document}\n";
1170 d->texrow.newline();
1171 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1173 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1175 runparams_in.encoding = runparams.encoding;
1177 // Just to be sure. (Asger)
1178 d->texrow.newline();
1180 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1181 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1185 bool Buffer::isLatex() const
1187 return params().getTextClass().outputType() == LATEX;
1191 bool Buffer::isLiterate() const
1193 return params().getTextClass().outputType() == LITERATE;
1197 bool Buffer::isDocBook() const
1199 return params().getTextClass().outputType() == DOCBOOK;
1203 void Buffer::makeDocBookFile(FileName const & fname,
1204 OutputParams const & runparams,
1205 bool const body_only) const
1207 LYXERR(Debug::LATEX, "makeDocBookFile...");
1210 if (!openFileWrite(ofs, fname))
1213 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1217 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1221 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1222 OutputParams const & runparams,
1223 bool const only_body) const
1225 LaTeXFeatures features(*this, params(), runparams);
1230 TextClass const & tclass = params().getTextClass();
1231 string const top_element = tclass.latexname();
1234 if (runparams.flavor == OutputParams::XML)
1235 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1238 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1241 if (! tclass.class_header().empty())
1242 os << from_ascii(tclass.class_header());
1243 else if (runparams.flavor == OutputParams::XML)
1244 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1245 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1247 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1249 docstring preamble = from_utf8(params().preamble);
1250 if (runparams.flavor != OutputParams::XML ) {
1251 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1252 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1253 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1254 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1257 string const name = runparams.nice
1258 ? changeExtension(absFileName(), ".sgml") : fname;
1259 preamble += features.getIncludedFiles(name);
1260 preamble += features.getLyXSGMLEntities();
1262 if (!preamble.empty()) {
1263 os << "\n [ " << preamble << " ]";
1268 string top = top_element;
1270 if (runparams.flavor == OutputParams::XML)
1271 top += params().language->code();
1273 top += params().language->code().substr(0,2);
1276 if (!params().options.empty()) {
1278 top += params().options;
1281 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1282 << " file was created by LyX " << lyx_version
1283 << "\n See http://www.lyx.org/ for more information -->\n";
1285 params().getTextClass().counters().reset();
1287 loadChildDocuments();
1289 sgml::openTag(os, top);
1291 docbookParagraphs(paragraphs(), *this, os, runparams);
1292 sgml::closeTag(os, top_element);
1296 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1297 // Other flags: -wall -v0 -x
1298 int Buffer::runChktex()
1302 // get LaTeX-Filename
1303 FileName const path(temppath());
1304 string const name = addName(path.absFilename(), latexName());
1305 string const org_path = filePath();
1307 PathChanger p(path); // path to LaTeX file
1308 message(_("Running chktex..."));
1310 // Generate the LaTeX file if neccessary
1311 OutputParams runparams(¶ms().encoding());
1312 runparams.flavor = OutputParams::LATEX;
1313 runparams.nice = false;
1314 makeLaTeXFile(FileName(name), org_path, runparams);
1317 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1318 int const res = chktex.run(terr); // run chktex
1321 Alert::error(_("chktex failure"),
1322 _("Could not run chktex successfully."));
1323 } else if (res > 0) {
1324 ErrorList & errlist = d->errorLists["ChkTeX"];
1326 bufferErrors(terr, errlist);
1337 void Buffer::validate(LaTeXFeatures & features) const
1339 params().validate(features);
1341 loadChildDocuments();
1343 for_each(paragraphs().begin(), paragraphs().end(),
1344 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1346 if (lyxerr.debugging(Debug::LATEX)) {
1347 features.showStruct();
1352 void Buffer::getLabelList(vector<docstring> & list) const
1354 /// if this is a child document and the parent is already loaded
1355 /// Use the parent's list instead [ale990407]
1356 Buffer const * tmp = masterBuffer();
1358 lyxerr << "masterBuffer() failed!" << endl;
1362 tmp->getLabelList(list);
1366 loadChildDocuments();
1368 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1369 it.nextInset()->getLabelList(*this, list);
1373 void Buffer::updateBibfilesCache() const
1375 // if this is a child document and the parent is already loaded
1376 // update the parent's cache instead
1377 Buffer const * tmp = masterBuffer();
1380 tmp->updateBibfilesCache();
1384 d->bibfilesCache_.clear();
1385 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1386 if (it->lyxCode() == BIBTEX_CODE) {
1387 InsetBibtex const & inset =
1388 static_cast<InsetBibtex const &>(*it);
1389 EmbeddedFileList const bibfiles = inset.getFiles(*this);
1390 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1393 } else if (it->lyxCode() == INCLUDE_CODE) {
1394 InsetInclude & inset =
1395 static_cast<InsetInclude &>(*it);
1396 inset.updateBibfilesCache(*this);
1397 EmbeddedFileList const & bibfiles =
1398 inset.getBibfilesCache(*this);
1399 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1407 EmbeddedFileList const & Buffer::getBibfilesCache() const
1409 // if this is a child document and the parent is already loaded
1410 // use the parent's cache instead
1411 Buffer const * tmp = masterBuffer();
1414 return tmp->getBibfilesCache();
1416 // We update the cache when first used instead of at loading time.
1417 if (d->bibfilesCache_.empty())
1418 const_cast<Buffer *>(this)->updateBibfilesCache();
1420 return d->bibfilesCache_;
1424 bool Buffer::isDepClean(string const & name) const
1426 DepClean::const_iterator const it = d->dep_clean.find(name);
1427 if (it == d->dep_clean.end())
1433 void Buffer::markDepClean(string const & name)
1435 d->dep_clean[name] = true;
1439 bool Buffer::dispatch(string const & command, bool * result)
1441 return dispatch(lyxaction.lookupFunc(command), result);
1445 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1447 bool dispatched = true;
1449 switch (func.action) {
1450 case LFUN_BUFFER_EXPORT: {
1451 bool const tmp = doExport(to_utf8(func.argument()), false);
1464 void Buffer::changeLanguage(Language const * from, Language const * to)
1469 for_each(par_iterator_begin(),
1471 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1475 bool Buffer::isMultiLingual() const
1477 ParConstIterator end = par_iterator_end();
1478 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1479 if (it->isMultiLingual(params()))
1486 DocIterator Buffer::getParFromID(int const id) const
1489 // John says this is called with id == -1 from undo
1490 lyxerr << "getParFromID(), id: " << id << endl;
1491 return doc_iterator_end(inset());
1494 for (DocIterator it = doc_iterator_begin(inset()); !it.atEnd(); it.forwardPar())
1495 if (it.paragraph().id() == id)
1498 return doc_iterator_end(inset());
1502 bool Buffer::hasParWithID(int const id) const
1504 return !getParFromID(id).atEnd();
1508 ParIterator Buffer::par_iterator_begin()
1510 return ParIterator(doc_iterator_begin(inset()));
1514 ParIterator Buffer::par_iterator_end()
1516 return ParIterator(doc_iterator_end(inset()));
1520 ParConstIterator Buffer::par_iterator_begin() const
1522 return lyx::par_const_iterator_begin(inset());
1526 ParConstIterator Buffer::par_iterator_end() const
1528 return lyx::par_const_iterator_end(inset());
1532 Language const * Buffer::language() const
1534 return params().language;
1538 docstring const Buffer::B_(string const & l10n) const
1540 return params().B_(l10n);
1544 bool Buffer::isClean() const
1546 return d->lyx_clean;
1550 bool Buffer::isBakClean() const
1552 return d->bak_clean;
1556 bool Buffer::isExternallyModified(CheckMethod method) const
1558 BOOST_ASSERT(d->filename.exists());
1559 // if method == timestamp, check timestamp before checksum
1560 return (method == checksum_method
1561 || d->timestamp_ != d->filename.lastModified())
1562 && d->checksum_ != d->filename.checksum();
1566 void Buffer::saveCheckSum(FileName const & file) const
1568 if (file.exists()) {
1569 d->timestamp_ = file.lastModified();
1570 d->checksum_ = file.checksum();
1572 // in the case of save to a new file.
1579 void Buffer::markClean() const
1581 if (!d->lyx_clean) {
1582 d->lyx_clean = true;
1585 // if the .lyx file has been saved, we don't need an
1587 d->bak_clean = true;
1591 void Buffer::markBakClean() const
1593 d->bak_clean = true;
1597 void Buffer::setUnnamed(bool flag)
1603 bool Buffer::isUnnamed() const
1609 // FIXME: this function should be moved to buffer_pimpl.C
1610 void Buffer::markDirty()
1613 d->lyx_clean = false;
1616 d->bak_clean = false;
1618 DepClean::iterator it = d->dep_clean.begin();
1619 DepClean::const_iterator const end = d->dep_clean.end();
1621 for (; it != end; ++it)
1626 FileName Buffer::fileName() const
1632 string Buffer::absFileName() const
1634 return d->filename.absFilename();
1638 string Buffer::filePath() const
1640 return d->filename.onlyPath().absFilename() + "/";
1644 bool Buffer::isReadonly() const
1646 return d->read_only;
1650 void Buffer::setParent(Buffer const * buffer)
1652 // Avoids recursive include.
1653 d->parent_buffer = buffer == this ? 0 : buffer;
1658 Buffer const * Buffer::parent()
1660 return d->parent_buffer;
1664 Buffer const * Buffer::masterBuffer() const
1666 if (!d->parent_buffer)
1669 return d->parent_buffer->masterBuffer();
1673 template<typename M>
1674 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
1679 typename M::iterator it = m.lower_bound(x);
1680 if (it == m.begin())
1688 MacroData const * Buffer::getBufferMacro(docstring const & name,
1689 DocIterator const & pos) const
1691 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
1693 // if paragraphs have no macro context set, pos will be empty
1697 // we haven't found anything yet
1698 DocIterator bestPos = par_iterator_begin();
1699 MacroData const * bestData = 0;
1701 // find macro definitions for name
1702 Impl::NamePositionScopeMacroMap::iterator nameIt
1703 = d->macros.find(name);
1704 if (nameIt != d->macros.end()) {
1705 // find last definition in front of pos or at pos itself
1706 Impl::PositionScopeMacroMap::const_iterator it
1707 = greatest_below(nameIt->second, pos);
1708 if (it != nameIt->second.end()) {
1710 // scope ends behind pos?
1711 if (pos < it->second.first) {
1712 // Looks good, remember this. If there
1713 // is no external macro behind this,
1714 // we found the right one already.
1715 bestPos = it->first;
1716 bestData = &it->second.second;
1720 // try previous macro if there is one
1721 if (it == nameIt->second.begin())
1728 // find macros in included files
1729 Impl::PositionScopeBufferMap::const_iterator it
1730 = greatest_below(d->position_to_children, pos);
1731 if (it == d->position_to_children.end())
1732 // no children before
1736 // do we know something better (i.e. later) already?
1737 if (it->first < bestPos )
1740 // scope ends behind pos?
1741 if (pos < it->second.first) {
1742 // look for macro in external file
1743 d->macro_lock = true;
1744 MacroData const * data
1745 = it->second.second->getMacro(name, false);
1746 d->macro_lock = false;
1748 bestPos = it->first;
1754 // try previous file if there is one
1755 if (it == d->position_to_children.begin())
1760 // return the best macro we have found
1765 MacroData const * Buffer::getMacro(docstring const & name,
1766 DocIterator const & pos, bool global) const
1771 // query buffer macros
1772 MacroData const * data = getBufferMacro(name, pos);
1776 // If there is a master buffer, query that
1777 if (d->parent_buffer) {
1778 d->macro_lock = true;
1779 MacroData const * macro
1780 = d->parent_buffer->getMacro(name, *this, false);
1781 d->macro_lock = false;
1787 data = MacroTable::globalMacros().get(name);
1796 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
1798 // set scope end behind the last paragraph
1799 DocIterator scope = par_iterator_begin();
1800 scope.pit() = scope.lastpit() + 1;
1802 return getMacro(name, scope, global);
1806 MacroData const * Buffer::getMacro(docstring const & name, Buffer const & child, bool global) const
1808 // look where the child buffer is included first
1809 Impl::BufferPositionMap::iterator it
1810 = d->children_positions.find(&child);
1811 if (it == d->children_positions.end())
1814 // check for macros at the inclusion position
1815 return getMacro(name, it->second, global);
1819 void Buffer::updateEnvironmentMacros(DocIterator & it,
1821 DocIterator & scope) const
1823 Paragraph & par = it.paragraph();
1825 = par.params().depth();
1826 Length const & leftIndent
1827 = par.params().leftIndent();
1829 // look for macros in each paragraph
1830 while (it.pit() <= lastpit) {
1831 Paragraph & par = it.paragraph();
1834 if ((par.params().depth() > depth
1835 || par.params().leftIndent() != leftIndent)
1836 && par.layout()->isEnvironment()) {
1837 updateBlockMacros(it, scope);
1841 // iterate over the insets of the current paragraph
1842 InsetList const & insets = par.insetList();
1843 InsetList::const_iterator iit = insets.begin();
1844 InsetList::const_iterator end = insets.end();
1845 for (; iit != end; ++iit) {
1846 it.pos() = iit->pos;
1848 // is it a nested text inset?
1849 if (iit->inset->asInsetText()) {
1850 // Inset needs its own scope?
1851 InsetText const * itext
1852 = iit->inset->asInsetText();
1853 bool newScope = itext->isMacroScope(*this);
1855 // scope which ends just behind die inset
1856 DocIterator insetScope = it;
1859 // collect macros in inset
1860 it.push_back(CursorSlice(*iit->inset));
1861 updateInsetMacros(it, newScope ? insetScope : scope);
1866 // is it an external file?
1867 if (iit->inset->lyxCode() == INCLUDE_CODE) {
1868 // get buffer of external file
1869 InsetCommand const & inset
1870 = static_cast<InsetCommand const &>(*iit->inset);
1871 InsetCommandParams const & ip = inset.params();
1872 d->macro_lock = true;
1873 Buffer * child = loadIfNeeded(*this, ip);
1874 d->macro_lock = false;
1878 // register its position, but only when it is
1879 // included first in the buffer
1880 if (d->children_positions.find(child)
1881 == d->children_positions.end())
1882 d->children_positions[child] = it;
1884 // register child with its scope
1885 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
1890 if (iit->inset->lyxCode() != MATHMACRO_CODE)
1894 MathMacroTemplate & macroTemplate
1895 = static_cast<MathMacroTemplate &>(*iit->inset);
1896 MacroContext mc(*this, it);
1897 macroTemplate.updateToContext(mc);
1900 bool valid = macroTemplate.validMacro();
1901 // FIXME: Should be fixNameAndCheckIfValid() in fact,
1902 // then the BufferView's cursor will be invalid in
1903 // some cases which leads to crashes.
1908 d->macros[macroTemplate.name()][it]
1909 = Impl::ScopeMacro(scope, MacroData(*this, it));
1919 void Buffer::updateBlockMacros(DocIterator & it, DocIterator & scope) const
1921 Paragraph & par = it.paragraph();
1923 // set scope for macros in this paragraph:
1924 // * either the "old" outer scope
1925 // * or the scope ending after the environment
1926 if (par.layout()->isEnvironment()) {
1927 // find end of environment block,
1928 DocIterator envEnd = it;
1929 pit_type n = it.lastpit() + 1;
1930 depth_type depth = par.params().depth();
1931 Length const & length = par.params().leftIndent();
1932 // looping through the paragraph, basically until
1933 // the layout changes or the depth gets smaller.
1934 // (the logic of output_latex.cpp's TeXEnvironment)
1937 if (envEnd.pit() == n)
1939 } while (par.layout() == envEnd.paragraph().layout()
1940 || depth < envEnd.paragraph().params().depth()
1941 || length != envEnd.paragraph().params().leftIndent());
1943 // collect macros from environment block
1944 updateEnvironmentMacros(it, envEnd.pit() - 1, envEnd);
1946 // collect macros from paragraph
1947 updateEnvironmentMacros(it, it.pit(), scope);
1952 void Buffer::updateInsetMacros(DocIterator & it, DocIterator & scope) const
1954 // look for macros in each paragraph
1955 pit_type n = it.lastpit() + 1;
1956 while (it.pit() < n)
1957 updateBlockMacros(it, scope);
1961 void Buffer::updateMacros() const
1966 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
1968 // start with empty table
1970 d->children_positions.clear();
1971 d->position_to_children.clear();
1973 // Iterate over buffer, starting with first paragraph
1974 // The scope must be bigger than any lookup DocIterator
1975 // later. For the global lookup, lastpit+1 is used, hence
1976 // we use lastpit+2 here.
1977 DocIterator it = par_iterator_begin();
1978 DocIterator outerScope = it;
1979 outerScope.pit() = outerScope.lastpit() + 2;
1980 updateInsetMacros(it, outerScope);
1984 void Buffer::updateMacroInstances() const
1986 LYXERR(Debug::MACROS, "updateMacroInstances for "
1987 << d->filename.onlyFileName());
1988 DocIterator it = doc_iterator_begin(inset());
1989 DocIterator end = doc_iterator_end(inset());
1990 for (; it != end; it.forwardPos()) {
1991 // look for MathData cells in InsetMathNest insets
1992 Inset * inset = it.nextInset();
1996 InsetMath * minset = inset->asInsetMath();
2000 // update macro in all cells of the InsetMathNest
2001 DocIterator::idx_type n = minset->nargs();
2002 MacroContext mc = MacroContext(*this, it);
2003 for (DocIterator::idx_type i = 0; i < n; ++i) {
2004 MathData & data = minset->cell(i);
2005 data.updateMacros(0, mc);
2011 void Buffer::listMacroNames(MacroNameSet & macros) const
2016 d->macro_lock = true;
2018 // loop over macro names
2019 Impl::NamePositionScopeMacroMap::iterator nameIt
2020 = d->macros.begin();
2021 Impl::NamePositionScopeMacroMap::iterator nameEnd
2023 for (; nameIt != nameEnd; ++nameIt)
2024 macros.insert(nameIt->first);
2026 // loop over children
2027 Impl::BufferPositionMap::iterator it
2028 = d->children_positions.begin();
2029 Impl::BufferPositionMap::iterator end
2030 = d->children_positions.end();
2031 for (; it != end; ++it)
2032 it->first->listMacroNames(macros);
2035 if (d->parent_buffer)
2036 d->parent_buffer->listMacroNames(macros);
2038 d->macro_lock = false;
2042 void Buffer::writeParentMacros(odocstream & os) const
2044 if (!d->parent_buffer)
2047 // collect macro names
2049 d->parent_buffer->listMacroNames(names);
2051 // resolve and output them
2052 MacroNameSet::iterator it = names.begin();
2053 MacroNameSet::iterator end = names.end();
2054 for (; it != end; ++it) {
2056 MacroData const * data =
2057 d->parent_buffer->getMacro(*it, *this, false);
2059 data->write(os, true);
2064 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2067 //FIXME: This does not work for child documents yet.
2068 BOOST_ASSERT(code == CITE_CODE || code == REF_CODE);
2069 // Check if the label 'from' appears more than once
2070 vector<docstring> labels;
2073 if (code == CITE_CODE) {
2075 keys.fillWithBibKeys(this);
2076 BiblioInfo::const_iterator bit = keys.begin();
2077 BiblioInfo::const_iterator bend = keys.end();
2079 for (; bit != bend; ++bit)
2081 labels.push_back(bit->first);
2084 getLabelList(labels);
2085 paramName = "reference";
2088 if (count(labels.begin(), labels.end(), from) > 1)
2091 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2092 if (it->lyxCode() == code) {
2093 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2094 docstring const oldValue = inset.getParam(paramName);
2095 if (oldValue == from)
2096 inset.setParam(paramName, to);
2102 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2103 pit_type par_end, bool full_source)
2105 OutputParams runparams(¶ms().encoding());
2106 runparams.nice = true;
2107 runparams.flavor = OutputParams::LATEX;
2108 runparams.linelen = lyxrc.plaintext_linelen;
2109 // No side effect of file copying and image conversion
2110 runparams.dryrun = true;
2114 os << "% " << _("Preview source code") << "\n\n";
2115 d->texrow.newline();
2116 d->texrow.newline();
2118 writeLaTeXSource(os, filePath(), runparams, true, true);
2120 writeDocBookSource(os, absFileName(), runparams, false);
2123 runparams.par_begin = par_begin;
2124 runparams.par_end = par_end;
2125 if (par_begin + 1 == par_end)
2127 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2131 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2132 convert<docstring>(par_begin),
2133 convert<docstring>(par_end - 1))
2135 d->texrow.newline();
2136 d->texrow.newline();
2137 // output paragraphs
2139 latexParagraphs(*this, text(), os, d->texrow, runparams);
2142 docbookParagraphs(paragraphs(), *this, os, runparams);
2148 ErrorList & Buffer::errorList(string const & type) const
2150 static ErrorList emptyErrorList;
2151 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2152 if (I == d->errorLists.end())
2153 return emptyErrorList;
2159 void Buffer::structureChanged() const
2162 gui_->structureChanged();
2166 void Buffer::errors(string const & err) const
2173 void Buffer::message(docstring const & msg) const
2180 void Buffer::setBusy(bool on) const
2187 void Buffer::setReadOnly(bool on) const
2190 d->wa_->setReadOnly(on);
2194 void Buffer::updateTitles() const
2197 d->wa_->updateTitles();
2201 void Buffer::resetAutosaveTimers() const
2204 gui_->resetAutosaveTimers();
2208 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2217 class AutoSaveBuffer : public ForkedProcess {
2220 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2221 : buffer_(buffer), fname_(fname) {}
2223 virtual boost::shared_ptr<ForkedProcess> clone() const
2225 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2230 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2231 from_utf8(fname_.absFilename())));
2232 return run(DontWait);
2236 virtual int generateChild();
2238 Buffer const & buffer_;
2243 int AutoSaveBuffer::generateChild()
2245 // tmp_ret will be located (usually) in /tmp
2246 // will that be a problem?
2247 // Note that this calls ForkedCalls::fork(), so it's
2248 // ok cross-platform.
2249 pid_t const pid = fork();
2250 // If you want to debug the autosave
2251 // you should set pid to -1, and comment out the fork.
2252 if (pid != 0 && pid != -1)
2255 // pid = -1 signifies that lyx was unable
2256 // to fork. But we will do the save
2258 bool failed = false;
2259 FileName const tmp_ret = FileName::tempName("lyxauto");
2260 if (!tmp_ret.empty()) {
2261 buffer_.writeFile(tmp_ret);
2262 // assume successful write of tmp_ret
2263 if (!tmp_ret.moveTo(fname_))
2269 // failed to write/rename tmp_ret so try writing direct
2270 if (!buffer_.writeFile(fname_)) {
2271 // It is dangerous to do this in the child,
2272 // but safe in the parent, so...
2273 if (pid == -1) // emit message signal.
2274 buffer_.message(_("Autosave failed!"));
2278 if (pid == 0) // we are the child so...
2287 // Perfect target for a thread...
2288 void Buffer::autoSave() const
2290 if (isBakClean() || isReadonly()) {
2291 // We don't save now, but we'll try again later
2292 resetAutosaveTimers();
2296 // emit message signal.
2297 message(_("Autosaving current document..."));
2299 // create autosave filename
2300 string fname = filePath();
2302 fname += d->filename.onlyFileName();
2305 AutoSaveBuffer autosave(*this, FileName(fname));
2309 resetAutosaveTimers();
2313 void Buffer::resetChildDocuments(bool close_them) const
2318 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2319 if (it->lyxCode() != INCLUDE_CODE)
2321 InsetCommand const & inset = static_cast<InsetCommand const &>(*it);
2322 InsetCommandParams const & ip = inset.params();
2324 resetParentBuffer(this, ip, close_them);
2327 if (use_gui && masterBuffer() == this)
2328 updateLabels(*this);
2330 // clear references to children in macro tables
2331 d->children_positions.clear();
2332 d->position_to_children.clear();
2336 void Buffer::loadChildDocuments() const
2338 bool parse_error = false;
2340 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2341 if (it->lyxCode() != INCLUDE_CODE)
2343 InsetCommand const & inset = static_cast<InsetCommand const &>(*it);
2344 InsetCommandParams const & ip = inset.params();
2345 Buffer * child = loadIfNeeded(*this, ip);
2348 parse_error |= !child->errorList("Parse").empty();
2349 child->loadChildDocuments();
2352 if (use_gui && masterBuffer() == this)
2353 updateLabels(*this);
2359 string Buffer::bufferFormat() const
2369 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2370 string & result_file) const
2372 string backend_format;
2373 OutputParams runparams(¶ms().encoding());
2374 runparams.flavor = OutputParams::LATEX;
2375 runparams.linelen = lyxrc.plaintext_linelen;
2376 vector<string> backs = backends();
2377 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2378 // Get shortest path to format
2379 Graph::EdgePath path;
2380 for (vector<string>::const_iterator it = backs.begin();
2381 it != backs.end(); ++it) {
2382 Graph::EdgePath p = theConverters().getPath(*it, format);
2383 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2384 backend_format = *it;
2389 runparams.flavor = theConverters().getFlavor(path);
2391 Alert::error(_("Couldn't export file"),
2392 bformat(_("No information for exporting the format %1$s."),
2393 formats.prettyName(format)));
2397 backend_format = format;
2398 // FIXME: Don't hardcode format names here, but use a flag
2399 if (backend_format == "pdflatex")
2400 runparams.flavor = OutputParams::PDFLATEX;
2403 string filename = latexName(false);
2404 filename = addName(temppath(), filename);
2405 filename = changeExtension(filename,
2406 formats.extension(backend_format));
2409 updateMacroInstances();
2411 // Plain text backend
2412 if (backend_format == "text")
2413 writePlaintextFile(*this, FileName(filename), runparams);
2415 else if (backend_format == "lyx")
2416 writeFile(FileName(filename));
2418 else if (isDocBook()) {
2419 runparams.nice = !put_in_tempdir;
2420 makeDocBookFile(FileName(filename), runparams);
2423 else if (backend_format == format) {
2424 runparams.nice = true;
2425 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2427 } else if (!lyxrc.tex_allows_spaces
2428 && contains(filePath(), ' ')) {
2429 Alert::error(_("File name error"),
2430 _("The directory path to the document cannot contain spaces."));
2433 runparams.nice = false;
2434 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2438 string const error_type = (format == "program")
2439 ? "Build" : bufferFormat();
2440 string const ext = formats.extension(format);
2441 FileName const tmp_result_file(changeExtension(filename, ext));
2442 bool const success = theConverters().convert(this, FileName(filename),
2443 tmp_result_file, FileName(absFileName()), backend_format, format,
2444 errorList(error_type));
2445 // Emit the signal to show the error list.
2446 if (format != backend_format)
2451 if (put_in_tempdir) {
2452 result_file = tmp_result_file.absFilename();
2456 result_file = changeExtension(absFileName(), ext);
2457 // We need to copy referenced files (e. g. included graphics
2458 // if format == "dvi") to the result dir.
2459 vector<ExportedFile> const files =
2460 runparams.exportdata->externalFiles(format);
2461 string const dest = onlyPath(result_file);
2462 CopyStatus status = SUCCESS;
2463 for (vector<ExportedFile>::const_iterator it = files.begin();
2464 it != files.end() && status != CANCEL; ++it) {
2465 string const fmt = formats.getFormatFromFile(it->sourceName);
2466 status = copyFile(fmt, it->sourceName,
2467 makeAbsPath(it->exportName, dest),
2468 it->exportName, status == FORCE);
2470 if (status == CANCEL) {
2471 message(_("Document export cancelled."));
2472 } else if (tmp_result_file.exists()) {
2473 // Finally copy the main file
2474 status = copyFile(format, tmp_result_file,
2475 FileName(result_file), result_file,
2477 message(bformat(_("Document exported as %1$s "
2479 formats.prettyName(format),
2480 makeDisplayPath(result_file)));
2482 // This must be a dummy converter like fax (bug 1888)
2483 message(bformat(_("Document exported as %1$s"),
2484 formats.prettyName(format)));
2491 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2494 return doExport(format, put_in_tempdir, result_file);
2498 bool Buffer::preview(string const & format) const
2501 if (!doExport(format, true, result_file))
2503 return formats.view(*this, FileName(result_file), format);
2507 bool Buffer::isExportable(string const & format) const
2509 vector<string> backs = backends();
2510 for (vector<string>::const_iterator it = backs.begin();
2511 it != backs.end(); ++it)
2512 if (theConverters().isReachable(*it, format))
2518 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2520 vector<string> backs = backends();
2521 vector<Format const *> result =
2522 theConverters().getReachable(backs[0], only_viewable, true);
2523 for (vector<string>::const_iterator it = backs.begin() + 1;
2524 it != backs.end(); ++it) {
2525 vector<Format const *> r =
2526 theConverters().getReachable(*it, only_viewable, false);
2527 result.insert(result.end(), r.begin(), r.end());
2533 vector<string> Buffer::backends() const
2536 if (params().getTextClass().isTeXClassAvailable()) {
2537 v.push_back(bufferFormat());
2538 // FIXME: Don't hardcode format names here, but use a flag
2539 if (v.back() == "latex")
2540 v.push_back("pdflatex");
2542 v.push_back("text");
2548 bool Buffer::readFileHelper(FileName const & s)
2550 // File information about normal file
2552 docstring const file = makeDisplayPath(s.absFilename(), 50);
2553 docstring text = bformat(_("The specified document\n%1$s"
2554 "\ncould not be read."), file);
2555 Alert::error(_("Could not read document"), text);
2559 // Check if emergency save file exists and is newer.
2560 FileName const e(s.absFilename() + ".emergency");
2562 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2563 docstring const file = makeDisplayPath(s.absFilename(), 20);
2564 docstring const text =
2565 bformat(_("An emergency save of the document "
2567 "Recover emergency save?"), file);
2568 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2569 _("&Recover"), _("&Load Original"),
2573 // the file is not saved if we load the emergency file.
2583 // Now check if autosave file is newer.
2584 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2586 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2587 docstring const file = makeDisplayPath(s.absFilename(), 20);
2588 docstring const text =
2589 bformat(_("The backup of the document "
2590 "%1$s is newer.\n\nLoad the "
2591 "backup instead?"), file);
2592 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2593 _("&Load backup"), _("Load &original"),
2597 // the file is not saved if we load the autosave file.
2601 // Here we delete the autosave
2612 bool Buffer::loadLyXFile(FileName const & s)
2614 if (s.isReadableFile()) {
2615 if (readFileHelper(s)) {
2616 lyxvc().file_found_hook(s);
2617 if (!s.isWritable())
2622 docstring const file = makeDisplayPath(s.absFilename(), 20);
2623 // Here we probably should run
2624 if (LyXVC::file_not_found_hook(s)) {
2625 docstring const text =
2626 bformat(_("Do you want to retrieve the document"
2627 " %1$s from version control?"), file);
2628 int const ret = Alert::prompt(_("Retrieve from version control?"),
2629 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2632 // How can we know _how_ to do the checkout?
2633 // With the current VC support it has to be,
2634 // a RCS file since CVS do not have special ,v files.
2636 return loadLyXFile(s);
2644 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2646 TeXErrors::Errors::const_iterator cit = terr.begin();
2647 TeXErrors::Errors::const_iterator end = terr.end();
2649 for (; cit != end; ++cit) {
2652 int errorRow = cit->error_in_line;
2653 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2659 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2660 } while (found && id_start == id_end && pos_start == pos_end);
2662 errorList.push_back(ErrorItem(cit->error_desc,
2663 cit->error_text, id_start, pos_start, pos_end));