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 "BaseClassList.h"
18 #include "BiblioInfo.h"
19 #include "BranchList.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
25 #include "Converter.h"
27 #include "DocIterator.h"
28 #include "EmbeddedFiles.h"
30 #include "ErrorList.h"
33 #include "FuncRequest.h"
34 #include "InsetIterator.h"
35 #include "InsetList.h"
37 #include "LaTeXFeatures.h"
41 #include "LyXAction.h"
45 #include "output_docbook.h"
47 #include "output_latex.h"
48 #include "output_plaintext.h"
49 #include "paragraph_funcs.h"
50 #include "Paragraph.h"
51 #include "ParagraphParameters.h"
52 #include "ParIterator.h"
53 #include "PDFOptions.h"
57 #include "TexStream.h"
59 #include "TocBackend.h"
61 #include "VCBackend.h"
65 #include "insets/InsetBibitem.h"
66 #include "insets/InsetBibtex.h"
67 #include "insets/InsetInclude.h"
68 #include "insets/InsetText.h"
70 #include "mathed/MacroTable.h"
71 #include "mathed/MathMacroTemplate.h"
72 #include "mathed/MathSupport.h"
74 #include "frontends/alert.h"
75 #include "frontends/Delegates.h"
76 #include "frontends/WorkAreaManager.h"
78 #include "graphics/Previews.h"
80 #include "support/convert.h"
81 #include "support/debug.h"
82 #include "support/ExceptionMessage.h"
83 #include "support/FileName.h"
84 #include "support/FileNameList.h"
85 #include "support/filetools.h"
86 #include "support/ForkedCalls.h"
87 #include "support/gettext.h"
88 #include "support/gzstream.h"
89 #include "support/lstrings.h"
90 #include "support/lyxalgo.h"
91 #include "support/os.h"
92 #include "support/Package.h"
93 #include "support/Path.h"
94 #include "support/textutils.h"
95 #include "support/types.h"
96 #include "support/FileZipListDir.h"
98 #include <boost/bind.hpp>
99 #include <boost/shared_ptr.hpp>
108 using namespace lyx::support;
112 namespace Alert = frontend::Alert;
113 namespace os = support::os;
117 int const LYX_FORMAT = 315; // Richard Heck: column separation
122 typedef map<string, bool> DepClean;
127 Impl(Buffer & parent, FileName const & file, bool readonly);
140 mutable TexRow texrow;
141 Buffer const * parent_buffer;
143 /// need to regenerate .tex?
147 mutable bool lyx_clean;
149 /// is autosave needed?
150 mutable bool bak_clean;
152 /// is this a unnamed file (New...)?
158 /// name of the file the buffer is associated with.
161 /** Set to true only when the file is fully loaded.
162 * Used to prevent the premature generation of previews
163 * and by the citation inset.
165 bool file_fully_loaded;
167 /// our Text that should be wrapped in an InsetText
171 mutable TocBackend toc_backend;
174 typedef pair<DocIterator, MacroData> ScopeMacro;
175 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
176 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
177 NamePositionScopeMacroMap macros;
180 /// positions of child buffers in the buffer
181 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
182 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
183 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
184 BufferPositionMap children_positions;
185 PositionScopeBufferMap position_to_children;
187 /// Container for all sort of Buffer dependant errors.
188 map<string, ErrorList> errorLists;
190 /// all embedded files of this buffer
191 EmbeddedFileList embedded_files;
193 /// timestamp and checksum used to test if the file has been externally
194 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
196 unsigned long checksum_;
199 frontend::WorkAreaManager * wa_;
204 /// A cache for the bibfiles (including bibfiles of loaded child
205 /// documents), needed for appropriate update of natbib labels.
206 mutable EmbeddedFileList bibfilesCache_;
212 /// Creates the per buffer temporary directory
213 static FileName createBufferTmpDir()
216 // We are in our own directory. Why bother to mangle name?
217 // In fact I wrote this code to circumvent a problematic behaviour
218 // (bug?) of EMX mkstemp().
219 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
220 convert<string>(count++));
222 if (!tmpfl.createDirectory(0777)) {
223 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
224 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
225 from_utf8(tmpfl.absFilename())));
231 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
232 : parent_buffer(0), lyx_clean(true), bak_clean(true), unnamed(false),
233 read_only(readonly_), filename(file), file_fully_loaded(false),
234 inset(params), toc_backend(&parent), macro_lock(false),
235 embedded_files(), timestamp_(0), checksum_(0), wa_(0),
238 temppath = createBufferTmpDir();
239 inset.setAutoBreakRows(true);
240 lyxvc.setBuffer(&parent);
242 wa_ = new frontend::WorkAreaManager;
246 Buffer::Buffer(string const & file, bool readonly)
247 : d(new Impl(*this, FileName(file), readonly)), gui_(0)
249 LYXERR(Debug::INFO, "Buffer::Buffer()");
251 d->inset.getText(0)->setMacrocontextPosition(par_iterator_begin());
257 LYXERR(Debug::INFO, "Buffer::~Buffer()");
258 // here the buffer should take care that it is
259 // saved properly, before it goes into the void.
261 // GuiView already destroyed
264 Buffer const * master = masterBuffer();
265 if (master != this && use_gui) {
266 // We are closing buf which was a child document so we
267 // must update the labels and section numbering of its master
269 updateLabels(*master);
270 master->updateMacros();
273 resetChildDocuments(false);
275 if (!d->temppath.destroyDirectory()) {
276 Alert::warning(_("Could not remove temporary directory"),
277 bformat(_("Could not remove the temporary directory %1$s"),
278 from_utf8(d->temppath.absFilename())));
281 // Remove any previewed LaTeX snippets associated with this buffer.
282 graphics::Previews::get().removeLoader(*this);
288 void Buffer::changed() const
295 frontend::WorkAreaManager & Buffer::workAreaManager() const
297 BOOST_ASSERT(d->wa_);
302 Text & Buffer::text() const
304 return const_cast<Text &>(d->inset.text_);
308 Inset & Buffer::inset() const
310 return const_cast<InsetText &>(d->inset);
314 BufferParams & Buffer::params()
320 BufferParams const & Buffer::params() const
326 ParagraphList & Buffer::paragraphs()
328 return text().paragraphs();
332 ParagraphList const & Buffer::paragraphs() const
334 return text().paragraphs();
338 LyXVC & Buffer::lyxvc()
344 LyXVC const & Buffer::lyxvc() const
350 string const Buffer::temppath() const
352 return d->temppath.absFilename();
356 TexRow const & Buffer::texrow() const
362 TocBackend & Buffer::tocBackend() const
364 return d->toc_backend;
368 EmbeddedFileList & Buffer::embeddedFiles()
370 return d->embedded_files;
374 EmbeddedFileList const & Buffer::embeddedFiles() const
376 return d->embedded_files;
380 bool Buffer::embedded() const
382 return params().embedded;
386 Undo & Buffer::undo()
392 string Buffer::latexName(bool const no_path) const
394 FileName latex_name = makeLatexName(d->filename);
395 return no_path ? latex_name.onlyFileName()
396 : latex_name.absFilename();
400 string Buffer::logName(LogType * type) const
402 string const filename = latexName(false);
404 if (filename.empty()) {
410 string const path = temppath();
412 FileName const fname(addName(temppath(),
413 onlyFilename(changeExtension(filename,
415 FileName const bname(
416 addName(path, onlyFilename(
417 changeExtension(filename,
418 formats.extension("literate") + ".out"))));
420 // If no Latex log or Build log is newer, show Build log
422 if (bname.exists() &&
423 (!fname.exists() || fname.lastModified() < bname.lastModified())) {
424 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
427 return bname.absFilename();
429 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
432 return fname.absFilename();
436 void Buffer::setReadonly(bool const flag)
438 if (d->read_only != flag) {
445 void Buffer::setFileName(string const & newfile)
447 d->filename = makeAbsPath(newfile);
448 setReadonly(d->filename.isReadOnly());
453 int Buffer::readHeader(Lexer & lex)
455 int unknown_tokens = 0;
457 int begin_header_line = -1;
459 // Initialize parameters that may be/go lacking in header:
460 params().branchlist().clear();
461 params().preamble.erase();
462 params().options.erase();
463 params().float_placement.erase();
464 params().paperwidth.erase();
465 params().paperheight.erase();
466 params().leftmargin.erase();
467 params().rightmargin.erase();
468 params().topmargin.erase();
469 params().bottommargin.erase();
470 params().headheight.erase();
471 params().headsep.erase();
472 params().footskip.erase();
473 params().columnsep.erase();
474 params().listings_params.clear();
475 params().clearLayoutModules();
476 params().pdfoptions().clear();
478 for (int i = 0; i < 4; ++i) {
479 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
480 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
483 ErrorList & errorList = d->errorLists["Parse"];
487 string const token = lex.getString();
492 if (token == "\\end_header")
496 if (token == "\\begin_header") {
497 begin_header_line = line;
501 LYXERR(Debug::PARSER, "Handling document header token: `"
504 string unknown = params().readToken(lex, token, d->filename.onlyPath());
505 if (!unknown.empty()) {
506 if (unknown[0] != '\\' && token == "\\textclass") {
507 Alert::warning(_("Unknown document class"),
508 bformat(_("Using the default document class, because the "
509 "class %1$s is unknown."), from_utf8(unknown)));
512 docstring const s = bformat(_("Unknown token: "
516 errorList.push_back(ErrorItem(_("Document header error"),
521 if (begin_header_line) {
522 docstring const s = _("\\begin_header is missing");
523 errorList.push_back(ErrorItem(_("Document header error"),
527 params().makeTextClass();
529 return unknown_tokens;
534 // changed to be public and have one parameter
535 // Returns false if "\end_document" is not read (Asger)
536 bool Buffer::readDocument(Lexer & lex)
538 ErrorList & errorList = d->errorLists["Parse"];
542 string const token = lex.getString();
543 if (token != "\\begin_document") {
544 docstring const s = _("\\begin_document is missing");
545 errorList.push_back(ErrorItem(_("Document header error"),
549 // we are reading in a brand new document
550 BOOST_ASSERT(paragraphs().empty());
554 if (params().outputChanges) {
555 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
556 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
557 LaTeXFeatures::isAvailable("xcolor");
559 if (!dvipost && !xcolorsoul) {
560 Alert::warning(_("Changes not shown in LaTeX output"),
561 _("Changes will not be highlighted in LaTeX output, "
562 "because neither dvipost nor xcolor/soul are installed.\n"
563 "Please install these packages or redefine "
564 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
565 } else if (!xcolorsoul) {
566 Alert::warning(_("Changes not shown in LaTeX output"),
567 _("Changes will not be highlighted in LaTeX output "
568 "when using pdflatex, because xcolor and soul are not installed.\n"
569 "Please install both packages or redefine "
570 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
575 bool const res = text().read(*this, lex, errorList, &(d->inset));
578 updateMacroInstances();
583 // needed to insert the selection
584 void Buffer::insertStringAsLines(ParagraphList & pars,
585 pit_type & pit, pos_type & pos,
586 Font const & fn, docstring const & str, bool autobreakrows)
590 // insert the string, don't insert doublespace
591 bool space_inserted = true;
592 for (docstring::const_iterator cit = str.begin();
593 cit != str.end(); ++cit) {
594 Paragraph & par = pars[pit];
596 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
597 breakParagraph(params(), pars, pit, pos,
598 par.layout()->isEnvironment());
601 space_inserted = true;
605 // do not insert consecutive spaces if !free_spacing
606 } else if ((*cit == ' ' || *cit == '\t') &&
607 space_inserted && !par.isFreeSpacing()) {
609 } else if (*cit == '\t') {
610 if (!par.isFreeSpacing()) {
611 // tabs are like spaces here
612 par.insertChar(pos, ' ', font, params().trackChanges);
614 space_inserted = true;
616 const pos_type n = 8 - pos % 8;
617 for (pos_type i = 0; i < n; ++i) {
618 par.insertChar(pos, ' ', font, params().trackChanges);
621 space_inserted = true;
623 } else if (!isPrintable(*cit)) {
624 // Ignore unprintables
627 // just insert the character
628 par.insertChar(pos, *cit, font, params().trackChanges);
630 space_inserted = (*cit == ' ');
637 bool Buffer::readString(string const & s)
639 params().compressed = false;
641 // remove dummy empty par
642 paragraphs().clear();
646 FileName const name = FileName::tempName();
647 switch (readFile(lex, name, true)) {
651 // We need to call lyx2lyx, so write the input to a file
652 ofstream os(name.toFilesystemEncoding().c_str());
655 return readFile(name);
665 bool Buffer::readFile(FileName const & filename)
667 FileName fname(filename);
668 // Check if the file is compressed.
669 string format = filename.guessFormatFromContents();
670 if (format == "zip") {
671 // decompress to a temp directory
672 LYXERR(Debug::FILES, filename << " is in zip format. Unzip to " << temppath());
673 ::unzipToDir(filename.toFilesystemEncoding(), temppath());
675 FileName lyxfile(addName(temppath(), "content.lyx"));
676 // if both manifest.txt and file.lyx exist, this is am embedded file
677 if (lyxfile.exists()) {
678 // if in bundled format, save checksum of the compressed file, not content.lyx
679 saveCheckSum(filename);
680 params().embedded = true;
684 // The embedded lyx file can also be compressed, for backward compatibility
685 format = fname.guessFormatFromContents();
686 if (format == "gzip" || format == "zip" || format == "compress")
687 params().compressed = true;
689 // remove dummy empty par
690 paragraphs().clear();
693 if (readFile(lex, fname) != success)
700 bool Buffer::isFullyLoaded() const
702 return d->file_fully_loaded;
706 void Buffer::setFullyLoaded(bool value)
708 d->file_fully_loaded = value;
712 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
715 BOOST_ASSERT(!filename.empty());
718 Alert::error(_("Document could not be read"),
719 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
724 string const token = lex.getString();
727 Alert::error(_("Document could not be read"),
728 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
732 // the first token _must_ be...
733 if (token != "\\lyxformat") {
734 lyxerr << "Token: " << token << endl;
736 Alert::error(_("Document format failure"),
737 bformat(_("%1$s is not a LyX document."),
738 from_utf8(filename.absFilename())));
743 string tmp_format = lex.getString();
744 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
745 // if present remove ".," from string.
746 string::size_type dot = tmp_format.find_first_of(".,");
747 //lyxerr << " dot found at " << dot << endl;
748 if (dot != string::npos)
749 tmp_format.erase(dot, 1);
750 int const file_format = convert<int>(tmp_format);
751 //lyxerr << "format: " << file_format << endl;
753 // save timestamp and checksum of the original disk file, making sure
754 // to not overwrite them with those of the file created in the tempdir
755 // when it has to be converted to the current format.
757 // Save the timestamp and checksum of disk file. If filename is an
758 // emergency file, save the timestamp and checksum of the original lyx file
759 // because isExternallyModified will check for this file. (BUG4193)
760 string diskfile = filename.absFilename();
761 if (suffixIs(diskfile, ".emergency"))
762 diskfile = diskfile.substr(0, diskfile.size() - 10);
763 saveCheckSum(FileName(diskfile));
766 if (file_format != LYX_FORMAT) {
769 // lyx2lyx would fail
772 FileName const tmpfile = FileName::tempName();
773 if (tmpfile.empty()) {
774 Alert::error(_("Conversion failed"),
775 bformat(_("%1$s is from a different"
776 " version of LyX, but a temporary"
777 " file for converting it could"
779 from_utf8(filename.absFilename())));
782 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
783 if (lyx2lyx.empty()) {
784 Alert::error(_("Conversion script not found"),
785 bformat(_("%1$s is from a different"
786 " version of LyX, but the"
787 " conversion script lyx2lyx"
788 " could not be found."),
789 from_utf8(filename.absFilename())));
792 ostringstream command;
793 command << os::python()
794 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
795 << " -t " << convert<string>(LYX_FORMAT)
796 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
797 << ' ' << quoteName(filename.toFilesystemEncoding());
798 string const command_str = command.str();
800 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
802 cmd_ret const ret = runCommand(command_str);
803 if (ret.first != 0) {
804 Alert::error(_("Conversion script failed"),
805 bformat(_("%1$s is from a different version"
806 " of LyX, but the lyx2lyx script"
807 " failed to convert it."),
808 from_utf8(filename.absFilename())));
811 bool const ret = readFile(tmpfile);
812 // Do stuff with tmpfile name and buffer name here.
813 return ret ? success : failure;
818 if (readDocument(lex)) {
819 Alert::error(_("Document format failure"),
820 bformat(_("%1$s ended unexpectedly, which means"
821 " that it is probably corrupted."),
822 from_utf8(filename.absFilename())));
825 d->file_fully_loaded = true;
830 // Should probably be moved to somewhere else: BufferView? LyXView?
831 bool Buffer::save() const
833 // We don't need autosaves in the immediate future. (Asger)
834 resetAutosaveTimers();
836 string const encodedFilename = d->filename.toFilesystemEncoding();
839 bool madeBackup = false;
841 // make a backup if the file already exists
842 if (lyxrc.make_backup && fileName().exists()) {
843 backupName = FileName(absFileName() + '~');
844 if (!lyxrc.backupdir_path.empty()) {
845 string const mangledName =
846 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
847 backupName = FileName(addName(lyxrc.backupdir_path,
850 if (fileName().copyTo(backupName)) {
853 Alert::error(_("Backup failure"),
854 bformat(_("Cannot create backup file %1$s.\n"
855 "Please check whether the directory exists and is writeable."),
856 from_utf8(backupName.absFilename())));
857 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
861 // ask if the disk file has been externally modified (use checksum method)
862 if (fileName().exists() && isExternallyModified(checksum_method)) {
863 docstring const file = makeDisplayPath(absFileName(), 20);
864 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
865 "you want to overwrite this file?"), file);
866 int const ret = Alert::prompt(_("Overwrite modified file?"),
867 text, 1, 1, _("&Overwrite"), _("&Cancel"));
872 if (writeFile(d->filename)) {
876 // Saving failed, so backup is not backup
878 backupName.moveTo(d->filename);
884 bool Buffer::writeFile(FileName const & fname) const
886 if (d->read_only && fname == d->filename)
892 if (params().embedded)
893 // first write the .lyx file to the temporary directory
894 content = FileName(addName(temppath(), "content.lyx"));
898 docstring const str = bformat(_("Saving document %1$s..."),
899 makeDisplayPath(content.absFilename()));
902 if (params().compressed) {
903 gz::ogzstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
904 retval = ofs && write(ofs);
906 ofstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
907 retval = ofs && write(ofs);
911 message(str + _(" could not write file!."));
915 removeAutosaveFile(d->filename.absFilename());
917 if (params().embedded) {
918 message(str + _(" writing embedded files!."));
919 // if embedding is enabled, write file.lyx and all the embedded files
920 // to the zip file fname.
921 if (!d->embedded_files.writeFile(fname, *this)) {
922 message(str + _(" could not write embedded files!."));
926 saveCheckSum(d->filename);
927 message(str + _(" done."));
933 bool Buffer::write(ostream & ofs) const
936 // Use the standard "C" locale for file output.
937 ofs.imbue(locale::classic());
940 // The top of the file should not be written by params().
942 // write out a comment in the top of the file
943 ofs << "#LyX " << lyx_version
944 << " created this file. For more info see http://www.lyx.org/\n"
945 << "\\lyxformat " << LYX_FORMAT << "\n"
946 << "\\begin_document\n";
948 /// For each author, set 'used' to true if there is a change
949 /// by this author in the document; otherwise set it to 'false'.
950 AuthorList::Authors::const_iterator a_it = params().authors().begin();
951 AuthorList::Authors::const_iterator a_end = params().authors().end();
952 for (; a_it != a_end; ++a_it)
953 a_it->second.setUsed(false);
955 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
956 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
957 for ( ; it != end; ++it)
958 it->checkAuthors(params().authors());
960 // now write out the buffer parameters.
961 ofs << "\\begin_header\n";
962 params().writeFile(ofs);
963 ofs << "\\end_header\n";
966 ofs << "\n\\begin_body\n";
967 text().write(*this, ofs);
968 ofs << "\n\\end_body\n";
970 // Write marker that shows file is complete
971 ofs << "\\end_document" << endl;
973 // Shouldn't really be needed....
976 // how to check if close went ok?
977 // Following is an attempt... (BE 20001011)
979 // good() returns false if any error occured, including some
981 // bad() returns true if something bad happened in the buffer,
982 // which should include file system full errors.
987 lyxerr << "File was not closed properly." << endl;
994 bool Buffer::makeLaTeXFile(FileName const & fname,
995 string const & original_path,
996 OutputParams const & runparams,
997 bool output_preamble, bool output_body) const
999 string const encoding = runparams.encoding->iconvName();
1000 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1003 try { ofs.reset(encoding); }
1004 catch (iconv_codecvt_facet_exception & e) {
1005 lyxerr << "Caught iconv exception: " << e.what() << endl;
1006 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1007 "verify that the support software for your encoding (%1$s) is "
1008 "properly installed"), from_ascii(encoding)));
1011 if (!openFileWrite(ofs, fname))
1014 //TexStream ts(ofs.rdbuf(), &texrow());
1015 ErrorList & errorList = d->errorLists["Export"];
1017 bool failed_export = false;
1020 writeLaTeXSource(ofs, original_path,
1021 runparams, output_preamble, output_body);
1023 catch (EncodingException & e) {
1024 odocstringstream ods;
1025 ods.put(e.failed_char);
1027 oss << "0x" << hex << e.failed_char << dec;
1028 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1029 " (code point %2$s)"),
1030 ods.str(), from_utf8(oss.str()));
1031 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1032 "representable in the chosen encoding.\n"
1033 "Changing the document encoding to utf8 could help."),
1034 e.par_id, e.pos, e.pos + 1));
1035 failed_export = true;
1037 catch (iconv_codecvt_facet_exception & e) {
1038 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1039 _(e.what()), -1, 0, 0));
1040 failed_export = true;
1042 catch (exception const & e) {
1043 errorList.push_back(ErrorItem(_("conversion failed"),
1044 _(e.what()), -1, 0, 0));
1045 failed_export = true;
1048 lyxerr << "Caught some really weird exception..." << endl;
1049 LyX::cref().exit(1);
1054 failed_export = true;
1055 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1059 return !failed_export;
1063 void Buffer::writeLaTeXSource(odocstream & os,
1064 string const & original_path,
1065 OutputParams const & runparams_in,
1066 bool const output_preamble, bool const output_body) const
1068 OutputParams runparams = runparams_in;
1070 // validate the buffer.
1071 LYXERR(Debug::LATEX, " Validating buffer...");
1072 LaTeXFeatures features(*this, params(), runparams);
1074 LYXERR(Debug::LATEX, " Buffer validation done.");
1076 // The starting paragraph of the coming rows is the
1077 // first paragraph of the document. (Asger)
1078 if (output_preamble && runparams.nice) {
1079 os << "%% LyX " << lyx_version << " created this file. "
1080 "For more info, see http://www.lyx.org/.\n"
1081 "%% Do not edit unless you really know what "
1083 d->texrow.newline();
1084 d->texrow.newline();
1086 LYXERR(Debug::INFO, "lyx document header finished");
1087 // There are a few differences between nice LaTeX and usual files:
1088 // usual is \batchmode and has a
1089 // special input@path to allow the including of figures
1090 // with either \input or \includegraphics (what figinsets do).
1091 // input@path is set when the actual parameter
1092 // original_path is set. This is done for usual tex-file, but not
1093 // for nice-latex-file. (Matthias 250696)
1094 // Note that input@path is only needed for something the user does
1095 // in the preamble, included .tex files or ERT, files included by
1096 // LyX work without it.
1097 if (output_preamble) {
1098 if (!runparams.nice) {
1099 // code for usual, NOT nice-latex-file
1100 os << "\\batchmode\n"; // changed
1101 // from \nonstopmode
1102 d->texrow.newline();
1104 if (!original_path.empty()) {
1106 // We don't know the encoding of inputpath
1107 docstring const inputpath = from_utf8(latex_path(original_path));
1108 os << "\\makeatletter\n"
1109 << "\\def\\input@path{{"
1110 << inputpath << "/}}\n"
1111 << "\\makeatother\n";
1112 d->texrow.newline();
1113 d->texrow.newline();
1114 d->texrow.newline();
1117 // Write the preamble
1118 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1124 os << "\\begin{document}\n";
1125 d->texrow.newline();
1126 } // output_preamble
1128 d->texrow.start(paragraphs().begin()->id(), 0);
1130 LYXERR(Debug::INFO, "preamble finished, now the body.");
1132 // load children, if not already done.
1133 // This includes an updateMacro() call.
1134 // Don't move this behind the parent_buffer=0 code below,
1135 // because then the macros will not get the right "redefinition"
1136 // flag as they don't see the parent macros which are output before.
1137 loadChildDocuments();
1139 // fold macros if possible, still with parent buffer as the
1140 // macros will be put in the prefix anyway.
1141 updateMacroInstances();
1143 // if we are doing a real file with body, even if this is the
1144 // child of some other buffer, let's cut the link here.
1145 // This happens for example if only a child document is printed.
1146 Buffer const * save_parent = 0;
1147 if (output_preamble) {
1148 // output the macros visible for this buffer
1149 writeParentMacros(os);
1151 save_parent = d->parent_buffer;
1152 d->parent_buffer = 0;
1156 latexParagraphs(*this, text(), os, d->texrow, runparams);
1158 // Restore the parenthood if needed
1159 if (output_preamble) {
1160 d->parent_buffer = save_parent;
1162 // restore macros with correct parent buffer (especially
1163 // important for the redefinition flag which depends on the
1168 // add this just in case after all the paragraphs
1170 d->texrow.newline();
1172 if (output_preamble) {
1173 os << "\\end{document}\n";
1174 d->texrow.newline();
1175 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1177 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1179 runparams_in.encoding = runparams.encoding;
1181 // Just to be sure. (Asger)
1182 d->texrow.newline();
1184 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1185 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1189 bool Buffer::isLatex() const
1191 return params().textClass().outputType() == LATEX;
1195 bool Buffer::isLiterate() const
1197 return params().textClass().outputType() == LITERATE;
1201 bool Buffer::isDocBook() const
1203 return params().textClass().outputType() == DOCBOOK;
1207 void Buffer::makeDocBookFile(FileName const & fname,
1208 OutputParams const & runparams,
1209 bool const body_only) const
1211 LYXERR(Debug::LATEX, "makeDocBookFile...");
1214 if (!openFileWrite(ofs, fname))
1217 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1221 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1225 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1226 OutputParams const & runparams,
1227 bool const only_body) const
1229 LaTeXFeatures features(*this, params(), runparams);
1234 TextClass const & tclass = params().textClass();
1235 string const top_element = tclass.latexname();
1238 if (runparams.flavor == OutputParams::XML)
1239 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1242 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1245 if (! tclass.class_header().empty())
1246 os << from_ascii(tclass.class_header());
1247 else if (runparams.flavor == OutputParams::XML)
1248 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1249 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1251 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1253 docstring preamble = from_utf8(params().preamble);
1254 if (runparams.flavor != OutputParams::XML ) {
1255 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1256 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1257 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1258 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1261 string const name = runparams.nice
1262 ? changeExtension(absFileName(), ".sgml") : fname;
1263 preamble += features.getIncludedFiles(name);
1264 preamble += features.getLyXSGMLEntities();
1266 if (!preamble.empty()) {
1267 os << "\n [ " << preamble << " ]";
1272 string top = top_element;
1274 if (runparams.flavor == OutputParams::XML)
1275 top += params().language->code();
1277 top += params().language->code().substr(0,2);
1280 if (!params().options.empty()) {
1282 top += params().options;
1285 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1286 << " file was created by LyX " << lyx_version
1287 << "\n See http://www.lyx.org/ for more information -->\n";
1289 params().textClass().counters().reset();
1291 loadChildDocuments();
1293 sgml::openTag(os, top);
1295 docbookParagraphs(paragraphs(), *this, os, runparams);
1296 sgml::closeTag(os, top_element);
1300 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1301 // Other flags: -wall -v0 -x
1302 int Buffer::runChktex()
1306 // get LaTeX-Filename
1307 FileName const path(temppath());
1308 string const name = addName(path.absFilename(), latexName());
1309 string const org_path = filePath();
1311 PathChanger p(path); // path to LaTeX file
1312 message(_("Running chktex..."));
1314 // Generate the LaTeX file if neccessary
1315 OutputParams runparams(¶ms().encoding());
1316 runparams.flavor = OutputParams::LATEX;
1317 runparams.nice = false;
1318 makeLaTeXFile(FileName(name), org_path, runparams);
1321 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1322 int const res = chktex.run(terr); // run chktex
1325 Alert::error(_("chktex failure"),
1326 _("Could not run chktex successfully."));
1327 } else if (res > 0) {
1328 ErrorList & errlist = d->errorLists["ChkTeX"];
1330 bufferErrors(terr, errlist);
1341 void Buffer::validate(LaTeXFeatures & features) const
1343 params().validate(features);
1345 loadChildDocuments();
1347 for_each(paragraphs().begin(), paragraphs().end(),
1348 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1350 if (lyxerr.debugging(Debug::LATEX)) {
1351 features.showStruct();
1356 void Buffer::getLabelList(vector<docstring> & list) const
1358 /// if this is a child document and the parent is already loaded
1359 /// Use the parent's list instead [ale990407]
1360 Buffer const * tmp = masterBuffer();
1362 lyxerr << "masterBuffer() failed!" << endl;
1366 tmp->getLabelList(list);
1370 loadChildDocuments();
1372 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1373 it.nextInset()->getLabelList(*this, list);
1377 void Buffer::updateBibfilesCache() const
1379 // if this is a child document and the parent is already loaded
1380 // update the parent's cache instead
1381 Buffer const * tmp = masterBuffer();
1384 tmp->updateBibfilesCache();
1388 d->bibfilesCache_.clear();
1389 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1390 if (it->lyxCode() == BIBTEX_CODE) {
1391 InsetBibtex const & inset =
1392 static_cast<InsetBibtex const &>(*it);
1393 EmbeddedFileList const bibfiles = inset.getFiles(*this);
1394 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1397 } else if (it->lyxCode() == INCLUDE_CODE) {
1398 InsetInclude & inset =
1399 static_cast<InsetInclude &>(*it);
1400 inset.updateBibfilesCache(*this);
1401 EmbeddedFileList const & bibfiles =
1402 inset.getBibfilesCache(*this);
1403 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1411 EmbeddedFileList const & Buffer::getBibfilesCache() const
1413 // if this is a child document and the parent is already loaded
1414 // use the parent's cache instead
1415 Buffer const * tmp = masterBuffer();
1418 return tmp->getBibfilesCache();
1420 // We update the cache when first used instead of at loading time.
1421 if (d->bibfilesCache_.empty())
1422 const_cast<Buffer *>(this)->updateBibfilesCache();
1424 return d->bibfilesCache_;
1428 bool Buffer::isDepClean(string const & name) const
1430 DepClean::const_iterator const it = d->dep_clean.find(name);
1431 if (it == d->dep_clean.end())
1437 void Buffer::markDepClean(string const & name)
1439 d->dep_clean[name] = true;
1443 bool Buffer::dispatch(string const & command, bool * result)
1445 return dispatch(lyxaction.lookupFunc(command), result);
1449 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1451 bool dispatched = true;
1453 switch (func.action) {
1454 case LFUN_BUFFER_EXPORT: {
1455 bool const tmp = doExport(to_utf8(func.argument()), false);
1468 void Buffer::changeLanguage(Language const * from, Language const * to)
1473 for_each(par_iterator_begin(),
1475 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1479 bool Buffer::isMultiLingual() const
1481 ParConstIterator end = par_iterator_end();
1482 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1483 if (it->isMultiLingual(params()))
1490 DocIterator Buffer::getParFromID(int const id) const
1493 // John says this is called with id == -1 from undo
1494 lyxerr << "getParFromID(), id: " << id << endl;
1495 return doc_iterator_end(inset());
1498 for (DocIterator it = doc_iterator_begin(inset()); !it.atEnd(); it.forwardPar())
1499 if (it.paragraph().id() == id)
1502 return doc_iterator_end(inset());
1506 bool Buffer::hasParWithID(int const id) const
1508 return !getParFromID(id).atEnd();
1512 ParIterator Buffer::par_iterator_begin()
1514 return ParIterator(doc_iterator_begin(inset()));
1518 ParIterator Buffer::par_iterator_end()
1520 return ParIterator(doc_iterator_end(inset()));
1524 ParConstIterator Buffer::par_iterator_begin() const
1526 return lyx::par_const_iterator_begin(inset());
1530 ParConstIterator Buffer::par_iterator_end() const
1532 return lyx::par_const_iterator_end(inset());
1536 Language const * Buffer::language() const
1538 return params().language;
1542 docstring const Buffer::B_(string const & l10n) const
1544 return params().B_(l10n);
1548 bool Buffer::isClean() const
1550 return d->lyx_clean;
1554 bool Buffer::isBakClean() const
1556 return d->bak_clean;
1560 bool Buffer::isExternallyModified(CheckMethod method) const
1562 BOOST_ASSERT(d->filename.exists());
1563 // if method == timestamp, check timestamp before checksum
1564 return (method == checksum_method
1565 || d->timestamp_ != d->filename.lastModified())
1566 && d->checksum_ != d->filename.checksum();
1570 void Buffer::saveCheckSum(FileName const & file) const
1572 if (file.exists()) {
1573 d->timestamp_ = file.lastModified();
1574 d->checksum_ = file.checksum();
1576 // in the case of save to a new file.
1583 void Buffer::markClean() const
1585 if (!d->lyx_clean) {
1586 d->lyx_clean = true;
1589 // if the .lyx file has been saved, we don't need an
1591 d->bak_clean = true;
1595 void Buffer::markBakClean() const
1597 d->bak_clean = true;
1601 void Buffer::setUnnamed(bool flag)
1607 bool Buffer::isUnnamed() const
1613 // FIXME: this function should be moved to buffer_pimpl.C
1614 void Buffer::markDirty()
1617 d->lyx_clean = false;
1620 d->bak_clean = false;
1622 DepClean::iterator it = d->dep_clean.begin();
1623 DepClean::const_iterator const end = d->dep_clean.end();
1625 for (; it != end; ++it)
1630 FileName Buffer::fileName() const
1636 string Buffer::absFileName() const
1638 return d->filename.absFilename();
1642 string Buffer::filePath() const
1644 return d->filename.onlyPath().absFilename() + "/";
1648 bool Buffer::isReadonly() const
1650 return d->read_only;
1654 void Buffer::setParent(Buffer const * buffer)
1656 // Avoids recursive include.
1657 d->parent_buffer = buffer == this ? 0 : buffer;
1662 Buffer const * Buffer::parent()
1664 return d->parent_buffer;
1668 Buffer const * Buffer::masterBuffer() const
1670 if (!d->parent_buffer)
1673 return d->parent_buffer->masterBuffer();
1677 template<typename M>
1678 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
1683 typename M::iterator it = m.lower_bound(x);
1684 if (it == m.begin())
1692 MacroData const * Buffer::getBufferMacro(docstring const & name,
1693 DocIterator const & pos) const
1695 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
1697 // if paragraphs have no macro context set, pos will be empty
1701 // we haven't found anything yet
1702 DocIterator bestPos = par_iterator_begin();
1703 MacroData const * bestData = 0;
1705 // find macro definitions for name
1706 Impl::NamePositionScopeMacroMap::iterator nameIt
1707 = d->macros.find(name);
1708 if (nameIt != d->macros.end()) {
1709 // find last definition in front of pos or at pos itself
1710 Impl::PositionScopeMacroMap::const_iterator it
1711 = greatest_below(nameIt->second, pos);
1712 if (it != nameIt->second.end()) {
1714 // scope ends behind pos?
1715 if (pos < it->second.first) {
1716 // Looks good, remember this. If there
1717 // is no external macro behind this,
1718 // we found the right one already.
1719 bestPos = it->first;
1720 bestData = &it->second.second;
1724 // try previous macro if there is one
1725 if (it == nameIt->second.begin())
1732 // find macros in included files
1733 Impl::PositionScopeBufferMap::const_iterator it
1734 = greatest_below(d->position_to_children, pos);
1735 if (it == d->position_to_children.end())
1736 // no children before
1740 // do we know something better (i.e. later) already?
1741 if (it->first < bestPos )
1744 // scope ends behind pos?
1745 if (pos < it->second.first) {
1746 // look for macro in external file
1747 d->macro_lock = true;
1748 MacroData const * data
1749 = it->second.second->getMacro(name, false);
1750 d->macro_lock = false;
1752 bestPos = it->first;
1758 // try previous file if there is one
1759 if (it == d->position_to_children.begin())
1764 // return the best macro we have found
1769 MacroData const * Buffer::getMacro(docstring const & name,
1770 DocIterator const & pos, bool global) const
1775 // query buffer macros
1776 MacroData const * data = getBufferMacro(name, pos);
1780 // If there is a master buffer, query that
1781 if (d->parent_buffer) {
1782 d->macro_lock = true;
1783 MacroData const * macro
1784 = d->parent_buffer->getMacro(name, *this, false);
1785 d->macro_lock = false;
1791 data = MacroTable::globalMacros().get(name);
1800 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
1802 // set scope end behind the last paragraph
1803 DocIterator scope = par_iterator_begin();
1804 scope.pit() = scope.lastpit() + 1;
1806 return getMacro(name, scope, global);
1810 MacroData const * Buffer::getMacro(docstring const & name, Buffer const & child, bool global) const
1812 // look where the child buffer is included first
1813 Impl::BufferPositionMap::iterator it
1814 = d->children_positions.find(&child);
1815 if (it == d->children_positions.end())
1818 // check for macros at the inclusion position
1819 return getMacro(name, it->second, global);
1823 void Buffer::updateEnvironmentMacros(DocIterator & it,
1825 DocIterator & scope) const
1827 Paragraph & par = it.paragraph();
1829 = par.params().depth();
1830 Length const & leftIndent
1831 = par.params().leftIndent();
1833 // look for macros in each paragraph
1834 while (it.pit() <= lastpit) {
1835 Paragraph & par = it.paragraph();
1838 if ((par.params().depth() > depth
1839 || par.params().leftIndent() != leftIndent)
1840 && par.layout()->isEnvironment()) {
1841 updateBlockMacros(it, scope);
1845 // iterate over the insets of the current paragraph
1846 InsetList const & insets = par.insetList();
1847 InsetList::const_iterator iit = insets.begin();
1848 InsetList::const_iterator end = insets.end();
1849 for (; iit != end; ++iit) {
1850 it.pos() = iit->pos;
1852 // is it a nested text inset?
1853 if (iit->inset->asInsetText()) {
1854 // Inset needs its own scope?
1855 InsetText const * itext
1856 = iit->inset->asInsetText();
1857 bool newScope = itext->isMacroScope(*this);
1859 // scope which ends just behind die inset
1860 DocIterator insetScope = it;
1863 // collect macros in inset
1864 it.push_back(CursorSlice(*iit->inset));
1865 updateInsetMacros(it, newScope ? insetScope : scope);
1870 // is it an external file?
1871 if (iit->inset->lyxCode() == INCLUDE_CODE) {
1872 // get buffer of external file
1873 InsetCommand const & inset
1874 = static_cast<InsetCommand const &>(*iit->inset);
1875 InsetCommandParams const & ip = inset.params();
1876 d->macro_lock = true;
1877 Buffer * child = loadIfNeeded(*this, ip);
1878 d->macro_lock = false;
1882 // register its position, but only when it is
1883 // included first in the buffer
1884 if (d->children_positions.find(child)
1885 == d->children_positions.end())
1886 d->children_positions[child] = it;
1888 // register child with its scope
1889 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
1894 if (iit->inset->lyxCode() != MATHMACRO_CODE)
1898 MathMacroTemplate & macroTemplate
1899 = static_cast<MathMacroTemplate &>(*iit->inset);
1900 MacroContext mc(*this, it);
1901 macroTemplate.updateToContext(mc);
1904 bool valid = macroTemplate.validMacro();
1905 // FIXME: Should be fixNameAndCheckIfValid() in fact,
1906 // then the BufferView's cursor will be invalid in
1907 // some cases which leads to crashes.
1912 d->macros[macroTemplate.name()][it]
1913 = Impl::ScopeMacro(scope, MacroData(*this, it));
1923 void Buffer::updateBlockMacros(DocIterator & it, DocIterator & scope) const
1925 Paragraph & par = it.paragraph();
1927 // set scope for macros in this paragraph:
1928 // * either the "old" outer scope
1929 // * or the scope ending after the environment
1930 if (par.layout()->isEnvironment()) {
1931 // find end of environment block,
1932 DocIterator envEnd = it;
1933 pit_type n = it.lastpit() + 1;
1934 depth_type depth = par.params().depth();
1935 Length const & length = par.params().leftIndent();
1936 // looping through the paragraph, basically until
1937 // the layout changes or the depth gets smaller.
1938 // (the logic of output_latex.cpp's TeXEnvironment)
1941 if (envEnd.pit() == n)
1943 } while (par.layout() == envEnd.paragraph().layout()
1944 || depth < envEnd.paragraph().params().depth()
1945 || length != envEnd.paragraph().params().leftIndent());
1947 // collect macros from environment block
1948 updateEnvironmentMacros(it, envEnd.pit() - 1, envEnd);
1950 // collect macros from paragraph
1951 updateEnvironmentMacros(it, it.pit(), scope);
1956 void Buffer::updateInsetMacros(DocIterator & it, DocIterator & scope) const
1958 // look for macros in each paragraph
1959 pit_type n = it.lastpit() + 1;
1960 while (it.pit() < n)
1961 updateBlockMacros(it, scope);
1965 void Buffer::updateMacros() const
1970 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
1972 // start with empty table
1974 d->children_positions.clear();
1975 d->position_to_children.clear();
1977 // Iterate over buffer, starting with first paragraph
1978 // The scope must be bigger than any lookup DocIterator
1979 // later. For the global lookup, lastpit+1 is used, hence
1980 // we use lastpit+2 here.
1981 DocIterator it = par_iterator_begin();
1982 DocIterator outerScope = it;
1983 outerScope.pit() = outerScope.lastpit() + 2;
1984 updateInsetMacros(it, outerScope);
1988 void Buffer::updateMacroInstances() const
1990 LYXERR(Debug::MACROS, "updateMacroInstances for "
1991 << d->filename.onlyFileName());
1992 DocIterator it = doc_iterator_begin(inset());
1993 DocIterator end = doc_iterator_end(inset());
1994 for (; it != end; it.forwardPos()) {
1995 // look for MathData cells in InsetMathNest insets
1996 Inset * inset = it.nextInset();
2000 InsetMath * minset = inset->asInsetMath();
2004 // update macro in all cells of the InsetMathNest
2005 DocIterator::idx_type n = minset->nargs();
2006 MacroContext mc = MacroContext(*this, it);
2007 for (DocIterator::idx_type i = 0; i < n; ++i) {
2008 MathData & data = minset->cell(i);
2009 data.updateMacros(0, mc);
2015 void Buffer::listMacroNames(MacroNameSet & macros) const
2020 d->macro_lock = true;
2022 // loop over macro names
2023 Impl::NamePositionScopeMacroMap::iterator nameIt
2024 = d->macros.begin();
2025 Impl::NamePositionScopeMacroMap::iterator nameEnd
2027 for (; nameIt != nameEnd; ++nameIt)
2028 macros.insert(nameIt->first);
2030 // loop over children
2031 Impl::BufferPositionMap::iterator it
2032 = d->children_positions.begin();
2033 Impl::BufferPositionMap::iterator end
2034 = d->children_positions.end();
2035 for (; it != end; ++it)
2036 it->first->listMacroNames(macros);
2039 if (d->parent_buffer)
2040 d->parent_buffer->listMacroNames(macros);
2042 d->macro_lock = false;
2046 void Buffer::writeParentMacros(odocstream & os) const
2048 if (!d->parent_buffer)
2051 // collect macro names
2053 d->parent_buffer->listMacroNames(names);
2055 // resolve and output them
2056 MacroNameSet::iterator it = names.begin();
2057 MacroNameSet::iterator end = names.end();
2058 for (; it != end; ++it) {
2060 MacroData const * data =
2061 d->parent_buffer->getMacro(*it, *this, false);
2063 data->write(os, true);
2068 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2071 //FIXME: This does not work for child documents yet.
2072 BOOST_ASSERT(code == CITE_CODE || code == REF_CODE);
2073 // Check if the label 'from' appears more than once
2074 vector<docstring> labels;
2077 if (code == CITE_CODE) {
2079 keys.fillWithBibKeys(this);
2080 BiblioInfo::const_iterator bit = keys.begin();
2081 BiblioInfo::const_iterator bend = keys.end();
2083 for (; bit != bend; ++bit)
2085 labels.push_back(bit->first);
2088 getLabelList(labels);
2089 paramName = "reference";
2092 if (count(labels.begin(), labels.end(), from) > 1)
2095 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2096 if (it->lyxCode() == code) {
2097 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2098 docstring const oldValue = inset.getParam(paramName);
2099 if (oldValue == from)
2100 inset.setParam(paramName, to);
2106 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2107 pit_type par_end, bool full_source)
2109 OutputParams runparams(¶ms().encoding());
2110 runparams.nice = true;
2111 runparams.flavor = OutputParams::LATEX;
2112 runparams.linelen = lyxrc.plaintext_linelen;
2113 // No side effect of file copying and image conversion
2114 runparams.dryrun = true;
2118 os << "% " << _("Preview source code") << "\n\n";
2119 d->texrow.newline();
2120 d->texrow.newline();
2122 writeLaTeXSource(os, filePath(), runparams, true, true);
2124 writeDocBookSource(os, absFileName(), runparams, false);
2127 runparams.par_begin = par_begin;
2128 runparams.par_end = par_end;
2129 if (par_begin + 1 == par_end)
2131 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2135 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2136 convert<docstring>(par_begin),
2137 convert<docstring>(par_end - 1))
2139 d->texrow.newline();
2140 d->texrow.newline();
2141 // output paragraphs
2143 latexParagraphs(*this, text(), os, d->texrow, runparams);
2146 docbookParagraphs(paragraphs(), *this, os, runparams);
2152 ErrorList & Buffer::errorList(string const & type) const
2154 static ErrorList emptyErrorList;
2155 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2156 if (I == d->errorLists.end())
2157 return emptyErrorList;
2163 void Buffer::structureChanged() const
2166 gui_->structureChanged();
2170 void Buffer::errors(string const & err) const
2177 void Buffer::message(docstring const & msg) const
2184 void Buffer::setBusy(bool on) const
2191 void Buffer::setReadOnly(bool on) const
2194 d->wa_->setReadOnly(on);
2198 void Buffer::updateTitles() const
2201 d->wa_->updateTitles();
2205 void Buffer::resetAutosaveTimers() const
2208 gui_->resetAutosaveTimers();
2212 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2221 class AutoSaveBuffer : public ForkedProcess {
2224 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2225 : buffer_(buffer), fname_(fname) {}
2227 virtual boost::shared_ptr<ForkedProcess> clone() const
2229 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2234 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2235 from_utf8(fname_.absFilename())));
2236 return run(DontWait);
2240 virtual int generateChild();
2242 Buffer const & buffer_;
2247 int AutoSaveBuffer::generateChild()
2249 // tmp_ret will be located (usually) in /tmp
2250 // will that be a problem?
2251 // Note that this calls ForkedCalls::fork(), so it's
2252 // ok cross-platform.
2253 pid_t const pid = fork();
2254 // If you want to debug the autosave
2255 // you should set pid to -1, and comment out the fork.
2256 if (pid != 0 && pid != -1)
2259 // pid = -1 signifies that lyx was unable
2260 // to fork. But we will do the save
2262 bool failed = false;
2263 FileName const tmp_ret = FileName::tempName("lyxauto");
2264 if (!tmp_ret.empty()) {
2265 buffer_.writeFile(tmp_ret);
2266 // assume successful write of tmp_ret
2267 if (!tmp_ret.moveTo(fname_))
2273 // failed to write/rename tmp_ret so try writing direct
2274 if (!buffer_.writeFile(fname_)) {
2275 // It is dangerous to do this in the child,
2276 // but safe in the parent, so...
2277 if (pid == -1) // emit message signal.
2278 buffer_.message(_("Autosave failed!"));
2282 if (pid == 0) // we are the child so...
2291 // Perfect target for a thread...
2292 void Buffer::autoSave() const
2294 if (isBakClean() || isReadonly()) {
2295 // We don't save now, but we'll try again later
2296 resetAutosaveTimers();
2300 // emit message signal.
2301 message(_("Autosaving current document..."));
2303 // create autosave filename
2304 string fname = filePath();
2306 fname += d->filename.onlyFileName();
2309 AutoSaveBuffer autosave(*this, FileName(fname));
2313 resetAutosaveTimers();
2317 void Buffer::resetChildDocuments(bool close_them) const
2322 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2323 if (it->lyxCode() != INCLUDE_CODE)
2325 InsetCommand const & inset = static_cast<InsetCommand const &>(*it);
2326 InsetCommandParams const & ip = inset.params();
2328 resetParentBuffer(this, ip, close_them);
2331 if (use_gui && masterBuffer() == this)
2332 updateLabels(*this);
2334 // clear references to children in macro tables
2335 d->children_positions.clear();
2336 d->position_to_children.clear();
2340 void Buffer::loadChildDocuments() const
2342 bool parse_error = false;
2344 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2345 if (it->lyxCode() != INCLUDE_CODE)
2347 InsetCommand const & inset = static_cast<InsetCommand const &>(*it);
2348 InsetCommandParams const & ip = inset.params();
2349 Buffer * child = loadIfNeeded(*this, ip);
2352 parse_error |= !child->errorList("Parse").empty();
2353 child->loadChildDocuments();
2356 if (use_gui && masterBuffer() == this)
2357 updateLabels(*this);
2363 string Buffer::bufferFormat() const
2373 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2374 string & result_file) const
2376 string backend_format;
2377 OutputParams runparams(¶ms().encoding());
2378 runparams.flavor = OutputParams::LATEX;
2379 runparams.linelen = lyxrc.plaintext_linelen;
2380 vector<string> backs = backends();
2381 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2382 // Get shortest path to format
2383 Graph::EdgePath path;
2384 for (vector<string>::const_iterator it = backs.begin();
2385 it != backs.end(); ++it) {
2386 Graph::EdgePath p = theConverters().getPath(*it, format);
2387 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2388 backend_format = *it;
2393 runparams.flavor = theConverters().getFlavor(path);
2395 Alert::error(_("Couldn't export file"),
2396 bformat(_("No information for exporting the format %1$s."),
2397 formats.prettyName(format)));
2401 backend_format = format;
2402 // FIXME: Don't hardcode format names here, but use a flag
2403 if (backend_format == "pdflatex")
2404 runparams.flavor = OutputParams::PDFLATEX;
2407 string filename = latexName(false);
2408 filename = addName(temppath(), filename);
2409 filename = changeExtension(filename,
2410 formats.extension(backend_format));
2413 updateMacroInstances();
2415 // Plain text backend
2416 if (backend_format == "text")
2417 writePlaintextFile(*this, FileName(filename), runparams);
2419 else if (backend_format == "lyx")
2420 writeFile(FileName(filename));
2422 else if (isDocBook()) {
2423 runparams.nice = !put_in_tempdir;
2424 makeDocBookFile(FileName(filename), runparams);
2427 else if (backend_format == format) {
2428 runparams.nice = true;
2429 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2431 } else if (!lyxrc.tex_allows_spaces
2432 && contains(filePath(), ' ')) {
2433 Alert::error(_("File name error"),
2434 _("The directory path to the document cannot contain spaces."));
2437 runparams.nice = false;
2438 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2442 string const error_type = (format == "program")
2443 ? "Build" : bufferFormat();
2444 string const ext = formats.extension(format);
2445 FileName const tmp_result_file(changeExtension(filename, ext));
2446 bool const success = theConverters().convert(this, FileName(filename),
2447 tmp_result_file, FileName(absFileName()), backend_format, format,
2448 errorList(error_type));
2449 // Emit the signal to show the error list.
2450 if (format != backend_format)
2455 if (put_in_tempdir) {
2456 result_file = tmp_result_file.absFilename();
2460 result_file = changeExtension(absFileName(), ext);
2461 // We need to copy referenced files (e. g. included graphics
2462 // if format == "dvi") to the result dir.
2463 vector<ExportedFile> const files =
2464 runparams.exportdata->externalFiles(format);
2465 string const dest = onlyPath(result_file);
2466 CopyStatus status = SUCCESS;
2467 for (vector<ExportedFile>::const_iterator it = files.begin();
2468 it != files.end() && status != CANCEL; ++it) {
2469 string const fmt = formats.getFormatFromFile(it->sourceName);
2470 status = copyFile(fmt, it->sourceName,
2471 makeAbsPath(it->exportName, dest),
2472 it->exportName, status == FORCE);
2474 if (status == CANCEL) {
2475 message(_("Document export cancelled."));
2476 } else if (tmp_result_file.exists()) {
2477 // Finally copy the main file
2478 status = copyFile(format, tmp_result_file,
2479 FileName(result_file), result_file,
2481 message(bformat(_("Document exported as %1$s "
2483 formats.prettyName(format),
2484 makeDisplayPath(result_file)));
2486 // This must be a dummy converter like fax (bug 1888)
2487 message(bformat(_("Document exported as %1$s"),
2488 formats.prettyName(format)));
2495 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2498 return doExport(format, put_in_tempdir, result_file);
2502 bool Buffer::preview(string const & format) const
2505 if (!doExport(format, true, result_file))
2507 return formats.view(*this, FileName(result_file), format);
2511 bool Buffer::isExportable(string const & format) const
2513 vector<string> backs = backends();
2514 for (vector<string>::const_iterator it = backs.begin();
2515 it != backs.end(); ++it)
2516 if (theConverters().isReachable(*it, format))
2522 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2524 vector<string> backs = backends();
2525 vector<Format const *> result =
2526 theConverters().getReachable(backs[0], only_viewable, true);
2527 for (vector<string>::const_iterator it = backs.begin() + 1;
2528 it != backs.end(); ++it) {
2529 vector<Format const *> r =
2530 theConverters().getReachable(*it, only_viewable, false);
2531 result.insert(result.end(), r.begin(), r.end());
2537 vector<string> Buffer::backends() const
2540 if (params().textClass().isTeXClassAvailable()) {
2541 v.push_back(bufferFormat());
2542 // FIXME: Don't hardcode format names here, but use a flag
2543 if (v.back() == "latex")
2544 v.push_back("pdflatex");
2546 v.push_back("text");
2552 bool Buffer::readFileHelper(FileName const & s)
2554 // File information about normal file
2556 docstring const file = makeDisplayPath(s.absFilename(), 50);
2557 docstring text = bformat(_("The specified document\n%1$s"
2558 "\ncould not be read."), file);
2559 Alert::error(_("Could not read document"), text);
2563 // Check if emergency save file exists and is newer.
2564 FileName const e(s.absFilename() + ".emergency");
2566 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2567 docstring const file = makeDisplayPath(s.absFilename(), 20);
2568 docstring const text =
2569 bformat(_("An emergency save of the document "
2571 "Recover emergency save?"), file);
2572 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2573 _("&Recover"), _("&Load Original"),
2577 // the file is not saved if we load the emergency file.
2587 // Now check if autosave file is newer.
2588 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2590 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2591 docstring const file = makeDisplayPath(s.absFilename(), 20);
2592 docstring const text =
2593 bformat(_("The backup of the document "
2594 "%1$s is newer.\n\nLoad the "
2595 "backup instead?"), file);
2596 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2597 _("&Load backup"), _("Load &original"),
2601 // the file is not saved if we load the autosave file.
2605 // Here we delete the autosave
2616 bool Buffer::loadLyXFile(FileName const & s)
2618 if (s.isReadableFile()) {
2619 if (readFileHelper(s)) {
2620 lyxvc().file_found_hook(s);
2621 if (!s.isWritable())
2626 docstring const file = makeDisplayPath(s.absFilename(), 20);
2627 // Here we probably should run
2628 if (LyXVC::file_not_found_hook(s)) {
2629 docstring const text =
2630 bformat(_("Do you want to retrieve the document"
2631 " %1$s from version control?"), file);
2632 int const ret = Alert::prompt(_("Retrieve from version control?"),
2633 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2636 // How can we know _how_ to do the checkout?
2637 // With the current VC support it has to be,
2638 // a RCS file since CVS do not have special ,v files.
2640 return loadLyXFile(s);
2648 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2650 TeXErrors::Errors::const_iterator cit = terr.begin();
2651 TeXErrors::Errors::const_iterator end = terr.end();
2653 for (; cit != end; ++cit) {
2656 int errorRow = cit->error_in_line;
2657 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2663 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2664 } while (found && id_start == id_end && pos_start == pos_end);
2666 errorList.push_back(ErrorItem(cit->error_desc,
2667 cit->error_text, id_start, pos_start, pos_end));
2672 void Buffer::registerWord(docstring const & word)
2674 d->words_.insert(word);
2678 WordList const & Buffer::registeredWords() const