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 = 314; // Uwe Stöhr: scrlttr2 for serial letters
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().listings_params.clear();
470 params().clearLayoutModules();
471 params().pdfoptions().clear();
473 for (int i = 0; i < 4; ++i) {
474 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
475 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
478 ErrorList & errorList = d->errorLists["Parse"];
482 string const token = lex.getString();
487 if (token == "\\end_header")
491 if (token == "\\begin_header") {
492 begin_header_line = line;
496 LYXERR(Debug::PARSER, "Handling document header token: `"
499 string unknown = params().readToken(lex, token, d->filename.onlyPath());
500 if (!unknown.empty()) {
501 if (unknown[0] != '\\' && token == "\\textclass") {
502 Alert::warning(_("Unknown document class"),
503 bformat(_("Using the default document class, because the "
504 "class %1$s is unknown."), from_utf8(unknown)));
507 docstring const s = bformat(_("Unknown token: "
511 errorList.push_back(ErrorItem(_("Document header error"),
516 if (begin_header_line) {
517 docstring const s = _("\\begin_header is missing");
518 errorList.push_back(ErrorItem(_("Document header error"),
522 params().makeTextClass();
524 return unknown_tokens;
529 // changed to be public and have one parameter
530 // Returns false if "\end_document" is not read (Asger)
531 bool Buffer::readDocument(Lexer & lex)
533 ErrorList & errorList = d->errorLists["Parse"];
537 string const token = lex.getString();
538 if (token != "\\begin_document") {
539 docstring const s = _("\\begin_document is missing");
540 errorList.push_back(ErrorItem(_("Document header error"),
544 // we are reading in a brand new document
545 BOOST_ASSERT(paragraphs().empty());
549 if (params().outputChanges) {
550 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
551 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
552 LaTeXFeatures::isAvailable("xcolor");
554 if (!dvipost && !xcolorsoul) {
555 Alert::warning(_("Changes not shown in LaTeX output"),
556 _("Changes will not be highlighted in LaTeX output, "
557 "because neither dvipost nor xcolor/soul are installed.\n"
558 "Please install these packages or redefine "
559 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
560 } else if (!xcolorsoul) {
561 Alert::warning(_("Changes not shown in LaTeX output"),
562 _("Changes will not be highlighted in LaTeX output "
563 "when using pdflatex, because xcolor and soul are not installed.\n"
564 "Please install both packages or redefine "
565 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
570 bool const res = text().read(*this, lex, errorList, &inset());
573 updateMacroInstances();
578 // needed to insert the selection
579 void Buffer::insertStringAsLines(ParagraphList & pars,
580 pit_type & pit, pos_type & pos,
581 Font const & fn, docstring const & str, bool autobreakrows)
585 // insert the string, don't insert doublespace
586 bool space_inserted = true;
587 for (docstring::const_iterator cit = str.begin();
588 cit != str.end(); ++cit) {
589 Paragraph & par = pars[pit];
591 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
592 breakParagraph(params(), pars, pit, pos,
593 par.layout()->isEnvironment());
596 space_inserted = true;
600 // do not insert consecutive spaces if !free_spacing
601 } else if ((*cit == ' ' || *cit == '\t') &&
602 space_inserted && !par.isFreeSpacing()) {
604 } else if (*cit == '\t') {
605 if (!par.isFreeSpacing()) {
606 // tabs are like spaces here
607 par.insertChar(pos, ' ', font, params().trackChanges);
609 space_inserted = true;
611 const pos_type n = 8 - pos % 8;
612 for (pos_type i = 0; i < n; ++i) {
613 par.insertChar(pos, ' ', font, params().trackChanges);
616 space_inserted = true;
618 } else if (!isPrintable(*cit)) {
619 // Ignore unprintables
622 // just insert the character
623 par.insertChar(pos, *cit, font, params().trackChanges);
625 space_inserted = (*cit == ' ');
632 bool Buffer::readString(string const & s)
634 params().compressed = false;
636 // remove dummy empty par
637 paragraphs().clear();
641 FileName const name = FileName::tempName();
642 switch (readFile(lex, name, true)) {
646 // We need to call lyx2lyx, so write the input to a file
647 ofstream os(name.toFilesystemEncoding().c_str());
650 return readFile(name);
660 bool Buffer::readFile(FileName const & filename)
662 FileName fname(filename);
663 // Check if the file is compressed.
664 string format = filename.guessFormatFromContents();
665 if (format == "zip") {
666 // decompress to a temp directory
667 LYXERR(Debug::FILES, filename << " is in zip format. Unzip to " << temppath());
668 ::unzipToDir(filename.toFilesystemEncoding(), temppath());
670 FileName lyxfile(addName(temppath(), "content.lyx"));
671 // if both manifest.txt and file.lyx exist, this is am embedded file
672 if (lyxfile.exists()) {
673 // if in bundled format, save checksum of the compressed file, not content.lyx
674 saveCheckSum(filename);
675 params().embedded = true;
679 // The embedded lyx file can also be compressed, for backward compatibility
680 format = fname.guessFormatFromContents();
681 if (format == "gzip" || format == "zip" || format == "compress")
682 params().compressed = true;
684 // remove dummy empty par
685 paragraphs().clear();
688 if (readFile(lex, fname) != success)
695 bool Buffer::isFullyLoaded() const
697 return d->file_fully_loaded;
701 void Buffer::setFullyLoaded(bool value)
703 d->file_fully_loaded = value;
707 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
710 BOOST_ASSERT(!filename.empty());
713 Alert::error(_("Document could not be read"),
714 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
719 string const token = lex.getString();
722 Alert::error(_("Document could not be read"),
723 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
727 // the first token _must_ be...
728 if (token != "\\lyxformat") {
729 lyxerr << "Token: " << token << endl;
731 Alert::error(_("Document format failure"),
732 bformat(_("%1$s is not a LyX document."),
733 from_utf8(filename.absFilename())));
738 string tmp_format = lex.getString();
739 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
740 // if present remove ".," from string.
741 string::size_type dot = tmp_format.find_first_of(".,");
742 //lyxerr << " dot found at " << dot << endl;
743 if (dot != string::npos)
744 tmp_format.erase(dot, 1);
745 int const file_format = convert<int>(tmp_format);
746 //lyxerr << "format: " << file_format << endl;
748 // save timestamp and checksum of the original disk file, making sure
749 // to not overwrite them with those of the file created in the tempdir
750 // when it has to be converted to the current format.
752 // Save the timestamp and checksum of disk file. If filename is an
753 // emergency file, save the timestamp and checksum of the original lyx file
754 // because isExternallyModified will check for this file. (BUG4193)
755 string diskfile = filename.absFilename();
756 if (suffixIs(diskfile, ".emergency"))
757 diskfile = diskfile.substr(0, diskfile.size() - 10);
758 saveCheckSum(FileName(diskfile));
761 if (file_format != LYX_FORMAT) {
764 // lyx2lyx would fail
767 FileName const tmpfile = FileName::tempName();
768 if (tmpfile.empty()) {
769 Alert::error(_("Conversion failed"),
770 bformat(_("%1$s is from a different"
771 " version of LyX, but a temporary"
772 " file for converting it could"
774 from_utf8(filename.absFilename())));
777 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
778 if (lyx2lyx.empty()) {
779 Alert::error(_("Conversion script not found"),
780 bformat(_("%1$s is from a different"
781 " version of LyX, but the"
782 " conversion script lyx2lyx"
783 " could not be found."),
784 from_utf8(filename.absFilename())));
787 ostringstream command;
788 command << os::python()
789 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
790 << " -t " << convert<string>(LYX_FORMAT)
791 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
792 << ' ' << quoteName(filename.toFilesystemEncoding());
793 string const command_str = command.str();
795 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
797 cmd_ret const ret = runCommand(command_str);
798 if (ret.first != 0) {
799 Alert::error(_("Conversion script failed"),
800 bformat(_("%1$s is from a different version"
801 " of LyX, but the lyx2lyx script"
802 " failed to convert it."),
803 from_utf8(filename.absFilename())));
806 bool const ret = readFile(tmpfile);
807 // Do stuff with tmpfile name and buffer name here.
808 return ret ? success : failure;
813 if (readDocument(lex)) {
814 Alert::error(_("Document format failure"),
815 bformat(_("%1$s ended unexpectedly, which means"
816 " that it is probably corrupted."),
817 from_utf8(filename.absFilename())));
820 d->file_fully_loaded = true;
825 // Should probably be moved to somewhere else: BufferView? LyXView?
826 bool Buffer::save() const
828 // We don't need autosaves in the immediate future. (Asger)
829 resetAutosaveTimers();
831 string const encodedFilename = d->filename.toFilesystemEncoding();
834 bool madeBackup = false;
836 // make a backup if the file already exists
837 if (lyxrc.make_backup && fileName().exists()) {
838 backupName = FileName(absFileName() + '~');
839 if (!lyxrc.backupdir_path.empty()) {
840 string const mangledName =
841 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
842 backupName = FileName(addName(lyxrc.backupdir_path,
845 if (fileName().copyTo(backupName)) {
848 Alert::error(_("Backup failure"),
849 bformat(_("Cannot create backup file %1$s.\n"
850 "Please check whether the directory exists and is writeable."),
851 from_utf8(backupName.absFilename())));
852 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
856 // ask if the disk file has been externally modified (use checksum method)
857 if (fileName().exists() && isExternallyModified(checksum_method)) {
858 docstring const file = makeDisplayPath(absFileName(), 20);
859 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
860 "you want to overwrite this file?"), file);
861 int const ret = Alert::prompt(_("Overwrite modified file?"),
862 text, 1, 1, _("&Overwrite"), _("&Cancel"));
867 if (writeFile(d->filename)) {
871 // Saving failed, so backup is not backup
873 backupName.moveTo(d->filename);
879 bool Buffer::writeFile(FileName const & fname) const
881 if (d->read_only && fname == d->filename)
887 if (params().embedded)
888 // first write the .lyx file to the temporary directory
889 content = FileName(addName(temppath(), "content.lyx"));
893 docstring const str = bformat(_("Saving document %1$s..."),
894 makeDisplayPath(content.absFilename()));
897 if (params().compressed) {
898 gz::ogzstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
899 retval = ofs && write(ofs);
901 ofstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
902 retval = ofs && write(ofs);
906 message(str + _(" could not write file!."));
910 removeAutosaveFile(d->filename.absFilename());
912 if (params().embedded) {
913 message(str + _(" writing embedded files!."));
914 // if embedding is enabled, write file.lyx and all the embedded files
915 // to the zip file fname.
916 if (!d->embedded_files.writeFile(fname, *this)) {
917 message(str + _(" could not write embedded files!."));
921 saveCheckSum(d->filename);
922 message(str + _(" done."));
928 bool Buffer::write(ostream & ofs) const
931 // Use the standard "C" locale for file output.
932 ofs.imbue(locale::classic());
935 // The top of the file should not be written by params().
937 // write out a comment in the top of the file
938 ofs << "#LyX " << lyx_version
939 << " created this file. For more info see http://www.lyx.org/\n"
940 << "\\lyxformat " << LYX_FORMAT << "\n"
941 << "\\begin_document\n";
943 /// For each author, set 'used' to true if there is a change
944 /// by this author in the document; otherwise set it to 'false'.
945 AuthorList::Authors::const_iterator a_it = params().authors().begin();
946 AuthorList::Authors::const_iterator a_end = params().authors().end();
947 for (; a_it != a_end; ++a_it)
948 a_it->second.setUsed(false);
950 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
951 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
952 for ( ; it != end; ++it)
953 it->checkAuthors(params().authors());
955 // now write out the buffer parameters.
956 ofs << "\\begin_header\n";
957 params().writeFile(ofs);
958 ofs << "\\end_header\n";
961 ofs << "\n\\begin_body\n";
962 text().write(*this, ofs);
963 ofs << "\n\\end_body\n";
965 // Write marker that shows file is complete
966 ofs << "\\end_document" << endl;
968 // Shouldn't really be needed....
971 // how to check if close went ok?
972 // Following is an attempt... (BE 20001011)
974 // good() returns false if any error occured, including some
976 // bad() returns true if something bad happened in the buffer,
977 // which should include file system full errors.
982 lyxerr << "File was not closed properly." << endl;
989 bool Buffer::makeLaTeXFile(FileName const & fname,
990 string const & original_path,
991 OutputParams const & runparams,
992 bool output_preamble, bool output_body) const
994 string const encoding = runparams.encoding->iconvName();
995 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
998 try { ofs.reset(encoding); }
999 catch (iconv_codecvt_facet_exception & e) {
1000 lyxerr << "Caught iconv exception: " << e.what() << endl;
1001 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1002 "verify that the support software for your encoding (%1$s) is "
1003 "properly installed"), from_ascii(encoding)));
1006 if (!openFileWrite(ofs, fname))
1009 //TexStream ts(ofs.rdbuf(), &texrow());
1010 ErrorList & errorList = d->errorLists["Export"];
1012 bool failed_export = false;
1015 writeLaTeXSource(ofs, original_path,
1016 runparams, output_preamble, output_body);
1018 catch (EncodingException & e) {
1019 odocstringstream ods;
1020 ods.put(e.failed_char);
1022 oss << "0x" << hex << e.failed_char << dec;
1023 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1024 " (code point %2$s)"),
1025 ods.str(), from_utf8(oss.str()));
1026 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1027 "representable in the chosen encoding.\n"
1028 "Changing the document encoding to utf8 could help."),
1029 e.par_id, e.pos, e.pos + 1));
1030 failed_export = true;
1032 catch (iconv_codecvt_facet_exception & e) {
1033 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1034 _(e.what()), -1, 0, 0));
1035 failed_export = true;
1037 catch (exception const & e) {
1038 errorList.push_back(ErrorItem(_("conversion failed"),
1039 _(e.what()), -1, 0, 0));
1040 failed_export = true;
1043 lyxerr << "Caught some really weird exception..." << endl;
1044 LyX::cref().exit(1);
1049 failed_export = true;
1050 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1054 return !failed_export;
1058 void Buffer::writeLaTeXSource(odocstream & os,
1059 string const & original_path,
1060 OutputParams const & runparams_in,
1061 bool const output_preamble, bool const output_body) const
1063 OutputParams runparams = runparams_in;
1065 // validate the buffer.
1066 LYXERR(Debug::LATEX, " Validating buffer...");
1067 LaTeXFeatures features(*this, params(), runparams);
1069 LYXERR(Debug::LATEX, " Buffer validation done.");
1071 // The starting paragraph of the coming rows is the
1072 // first paragraph of the document. (Asger)
1073 if (output_preamble && runparams.nice) {
1074 os << "%% LyX " << lyx_version << " created this file. "
1075 "For more info, see http://www.lyx.org/.\n"
1076 "%% Do not edit unless you really know what "
1078 d->texrow.newline();
1079 d->texrow.newline();
1081 LYXERR(Debug::INFO, "lyx document header finished");
1082 // There are a few differences between nice LaTeX and usual files:
1083 // usual is \batchmode and has a
1084 // special input@path to allow the including of figures
1085 // with either \input or \includegraphics (what figinsets do).
1086 // input@path is set when the actual parameter
1087 // original_path is set. This is done for usual tex-file, but not
1088 // for nice-latex-file. (Matthias 250696)
1089 // Note that input@path is only needed for something the user does
1090 // in the preamble, included .tex files or ERT, files included by
1091 // LyX work without it.
1092 if (output_preamble) {
1093 if (!runparams.nice) {
1094 // code for usual, NOT nice-latex-file
1095 os << "\\batchmode\n"; // changed
1096 // from \nonstopmode
1097 d->texrow.newline();
1099 if (!original_path.empty()) {
1101 // We don't know the encoding of inputpath
1102 docstring const inputpath = from_utf8(latex_path(original_path));
1103 os << "\\makeatletter\n"
1104 << "\\def\\input@path{{"
1105 << inputpath << "/}}\n"
1106 << "\\makeatother\n";
1107 d->texrow.newline();
1108 d->texrow.newline();
1109 d->texrow.newline();
1112 // Write the preamble
1113 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1119 os << "\\begin{document}\n";
1120 d->texrow.newline();
1121 } // output_preamble
1123 d->texrow.start(paragraphs().begin()->id(), 0);
1125 LYXERR(Debug::INFO, "preamble finished, now the body.");
1127 // load children, if not already done.
1128 // This includes an updateMacro() call.
1129 // Don't move this behind the parent_buffer=0 code below,
1130 // because then the macros will not get the right "redefinition"
1131 // flag as they don't see the parent macros which are output before.
1132 loadChildDocuments();
1134 // fold macros if possible, still with parent buffer as the
1135 // macros will be put in the prefix anyway.
1136 updateMacroInstances();
1138 // if we are doing a real file with body, even if this is the
1139 // child of some other buffer, let's cut the link here.
1140 // This happens for example if only a child document is printed.
1141 Buffer const * save_parent = 0;
1142 if (output_preamble) {
1143 // output the macros visible for this buffer
1144 writeParentMacros(os);
1146 save_parent = d->parent_buffer;
1147 d->parent_buffer = 0;
1151 latexParagraphs(*this, text(), os, d->texrow, runparams);
1153 // Restore the parenthood if needed
1154 if (output_preamble) {
1155 d->parent_buffer = save_parent;
1157 // restore macros with correct parent buffer (especially
1158 // important for the redefinition flag which depends on the
1163 // add this just in case after all the paragraphs
1165 d->texrow.newline();
1167 if (output_preamble) {
1168 os << "\\end{document}\n";
1169 d->texrow.newline();
1170 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1172 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1174 runparams_in.encoding = runparams.encoding;
1176 // Just to be sure. (Asger)
1177 d->texrow.newline();
1179 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1180 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1184 bool Buffer::isLatex() const
1186 return params().getTextClass().outputType() == LATEX;
1190 bool Buffer::isLiterate() const
1192 return params().getTextClass().outputType() == LITERATE;
1196 bool Buffer::isDocBook() const
1198 return params().getTextClass().outputType() == DOCBOOK;
1202 void Buffer::makeDocBookFile(FileName const & fname,
1203 OutputParams const & runparams,
1204 bool const body_only) const
1206 LYXERR(Debug::LATEX, "makeDocBookFile...");
1209 if (!openFileWrite(ofs, fname))
1212 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1216 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1220 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1221 OutputParams const & runparams,
1222 bool const only_body) const
1224 LaTeXFeatures features(*this, params(), runparams);
1229 TextClass const & tclass = params().getTextClass();
1230 string const top_element = tclass.latexname();
1233 if (runparams.flavor == OutputParams::XML)
1234 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1237 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1240 if (! tclass.class_header().empty())
1241 os << from_ascii(tclass.class_header());
1242 else if (runparams.flavor == OutputParams::XML)
1243 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1244 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1246 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1248 docstring preamble = from_utf8(params().preamble);
1249 if (runparams.flavor != OutputParams::XML ) {
1250 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1251 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1252 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1253 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1256 string const name = runparams.nice
1257 ? changeExtension(absFileName(), ".sgml") : fname;
1258 preamble += features.getIncludedFiles(name);
1259 preamble += features.getLyXSGMLEntities();
1261 if (!preamble.empty()) {
1262 os << "\n [ " << preamble << " ]";
1267 string top = top_element;
1269 if (runparams.flavor == OutputParams::XML)
1270 top += params().language->code();
1272 top += params().language->code().substr(0,2);
1275 if (!params().options.empty()) {
1277 top += params().options;
1280 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1281 << " file was created by LyX " << lyx_version
1282 << "\n See http://www.lyx.org/ for more information -->\n";
1284 params().getTextClass().counters().reset();
1286 loadChildDocuments();
1288 sgml::openTag(os, top);
1290 docbookParagraphs(paragraphs(), *this, os, runparams);
1291 sgml::closeTag(os, top_element);
1295 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1296 // Other flags: -wall -v0 -x
1297 int Buffer::runChktex()
1301 // get LaTeX-Filename
1302 FileName const path(temppath());
1303 string const name = addName(path.absFilename(), latexName());
1304 string const org_path = filePath();
1306 PathChanger p(path); // path to LaTeX file
1307 message(_("Running chktex..."));
1309 // Generate the LaTeX file if neccessary
1310 OutputParams runparams(¶ms().encoding());
1311 runparams.flavor = OutputParams::LATEX;
1312 runparams.nice = false;
1313 makeLaTeXFile(FileName(name), org_path, runparams);
1316 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1317 int const res = chktex.run(terr); // run chktex
1320 Alert::error(_("chktex failure"),
1321 _("Could not run chktex successfully."));
1322 } else if (res > 0) {
1323 ErrorList & errlist = d->errorLists["ChkTeX"];
1325 bufferErrors(terr, errlist);
1336 void Buffer::validate(LaTeXFeatures & features) const
1338 params().validate(features);
1340 loadChildDocuments();
1342 for_each(paragraphs().begin(), paragraphs().end(),
1343 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1345 if (lyxerr.debugging(Debug::LATEX)) {
1346 features.showStruct();
1351 void Buffer::getLabelList(vector<docstring> & list) const
1353 /// if this is a child document and the parent is already loaded
1354 /// Use the parent's list instead [ale990407]
1355 Buffer const * tmp = masterBuffer();
1357 lyxerr << "masterBuffer() failed!" << endl;
1361 tmp->getLabelList(list);
1365 loadChildDocuments();
1367 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1368 it.nextInset()->getLabelList(*this, list);
1372 void Buffer::updateBibfilesCache() const
1374 // if this is a child document and the parent is already loaded
1375 // update the parent's cache instead
1376 Buffer const * tmp = masterBuffer();
1379 tmp->updateBibfilesCache();
1383 d->bibfilesCache_.clear();
1384 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1385 if (it->lyxCode() == BIBTEX_CODE) {
1386 InsetBibtex const & inset =
1387 static_cast<InsetBibtex const &>(*it);
1388 EmbeddedFileList const bibfiles = inset.getFiles(*this);
1389 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1392 } else if (it->lyxCode() == INCLUDE_CODE) {
1393 InsetInclude & inset =
1394 static_cast<InsetInclude &>(*it);
1395 inset.updateBibfilesCache(*this);
1396 EmbeddedFileList const & bibfiles =
1397 inset.getBibfilesCache(*this);
1398 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1406 EmbeddedFileList const & Buffer::getBibfilesCache() const
1408 // if this is a child document and the parent is already loaded
1409 // use the parent's cache instead
1410 Buffer const * tmp = masterBuffer();
1413 return tmp->getBibfilesCache();
1415 // We update the cache when first used instead of at loading time.
1416 if (d->bibfilesCache_.empty())
1417 const_cast<Buffer *>(this)->updateBibfilesCache();
1419 return d->bibfilesCache_;
1423 bool Buffer::isDepClean(string const & name) const
1425 DepClean::const_iterator const it = d->dep_clean.find(name);
1426 if (it == d->dep_clean.end())
1432 void Buffer::markDepClean(string const & name)
1434 d->dep_clean[name] = true;
1438 bool Buffer::dispatch(string const & command, bool * result)
1440 return dispatch(lyxaction.lookupFunc(command), result);
1444 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1446 bool dispatched = true;
1448 switch (func.action) {
1449 case LFUN_BUFFER_EXPORT: {
1450 bool const tmp = doExport(to_utf8(func.argument()), false);
1463 void Buffer::changeLanguage(Language const * from, Language const * to)
1468 for_each(par_iterator_begin(),
1470 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1474 bool Buffer::isMultiLingual() const
1476 ParConstIterator end = par_iterator_end();
1477 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1478 if (it->isMultiLingual(params()))
1485 DocIterator Buffer::getParFromID(int const id) const
1488 // John says this is called with id == -1 from undo
1489 lyxerr << "getParFromID(), id: " << id << endl;
1490 return doc_iterator_end(inset());
1493 for (DocIterator it = doc_iterator_begin(inset()); !it.atEnd(); it.forwardPar())
1494 if (it.paragraph().id() == id)
1497 return doc_iterator_end(inset());
1501 bool Buffer::hasParWithID(int const id) const
1503 return !getParFromID(id).atEnd();
1507 ParIterator Buffer::par_iterator_begin()
1509 return ParIterator(doc_iterator_begin(inset()));
1513 ParIterator Buffer::par_iterator_end()
1515 return ParIterator(doc_iterator_end(inset()));
1519 ParConstIterator Buffer::par_iterator_begin() const
1521 return lyx::par_const_iterator_begin(inset());
1525 ParConstIterator Buffer::par_iterator_end() const
1527 return lyx::par_const_iterator_end(inset());
1531 Language const * Buffer::language() const
1533 return params().language;
1537 docstring const Buffer::B_(string const & l10n) const
1539 return params().B_(l10n);
1543 bool Buffer::isClean() const
1545 return d->lyx_clean;
1549 bool Buffer::isBakClean() const
1551 return d->bak_clean;
1555 bool Buffer::isExternallyModified(CheckMethod method) const
1557 BOOST_ASSERT(d->filename.exists());
1558 // if method == timestamp, check timestamp before checksum
1559 return (method == checksum_method
1560 || d->timestamp_ != d->filename.lastModified())
1561 && d->checksum_ != d->filename.checksum();
1565 void Buffer::saveCheckSum(FileName const & file) const
1567 if (file.exists()) {
1568 d->timestamp_ = file.lastModified();
1569 d->checksum_ = file.checksum();
1571 // in the case of save to a new file.
1578 void Buffer::markClean() const
1580 if (!d->lyx_clean) {
1581 d->lyx_clean = true;
1584 // if the .lyx file has been saved, we don't need an
1586 d->bak_clean = true;
1590 void Buffer::markBakClean() const
1592 d->bak_clean = true;
1596 void Buffer::setUnnamed(bool flag)
1602 bool Buffer::isUnnamed() const
1608 // FIXME: this function should be moved to buffer_pimpl.C
1609 void Buffer::markDirty()
1612 d->lyx_clean = false;
1615 d->bak_clean = false;
1617 DepClean::iterator it = d->dep_clean.begin();
1618 DepClean::const_iterator const end = d->dep_clean.end();
1620 for (; it != end; ++it)
1625 FileName Buffer::fileName() const
1631 string Buffer::absFileName() const
1633 return d->filename.absFilename();
1637 string Buffer::filePath() const
1639 return d->filename.onlyPath().absFilename() + "/";
1643 bool Buffer::isReadonly() const
1645 return d->read_only;
1649 void Buffer::setParent(Buffer const * buffer)
1651 // Avoids recursive include.
1652 d->parent_buffer = buffer == this ? 0 : buffer;
1657 Buffer const * Buffer::parent()
1659 return d->parent_buffer;
1663 Buffer const * Buffer::masterBuffer() const
1665 if (!d->parent_buffer)
1668 return d->parent_buffer->masterBuffer();
1672 template<typename M>
1673 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
1678 typename M::iterator it = m.lower_bound(x);
1679 if (it == m.begin())
1687 MacroData const * Buffer::getBufferMacro(docstring const & name,
1688 DocIterator const & pos) const
1690 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
1692 // if paragraphs have no macro context set, pos will be empty
1696 // we haven't found anything yet
1697 DocIterator bestPos = par_iterator_begin();
1698 MacroData const * bestData = 0;
1700 // find macro definitions for name
1701 Impl::NamePositionScopeMacroMap::iterator nameIt
1702 = d->macros.find(name);
1703 if (nameIt != d->macros.end()) {
1704 // find last definition in front of pos or at pos itself
1705 Impl::PositionScopeMacroMap::const_iterator it
1706 = greatest_below(nameIt->second, pos);
1707 if (it != nameIt->second.end()) {
1709 // scope ends behind pos?
1710 if (pos < it->second.first) {
1711 // Looks good, remember this. If there
1712 // is no external macro behind this,
1713 // we found the right one already.
1714 bestPos = it->first;
1715 bestData = &it->second.second;
1719 // try previous macro if there is one
1720 if (it == nameIt->second.begin())
1727 // find macros in included files
1728 Impl::PositionScopeBufferMap::const_iterator it
1729 = greatest_below(d->position_to_children, pos);
1730 if (it == d->position_to_children.end())
1731 // no children before
1735 // do we know something better (i.e. later) already?
1736 if (it->first < bestPos )
1739 // scope ends behind pos?
1740 if (pos < it->second.first) {
1741 // look for macro in external file
1742 d->macro_lock = true;
1743 MacroData const * data
1744 = it->second.second->getMacro(name, false);
1745 d->macro_lock = false;
1747 bestPos = it->first;
1753 // try previous file if there is one
1754 if (it == d->position_to_children.begin())
1759 // return the best macro we have found
1764 MacroData const * Buffer::getMacro(docstring const & name,
1765 DocIterator const & pos, bool global) const
1770 // query buffer macros
1771 MacroData const * data = getBufferMacro(name, pos);
1775 // If there is a master buffer, query that
1776 if (d->parent_buffer) {
1777 d->macro_lock = true;
1778 MacroData const * macro
1779 = d->parent_buffer->getMacro(name, *this, false);
1780 d->macro_lock = false;
1786 data = MacroTable::globalMacros().get(name);
1795 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
1797 // set scope end behind the last paragraph
1798 DocIterator scope = par_iterator_begin();
1799 scope.pit() = scope.lastpit() + 1;
1801 return getMacro(name, scope, global);
1805 MacroData const * Buffer::getMacro(docstring const & name, Buffer const & child, bool global) const
1807 // look where the child buffer is included first
1808 Impl::BufferPositionMap::iterator it
1809 = d->children_positions.find(&child);
1810 if (it == d->children_positions.end())
1813 // check for macros at the inclusion position
1814 return getMacro(name, it->second, global);
1818 void Buffer::updateEnvironmentMacros(DocIterator & it,
1820 DocIterator & scope) const
1822 Paragraph & par = it.paragraph();
1824 = par.params().depth();
1825 Length const & leftIndent
1826 = par.params().leftIndent();
1828 // look for macros in each paragraph
1829 while (it.pit() <= lastpit) {
1830 Paragraph & par = it.paragraph();
1833 if ((par.params().depth() > depth
1834 || par.params().leftIndent() != leftIndent)
1835 && par.layout()->isEnvironment()) {
1836 updateBlockMacros(it, scope);
1840 // iterate over the insets of the current paragraph
1841 InsetList const & insets = par.insetList();
1842 InsetList::const_iterator iit = insets.begin();
1843 InsetList::const_iterator end = insets.end();
1844 for (; iit != end; ++iit) {
1845 it.pos() = iit->pos;
1847 // is it a nested text inset?
1848 if (iit->inset->asInsetText()) {
1849 // Inset needs its own scope?
1850 InsetText const * itext
1851 = iit->inset->asInsetText();
1852 bool newScope = itext->isMacroScope(*this);
1854 // scope which ends just behind die inset
1855 DocIterator insetScope = it;
1858 // collect macros in inset
1859 it.push_back(CursorSlice(*iit->inset));
1860 updateInsetMacros(it, newScope ? insetScope : scope);
1865 // is it an external file?
1866 if (iit->inset->lyxCode() == INCLUDE_CODE) {
1867 // get buffer of external file
1868 InsetCommand const & inset
1869 = static_cast<InsetCommand const &>(*iit->inset);
1870 InsetCommandParams const & ip = inset.params();
1871 d->macro_lock = true;
1872 Buffer * child = loadIfNeeded(*this, ip);
1873 d->macro_lock = false;
1877 // register its position, but only when it is
1878 // included first in the buffer
1879 if (d->children_positions.find(child)
1880 == d->children_positions.end())
1881 d->children_positions[child] = it;
1883 // register child with its scope
1884 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
1889 if (iit->inset->lyxCode() != MATHMACRO_CODE)
1893 MathMacroTemplate & macroTemplate
1894 = static_cast<MathMacroTemplate &>(*iit->inset);
1895 MacroContext mc(*this, it);
1896 macroTemplate.updateToContext(mc);
1899 bool valid = macroTemplate.validMacro();
1900 // FIXME: Should be fixNameAndCheckIfValid() in fact,
1901 // then the BufferView's cursor will be invalid in
1902 // some cases which leads to crashes.
1907 d->macros[macroTemplate.name()][it]
1908 = Impl::ScopeMacro(scope, MacroData(*this, it));
1918 void Buffer::updateBlockMacros(DocIterator & it, DocIterator & scope) const
1920 Paragraph & par = it.paragraph();
1922 // set scope for macros in this paragraph:
1923 // * either the "old" outer scope
1924 // * or the scope ending after the environment
1925 if (par.layout()->isEnvironment()) {
1926 // find end of environment block,
1927 DocIterator envEnd = it;
1928 pit_type n = it.lastpit() + 1;
1929 depth_type depth = par.params().depth();
1930 Length const & length = par.params().leftIndent();
1931 // looping through the paragraph, basically until
1932 // the layout changes or the depth gets smaller.
1933 // (the logic of output_latex.cpp's TeXEnvironment)
1936 if (envEnd.pit() == n)
1938 } while (par.layout() == envEnd.paragraph().layout()
1939 || depth < envEnd.paragraph().params().depth()
1940 || length != envEnd.paragraph().params().leftIndent());
1942 // collect macros from environment block
1943 updateEnvironmentMacros(it, envEnd.pit() - 1, envEnd);
1945 // collect macros from paragraph
1946 updateEnvironmentMacros(it, it.pit(), scope);
1951 void Buffer::updateInsetMacros(DocIterator & it, DocIterator & scope) const
1953 // look for macros in each paragraph
1954 pit_type n = it.lastpit() + 1;
1955 while (it.pit() < n)
1956 updateBlockMacros(it, scope);
1960 void Buffer::updateMacros() const
1965 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
1967 // start with empty table
1969 d->children_positions.clear();
1970 d->position_to_children.clear();
1972 // Iterate over buffer, starting with first paragraph
1973 // The scope must be bigger than any lookup DocIterator
1974 // later. For the global lookup, lastpit+1 is used, hence
1975 // we use lastpit+2 here.
1976 DocIterator it = par_iterator_begin();
1977 DocIterator outerScope = it;
1978 outerScope.pit() = outerScope.lastpit() + 2;
1979 updateInsetMacros(it, outerScope);
1983 void Buffer::updateMacroInstances() const
1985 LYXERR(Debug::MACROS, "updateMacroInstances for "
1986 << d->filename.onlyFileName());
1987 DocIterator it = doc_iterator_begin(inset());
1988 DocIterator end = doc_iterator_end(inset());
1989 for (; it != end; it.forwardPos()) {
1990 // look for MathData cells in InsetMathNest insets
1991 Inset * inset = it.nextInset();
1995 InsetMath * minset = inset->asInsetMath();
1999 // update macro in all cells of the InsetMathNest
2000 DocIterator::idx_type n = minset->nargs();
2001 MacroContext mc = MacroContext(*this, it);
2002 for (DocIterator::idx_type i = 0; i < n; ++i) {
2003 MathData & data = minset->cell(i);
2004 data.updateMacros(0, mc);
2010 void Buffer::listMacroNames(MacroNameSet & macros) const
2015 d->macro_lock = true;
2017 // loop over macro names
2018 Impl::NamePositionScopeMacroMap::iterator nameIt
2019 = d->macros.begin();
2020 Impl::NamePositionScopeMacroMap::iterator nameEnd
2022 for (; nameIt != nameEnd; ++nameIt)
2023 macros.insert(nameIt->first);
2025 // loop over children
2026 Impl::BufferPositionMap::iterator it
2027 = d->children_positions.begin();
2028 Impl::BufferPositionMap::iterator end
2029 = d->children_positions.end();
2030 for (; it != end; ++it)
2031 it->first->listMacroNames(macros);
2034 if (d->parent_buffer)
2035 d->parent_buffer->listMacroNames(macros);
2037 d->macro_lock = false;
2041 void Buffer::writeParentMacros(odocstream & os) const
2043 if (!d->parent_buffer)
2046 // collect macro names
2048 d->parent_buffer->listMacroNames(names);
2050 // resolve and output them
2051 MacroNameSet::iterator it = names.begin();
2052 MacroNameSet::iterator end = names.end();
2053 for (; it != end; ++it) {
2055 MacroData const * data =
2056 d->parent_buffer->getMacro(*it, *this, false);
2058 data->write(os, true);
2063 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2066 //FIXME: This does not work for child documents yet.
2067 BOOST_ASSERT(code == CITE_CODE || code == REF_CODE);
2068 // Check if the label 'from' appears more than once
2069 vector<docstring> labels;
2072 if (code == CITE_CODE) {
2074 keys.fillWithBibKeys(this);
2075 BiblioInfo::const_iterator bit = keys.begin();
2076 BiblioInfo::const_iterator bend = keys.end();
2078 for (; bit != bend; ++bit)
2080 labels.push_back(bit->first);
2083 getLabelList(labels);
2084 paramName = "reference";
2087 if (count(labels.begin(), labels.end(), from) > 1)
2090 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2091 if (it->lyxCode() == code) {
2092 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2093 docstring const oldValue = inset.getParam(paramName);
2094 if (oldValue == from)
2095 inset.setParam(paramName, to);
2101 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2102 pit_type par_end, bool full_source)
2104 OutputParams runparams(¶ms().encoding());
2105 runparams.nice = true;
2106 runparams.flavor = OutputParams::LATEX;
2107 runparams.linelen = lyxrc.plaintext_linelen;
2108 // No side effect of file copying and image conversion
2109 runparams.dryrun = true;
2113 os << "% " << _("Preview source code") << "\n\n";
2114 d->texrow.newline();
2115 d->texrow.newline();
2117 writeLaTeXSource(os, filePath(), runparams, true, true);
2119 writeDocBookSource(os, absFileName(), runparams, false);
2122 runparams.par_begin = par_begin;
2123 runparams.par_end = par_end;
2124 if (par_begin + 1 == par_end)
2126 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2130 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2131 convert<docstring>(par_begin),
2132 convert<docstring>(par_end - 1))
2134 d->texrow.newline();
2135 d->texrow.newline();
2136 // output paragraphs
2138 latexParagraphs(*this, text(), os, d->texrow, runparams);
2141 docbookParagraphs(paragraphs(), *this, os, runparams);
2147 ErrorList & Buffer::errorList(string const & type) const
2149 static ErrorList emptyErrorList;
2150 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2151 if (I == d->errorLists.end())
2152 return emptyErrorList;
2158 void Buffer::structureChanged() const
2161 gui_->structureChanged();
2165 void Buffer::errors(string const & err) const
2172 void Buffer::message(docstring const & msg) const
2179 void Buffer::setBusy(bool on) const
2186 void Buffer::setReadOnly(bool on) const
2189 d->wa_->setReadOnly(on);
2193 void Buffer::updateTitles() const
2196 d->wa_->updateTitles();
2200 void Buffer::resetAutosaveTimers() const
2203 gui_->resetAutosaveTimers();
2207 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2216 class AutoSaveBuffer : public ForkedProcess {
2219 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2220 : buffer_(buffer), fname_(fname) {}
2222 virtual boost::shared_ptr<ForkedProcess> clone() const
2224 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2229 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2230 from_utf8(fname_.absFilename())));
2231 return run(DontWait);
2235 virtual int generateChild();
2237 Buffer const & buffer_;
2242 int AutoSaveBuffer::generateChild()
2244 // tmp_ret will be located (usually) in /tmp
2245 // will that be a problem?
2246 // Note that this calls ForkedCalls::fork(), so it's
2247 // ok cross-platform.
2248 pid_t const pid = fork();
2249 // If you want to debug the autosave
2250 // you should set pid to -1, and comment out the fork.
2251 if (pid != 0 && pid != -1)
2254 // pid = -1 signifies that lyx was unable
2255 // to fork. But we will do the save
2257 bool failed = false;
2258 FileName const tmp_ret = FileName::tempName("lyxauto");
2259 if (!tmp_ret.empty()) {
2260 buffer_.writeFile(tmp_ret);
2261 // assume successful write of tmp_ret
2262 if (!tmp_ret.moveTo(fname_))
2268 // failed to write/rename tmp_ret so try writing direct
2269 if (!buffer_.writeFile(fname_)) {
2270 // It is dangerous to do this in the child,
2271 // but safe in the parent, so...
2272 if (pid == -1) // emit message signal.
2273 buffer_.message(_("Autosave failed!"));
2277 if (pid == 0) // we are the child so...
2286 // Perfect target for a thread...
2287 void Buffer::autoSave() const
2289 if (isBakClean() || isReadonly()) {
2290 // We don't save now, but we'll try again later
2291 resetAutosaveTimers();
2295 // emit message signal.
2296 message(_("Autosaving current document..."));
2298 // create autosave filename
2299 string fname = filePath();
2301 fname += d->filename.onlyFileName();
2304 AutoSaveBuffer autosave(*this, FileName(fname));
2308 resetAutosaveTimers();
2312 void Buffer::resetChildDocuments(bool close_them) const
2314 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2315 if (it->lyxCode() != INCLUDE_CODE)
2317 InsetCommand const & inset = static_cast<InsetCommand const &>(*it);
2318 InsetCommandParams const & ip = inset.params();
2320 resetParentBuffer(this, ip, close_them);
2323 if (use_gui && masterBuffer() == this)
2324 updateLabels(*this);
2326 // clear references to children in macro tables
2327 d->children_positions.clear();
2328 d->position_to_children.clear();
2332 void Buffer::loadChildDocuments() const
2334 bool parse_error = false;
2336 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2337 if (it->lyxCode() != INCLUDE_CODE)
2339 InsetCommand const & inset = static_cast<InsetCommand const &>(*it);
2340 InsetCommandParams const & ip = inset.params();
2341 Buffer * child = loadIfNeeded(*this, ip);
2344 parse_error |= !child->errorList("Parse").empty();
2345 child->loadChildDocuments();
2348 if (use_gui && masterBuffer() == this)
2349 updateLabels(*this);
2355 string Buffer::bufferFormat() const
2365 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2366 string & result_file) const
2368 string backend_format;
2369 OutputParams runparams(¶ms().encoding());
2370 runparams.flavor = OutputParams::LATEX;
2371 runparams.linelen = lyxrc.plaintext_linelen;
2372 vector<string> backs = backends();
2373 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2374 // Get shortest path to format
2375 Graph::EdgePath path;
2376 for (vector<string>::const_iterator it = backs.begin();
2377 it != backs.end(); ++it) {
2378 Graph::EdgePath p = theConverters().getPath(*it, format);
2379 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2380 backend_format = *it;
2385 runparams.flavor = theConverters().getFlavor(path);
2387 Alert::error(_("Couldn't export file"),
2388 bformat(_("No information for exporting the format %1$s."),
2389 formats.prettyName(format)));
2393 backend_format = format;
2394 // FIXME: Don't hardcode format names here, but use a flag
2395 if (backend_format == "pdflatex")
2396 runparams.flavor = OutputParams::PDFLATEX;
2399 string filename = latexName(false);
2400 filename = addName(temppath(), filename);
2401 filename = changeExtension(filename,
2402 formats.extension(backend_format));
2405 updateMacroInstances();
2407 // Plain text backend
2408 if (backend_format == "text")
2409 writePlaintextFile(*this, FileName(filename), runparams);
2411 else if (backend_format == "lyx")
2412 writeFile(FileName(filename));
2414 else if (isDocBook()) {
2415 runparams.nice = !put_in_tempdir;
2416 makeDocBookFile(FileName(filename), runparams);
2419 else if (backend_format == format) {
2420 runparams.nice = true;
2421 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2423 } else if (!lyxrc.tex_allows_spaces
2424 && contains(filePath(), ' ')) {
2425 Alert::error(_("File name error"),
2426 _("The directory path to the document cannot contain spaces."));
2429 runparams.nice = false;
2430 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2434 string const error_type = (format == "program")
2435 ? "Build" : bufferFormat();
2436 string const ext = formats.extension(format);
2437 FileName const tmp_result_file(changeExtension(filename, ext));
2438 bool const success = theConverters().convert(this, FileName(filename),
2439 tmp_result_file, FileName(absFileName()), backend_format, format,
2440 errorList(error_type));
2441 // Emit the signal to show the error list.
2442 if (format != backend_format)
2447 if (put_in_tempdir) {
2448 result_file = tmp_result_file.absFilename();
2452 result_file = changeExtension(absFileName(), ext);
2453 // We need to copy referenced files (e. g. included graphics
2454 // if format == "dvi") to the result dir.
2455 vector<ExportedFile> const files =
2456 runparams.exportdata->externalFiles(format);
2457 string const dest = onlyPath(result_file);
2458 CopyStatus status = SUCCESS;
2459 for (vector<ExportedFile>::const_iterator it = files.begin();
2460 it != files.end() && status != CANCEL; ++it) {
2461 string const fmt = formats.getFormatFromFile(it->sourceName);
2462 status = copyFile(fmt, it->sourceName,
2463 makeAbsPath(it->exportName, dest),
2464 it->exportName, status == FORCE);
2466 if (status == CANCEL) {
2467 message(_("Document export cancelled."));
2468 } else if (tmp_result_file.exists()) {
2469 // Finally copy the main file
2470 status = copyFile(format, tmp_result_file,
2471 FileName(result_file), result_file,
2473 message(bformat(_("Document exported as %1$s "
2475 formats.prettyName(format),
2476 makeDisplayPath(result_file)));
2478 // This must be a dummy converter like fax (bug 1888)
2479 message(bformat(_("Document exported as %1$s"),
2480 formats.prettyName(format)));
2487 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2490 return doExport(format, put_in_tempdir, result_file);
2494 bool Buffer::preview(string const & format) const
2497 if (!doExport(format, true, result_file))
2499 return formats.view(*this, FileName(result_file), format);
2503 bool Buffer::isExportable(string const & format) const
2505 vector<string> backs = backends();
2506 for (vector<string>::const_iterator it = backs.begin();
2507 it != backs.end(); ++it)
2508 if (theConverters().isReachable(*it, format))
2514 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2516 vector<string> backs = backends();
2517 vector<Format const *> result =
2518 theConverters().getReachable(backs[0], only_viewable, true);
2519 for (vector<string>::const_iterator it = backs.begin() + 1;
2520 it != backs.end(); ++it) {
2521 vector<Format const *> r =
2522 theConverters().getReachable(*it, only_viewable, false);
2523 result.insert(result.end(), r.begin(), r.end());
2529 vector<string> Buffer::backends() const
2532 if (params().getTextClass().isTeXClassAvailable()) {
2533 v.push_back(bufferFormat());
2534 // FIXME: Don't hardcode format names here, but use a flag
2535 if (v.back() == "latex")
2536 v.push_back("pdflatex");
2538 v.push_back("text");
2544 bool Buffer::readFileHelper(FileName const & s)
2546 // File information about normal file
2548 docstring const file = makeDisplayPath(s.absFilename(), 50);
2549 docstring text = bformat(_("The specified document\n%1$s"
2550 "\ncould not be read."), file);
2551 Alert::error(_("Could not read document"), text);
2555 // Check if emergency save file exists and is newer.
2556 FileName const e(s.absFilename() + ".emergency");
2558 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2559 docstring const file = makeDisplayPath(s.absFilename(), 20);
2560 docstring const text =
2561 bformat(_("An emergency save of the document "
2563 "Recover emergency save?"), file);
2564 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2565 _("&Recover"), _("&Load Original"),
2569 // the file is not saved if we load the emergency file.
2579 // Now check if autosave file is newer.
2580 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2582 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2583 docstring const file = makeDisplayPath(s.absFilename(), 20);
2584 docstring const text =
2585 bformat(_("The backup of the document "
2586 "%1$s is newer.\n\nLoad the "
2587 "backup instead?"), file);
2588 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2589 _("&Load backup"), _("Load &original"),
2593 // the file is not saved if we load the autosave file.
2597 // Here we delete the autosave
2608 bool Buffer::loadLyXFile(FileName const & s)
2610 if (s.isReadableFile()) {
2611 if (readFileHelper(s)) {
2612 lyxvc().file_found_hook(s);
2613 if (!s.isWritable())
2618 docstring const file = makeDisplayPath(s.absFilename(), 20);
2619 // Here we probably should run
2620 if (LyXVC::file_not_found_hook(s)) {
2621 docstring const text =
2622 bformat(_("Do you want to retrieve the document"
2623 " %1$s from version control?"), file);
2624 int const ret = Alert::prompt(_("Retrieve from version control?"),
2625 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2628 // How can we know _how_ to do the checkout?
2629 // With the current VC support it has to be,
2630 // a RCS file since CVS do not have special ,v files.
2632 return loadLyXFile(s);
2640 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2642 TeXErrors::Errors::const_iterator cit = terr.begin();
2643 TeXErrors::Errors::const_iterator end = terr.end();
2645 for (; cit != end; ++cit) {
2648 int errorRow = cit->error_in_line;
2649 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2655 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2656 } while (found && id_start == id_end && pos_start == pos_end);
2658 errorList.push_back(ErrorItem(cit->error_desc,
2659 cit->error_text, id_start, pos_start, pos_end));