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);
571 for_each(text().paragraphs().begin(),
572 text().paragraphs().end(),
573 bind(&Paragraph::setInsetOwner, _1, &inset()));
576 updateMacroInstances();
581 // needed to insert the selection
582 void Buffer::insertStringAsLines(ParagraphList & pars,
583 pit_type & pit, pos_type & pos,
584 Font const & fn, docstring const & str, bool autobreakrows)
588 // insert the string, don't insert doublespace
589 bool space_inserted = true;
590 for (docstring::const_iterator cit = str.begin();
591 cit != str.end(); ++cit) {
592 Paragraph & par = pars[pit];
594 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
595 breakParagraph(params(), pars, pit, pos,
596 par.layout()->isEnvironment());
599 space_inserted = true;
603 // do not insert consecutive spaces if !free_spacing
604 } else if ((*cit == ' ' || *cit == '\t') &&
605 space_inserted && !par.isFreeSpacing()) {
607 } else if (*cit == '\t') {
608 if (!par.isFreeSpacing()) {
609 // tabs are like spaces here
610 par.insertChar(pos, ' ', font, params().trackChanges);
612 space_inserted = true;
614 const pos_type n = 8 - pos % 8;
615 for (pos_type i = 0; i < n; ++i) {
616 par.insertChar(pos, ' ', font, params().trackChanges);
619 space_inserted = true;
621 } else if (!isPrintable(*cit)) {
622 // Ignore unprintables
625 // just insert the character
626 par.insertChar(pos, *cit, font, params().trackChanges);
628 space_inserted = (*cit == ' ');
635 bool Buffer::readString(string const & s)
637 params().compressed = false;
639 // remove dummy empty par
640 paragraphs().clear();
644 FileName const name = FileName::tempName();
645 switch (readFile(lex, name, true)) {
649 // We need to call lyx2lyx, so write the input to a file
650 ofstream os(name.toFilesystemEncoding().c_str());
653 return readFile(name);
663 bool Buffer::readFile(FileName const & filename)
665 FileName fname(filename);
666 // Check if the file is compressed.
667 string format = filename.guessFormatFromContents();
668 if (format == "zip") {
669 // decompress to a temp directory
670 LYXERR(Debug::FILES, filename << " is in zip format. Unzip to " << temppath());
671 ::unzipToDir(filename.toFilesystemEncoding(), temppath());
673 FileName lyxfile(addName(temppath(), "content.lyx"));
674 // if both manifest.txt and file.lyx exist, this is am embedded file
675 if (lyxfile.exists()) {
676 // if in bundled format, save checksum of the compressed file, not content.lyx
677 saveCheckSum(filename);
678 params().embedded = true;
682 // The embedded lyx file can also be compressed, for backward compatibility
683 format = fname.guessFormatFromContents();
684 if (format == "gzip" || format == "zip" || format == "compress")
685 params().compressed = true;
687 // remove dummy empty par
688 paragraphs().clear();
691 if (readFile(lex, fname) != success)
698 bool Buffer::isFullyLoaded() const
700 return d->file_fully_loaded;
704 void Buffer::setFullyLoaded(bool value)
706 d->file_fully_loaded = value;
710 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
713 BOOST_ASSERT(!filename.empty());
716 Alert::error(_("Document could not be read"),
717 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
722 string const token = lex.getString();
725 Alert::error(_("Document could not be read"),
726 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
730 // the first token _must_ be...
731 if (token != "\\lyxformat") {
732 lyxerr << "Token: " << token << endl;
734 Alert::error(_("Document format failure"),
735 bformat(_("%1$s is not a LyX document."),
736 from_utf8(filename.absFilename())));
741 string tmp_format = lex.getString();
742 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
743 // if present remove ".," from string.
744 string::size_type dot = tmp_format.find_first_of(".,");
745 //lyxerr << " dot found at " << dot << endl;
746 if (dot != string::npos)
747 tmp_format.erase(dot, 1);
748 int const file_format = convert<int>(tmp_format);
749 //lyxerr << "format: " << file_format << endl;
751 // save timestamp and checksum of the original disk file, making sure
752 // to not overwrite them with those of the file created in the tempdir
753 // when it has to be converted to the current format.
755 // Save the timestamp and checksum of disk file. If filename is an
756 // emergency file, save the timestamp and checksum of the original lyx file
757 // because isExternallyModified will check for this file. (BUG4193)
758 string diskfile = filename.absFilename();
759 if (suffixIs(diskfile, ".emergency"))
760 diskfile = diskfile.substr(0, diskfile.size() - 10);
761 saveCheckSum(FileName(diskfile));
764 if (file_format != LYX_FORMAT) {
767 // lyx2lyx would fail
770 FileName const tmpfile = FileName::tempName();
771 if (tmpfile.empty()) {
772 Alert::error(_("Conversion failed"),
773 bformat(_("%1$s is from a different"
774 " version of LyX, but a temporary"
775 " file for converting it could"
777 from_utf8(filename.absFilename())));
780 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
781 if (lyx2lyx.empty()) {
782 Alert::error(_("Conversion script not found"),
783 bformat(_("%1$s is from a different"
784 " version of LyX, but the"
785 " conversion script lyx2lyx"
786 " could not be found."),
787 from_utf8(filename.absFilename())));
790 ostringstream command;
791 command << os::python()
792 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
793 << " -t " << convert<string>(LYX_FORMAT)
794 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
795 << ' ' << quoteName(filename.toFilesystemEncoding());
796 string const command_str = command.str();
798 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
800 cmd_ret const ret = runCommand(command_str);
801 if (ret.first != 0) {
802 Alert::error(_("Conversion script failed"),
803 bformat(_("%1$s is from a different version"
804 " of LyX, but the lyx2lyx script"
805 " failed to convert it."),
806 from_utf8(filename.absFilename())));
809 bool const ret = readFile(tmpfile);
810 // Do stuff with tmpfile name and buffer name here.
811 return ret ? success : failure;
816 if (readDocument(lex)) {
817 Alert::error(_("Document format failure"),
818 bformat(_("%1$s ended unexpectedly, which means"
819 " that it is probably corrupted."),
820 from_utf8(filename.absFilename())));
823 d->file_fully_loaded = true;
828 // Should probably be moved to somewhere else: BufferView? LyXView?
829 bool Buffer::save() const
831 // We don't need autosaves in the immediate future. (Asger)
832 resetAutosaveTimers();
834 string const encodedFilename = d->filename.toFilesystemEncoding();
837 bool madeBackup = false;
839 // make a backup if the file already exists
840 if (lyxrc.make_backup && fileName().exists()) {
841 backupName = FileName(absFileName() + '~');
842 if (!lyxrc.backupdir_path.empty()) {
843 string const mangledName =
844 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
845 backupName = FileName(addName(lyxrc.backupdir_path,
848 if (fileName().copyTo(backupName)) {
851 Alert::error(_("Backup failure"),
852 bformat(_("Cannot create backup file %1$s.\n"
853 "Please check whether the directory exists and is writeable."),
854 from_utf8(backupName.absFilename())));
855 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
859 // ask if the disk file has been externally modified (use checksum method)
860 if (fileName().exists() && isExternallyModified(checksum_method)) {
861 docstring const file = makeDisplayPath(absFileName(), 20);
862 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
863 "you want to overwrite this file?"), file);
864 int const ret = Alert::prompt(_("Overwrite modified file?"),
865 text, 1, 1, _("&Overwrite"), _("&Cancel"));
870 if (writeFile(d->filename)) {
874 // Saving failed, so backup is not backup
876 backupName.moveTo(d->filename);
882 bool Buffer::writeFile(FileName const & fname) const
884 if (d->read_only && fname == d->filename)
890 if (params().embedded)
891 // first write the .lyx file to the temporary directory
892 content = FileName(addName(temppath(), "content.lyx"));
896 docstring const str = bformat(_("Saving document %1$s..."),
897 makeDisplayPath(content.absFilename()));
900 if (params().compressed) {
901 gz::ogzstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
902 retval = ofs && write(ofs);
904 ofstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
905 retval = ofs && write(ofs);
909 message(str + _(" could not write file!."));
913 removeAutosaveFile(d->filename.absFilename());
915 if (params().embedded) {
916 message(str + _(" writing embedded files!."));
917 // if embedding is enabled, write file.lyx and all the embedded files
918 // to the zip file fname.
919 if (!d->embedded_files.writeFile(fname, *this)) {
920 message(str + _(" could not write embedded files!."));
924 saveCheckSum(d->filename);
925 message(str + _(" done."));
931 bool Buffer::write(ostream & ofs) const
934 // Use the standard "C" locale for file output.
935 ofs.imbue(locale::classic());
938 // The top of the file should not be written by params().
940 // write out a comment in the top of the file
941 ofs << "#LyX " << lyx_version
942 << " created this file. For more info see http://www.lyx.org/\n"
943 << "\\lyxformat " << LYX_FORMAT << "\n"
944 << "\\begin_document\n";
946 /// For each author, set 'used' to true if there is a change
947 /// by this author in the document; otherwise set it to 'false'.
948 AuthorList::Authors::const_iterator a_it = params().authors().begin();
949 AuthorList::Authors::const_iterator a_end = params().authors().end();
950 for (; a_it != a_end; ++a_it)
951 a_it->second.setUsed(false);
953 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
954 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
955 for ( ; it != end; ++it)
956 it->checkAuthors(params().authors());
958 // now write out the buffer parameters.
959 ofs << "\\begin_header\n";
960 params().writeFile(ofs);
961 ofs << "\\end_header\n";
964 ofs << "\n\\begin_body\n";
965 text().write(*this, ofs);
966 ofs << "\n\\end_body\n";
968 // Write marker that shows file is complete
969 ofs << "\\end_document" << endl;
971 // Shouldn't really be needed....
974 // how to check if close went ok?
975 // Following is an attempt... (BE 20001011)
977 // good() returns false if any error occured, including some
979 // bad() returns true if something bad happened in the buffer,
980 // which should include file system full errors.
985 lyxerr << "File was not closed properly." << endl;
992 bool Buffer::makeLaTeXFile(FileName const & fname,
993 string const & original_path,
994 OutputParams const & runparams,
995 bool output_preamble, bool output_body) const
997 string const encoding = runparams.encoding->iconvName();
998 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1001 try { ofs.reset(encoding); }
1002 catch (iconv_codecvt_facet_exception & e) {
1003 lyxerr << "Caught iconv exception: " << e.what() << endl;
1004 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1005 "verify that the support software for your encoding (%1$s) is "
1006 "properly installed"), from_ascii(encoding)));
1009 if (!openFileWrite(ofs, fname))
1012 //TexStream ts(ofs.rdbuf(), &texrow());
1013 ErrorList & errorList = d->errorLists["Export"];
1015 bool failed_export = false;
1018 writeLaTeXSource(ofs, original_path,
1019 runparams, output_preamble, output_body);
1021 catch (EncodingException & e) {
1022 odocstringstream ods;
1023 ods.put(e.failed_char);
1025 oss << "0x" << hex << e.failed_char << dec;
1026 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1027 " (code point %2$s)"),
1028 ods.str(), from_utf8(oss.str()));
1029 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1030 "representable in the chosen encoding.\n"
1031 "Changing the document encoding to utf8 could help."),
1032 e.par_id, e.pos, e.pos + 1));
1033 failed_export = true;
1035 catch (iconv_codecvt_facet_exception & e) {
1036 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1037 _(e.what()), -1, 0, 0));
1038 failed_export = true;
1040 catch (exception const & e) {
1041 errorList.push_back(ErrorItem(_("conversion failed"),
1042 _(e.what()), -1, 0, 0));
1043 failed_export = true;
1046 lyxerr << "Caught some really weird exception..." << endl;
1047 LyX::cref().exit(1);
1052 failed_export = true;
1053 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1057 return !failed_export;
1061 void Buffer::writeLaTeXSource(odocstream & os,
1062 string const & original_path,
1063 OutputParams const & runparams_in,
1064 bool const output_preamble, bool const output_body) const
1066 OutputParams runparams = runparams_in;
1068 // validate the buffer.
1069 LYXERR(Debug::LATEX, " Validating buffer...");
1070 LaTeXFeatures features(*this, params(), runparams);
1072 LYXERR(Debug::LATEX, " Buffer validation done.");
1074 // The starting paragraph of the coming rows is the
1075 // first paragraph of the document. (Asger)
1076 if (output_preamble && runparams.nice) {
1077 os << "%% LyX " << lyx_version << " created this file. "
1078 "For more info, see http://www.lyx.org/.\n"
1079 "%% Do not edit unless you really know what "
1081 d->texrow.newline();
1082 d->texrow.newline();
1084 LYXERR(Debug::INFO, "lyx document header finished");
1085 // There are a few differences between nice LaTeX and usual files:
1086 // usual is \batchmode and has a
1087 // special input@path to allow the including of figures
1088 // with either \input or \includegraphics (what figinsets do).
1089 // input@path is set when the actual parameter
1090 // original_path is set. This is done for usual tex-file, but not
1091 // for nice-latex-file. (Matthias 250696)
1092 // Note that input@path is only needed for something the user does
1093 // in the preamble, included .tex files or ERT, files included by
1094 // LyX work without it.
1095 if (output_preamble) {
1096 if (!runparams.nice) {
1097 // code for usual, NOT nice-latex-file
1098 os << "\\batchmode\n"; // changed
1099 // from \nonstopmode
1100 d->texrow.newline();
1102 if (!original_path.empty()) {
1104 // We don't know the encoding of inputpath
1105 docstring const inputpath = from_utf8(latex_path(original_path));
1106 os << "\\makeatletter\n"
1107 << "\\def\\input@path{{"
1108 << inputpath << "/}}\n"
1109 << "\\makeatother\n";
1110 d->texrow.newline();
1111 d->texrow.newline();
1112 d->texrow.newline();
1115 // Write the preamble
1116 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1122 os << "\\begin{document}\n";
1123 d->texrow.newline();
1124 } // output_preamble
1126 d->texrow.start(paragraphs().begin()->id(), 0);
1128 LYXERR(Debug::INFO, "preamble finished, now the body.");
1130 // load children, if not already done.
1131 // This includes an updateMacro() call.
1132 // Don't move this behind the parent_buffer=0 code below,
1133 // because then the macros will not get the right "redefinition"
1134 // flag as they don't see the parent macros which are output before.
1135 loadChildDocuments();
1137 // fold macros if possible, still with parent buffer as the
1138 // macros will be put in the prefix anyway.
1139 updateMacroInstances();
1141 // if we are doing a real file with body, even if this is the
1142 // child of some other buffer, let's cut the link here.
1143 // This happens for example if only a child document is printed.
1144 Buffer const * save_parent = 0;
1145 if (output_preamble) {
1146 // output the macros visible for this buffer
1147 writeParentMacros(os);
1149 save_parent = d->parent_buffer;
1150 d->parent_buffer = 0;
1154 latexParagraphs(*this, text(), os, d->texrow, runparams);
1156 // Restore the parenthood if needed
1157 if (output_preamble) {
1158 d->parent_buffer = save_parent;
1160 // restore macros with correct parent buffer (especially
1161 // important for the redefinition flag which depends on the
1166 // add this just in case after all the paragraphs
1168 d->texrow.newline();
1170 if (output_preamble) {
1171 os << "\\end{document}\n";
1172 d->texrow.newline();
1173 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1175 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1177 runparams_in.encoding = runparams.encoding;
1179 // Just to be sure. (Asger)
1180 d->texrow.newline();
1182 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1183 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1187 bool Buffer::isLatex() const
1189 return params().getTextClass().outputType() == LATEX;
1193 bool Buffer::isLiterate() const
1195 return params().getTextClass().outputType() == LITERATE;
1199 bool Buffer::isDocBook() const
1201 return params().getTextClass().outputType() == DOCBOOK;
1205 void Buffer::makeDocBookFile(FileName const & fname,
1206 OutputParams const & runparams,
1207 bool const body_only) const
1209 LYXERR(Debug::LATEX, "makeDocBookFile...");
1212 if (!openFileWrite(ofs, fname))
1215 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1219 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1223 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1224 OutputParams const & runparams,
1225 bool const only_body) const
1227 LaTeXFeatures features(*this, params(), runparams);
1232 TextClass const & tclass = params().getTextClass();
1233 string const top_element = tclass.latexname();
1236 if (runparams.flavor == OutputParams::XML)
1237 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1240 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1243 if (! tclass.class_header().empty())
1244 os << from_ascii(tclass.class_header());
1245 else if (runparams.flavor == OutputParams::XML)
1246 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1247 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1249 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1251 docstring preamble = from_utf8(params().preamble);
1252 if (runparams.flavor != OutputParams::XML ) {
1253 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1254 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1255 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1256 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1259 string const name = runparams.nice
1260 ? changeExtension(absFileName(), ".sgml") : fname;
1261 preamble += features.getIncludedFiles(name);
1262 preamble += features.getLyXSGMLEntities();
1264 if (!preamble.empty()) {
1265 os << "\n [ " << preamble << " ]";
1270 string top = top_element;
1272 if (runparams.flavor == OutputParams::XML)
1273 top += params().language->code();
1275 top += params().language->code().substr(0,2);
1278 if (!params().options.empty()) {
1280 top += params().options;
1283 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1284 << " file was created by LyX " << lyx_version
1285 << "\n See http://www.lyx.org/ for more information -->\n";
1287 params().getTextClass().counters().reset();
1289 loadChildDocuments();
1291 sgml::openTag(os, top);
1293 docbookParagraphs(paragraphs(), *this, os, runparams);
1294 sgml::closeTag(os, top_element);
1298 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1299 // Other flags: -wall -v0 -x
1300 int Buffer::runChktex()
1304 // get LaTeX-Filename
1305 FileName const path(temppath());
1306 string const name = addName(path.absFilename(), latexName());
1307 string const org_path = filePath();
1309 PathChanger p(path); // path to LaTeX file
1310 message(_("Running chktex..."));
1312 // Generate the LaTeX file if neccessary
1313 OutputParams runparams(¶ms().encoding());
1314 runparams.flavor = OutputParams::LATEX;
1315 runparams.nice = false;
1316 makeLaTeXFile(FileName(name), org_path, runparams);
1319 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1320 int const res = chktex.run(terr); // run chktex
1323 Alert::error(_("chktex failure"),
1324 _("Could not run chktex successfully."));
1325 } else if (res > 0) {
1326 ErrorList & errlist = d->errorLists["ChkTeX"];
1328 bufferErrors(terr, errlist);
1339 void Buffer::validate(LaTeXFeatures & features) const
1341 params().validate(features);
1343 loadChildDocuments();
1345 for_each(paragraphs().begin(), paragraphs().end(),
1346 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1348 if (lyxerr.debugging(Debug::LATEX)) {
1349 features.showStruct();
1354 void Buffer::getLabelList(vector<docstring> & list) const
1356 /// if this is a child document and the parent is already loaded
1357 /// Use the parent's list instead [ale990407]
1358 Buffer const * tmp = masterBuffer();
1360 lyxerr << "masterBuffer() failed!" << endl;
1364 tmp->getLabelList(list);
1368 loadChildDocuments();
1370 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1371 it.nextInset()->getLabelList(*this, list);
1375 void Buffer::updateBibfilesCache() const
1377 // if this is a child document and the parent is already loaded
1378 // update the parent's cache instead
1379 Buffer const * tmp = masterBuffer();
1382 tmp->updateBibfilesCache();
1386 d->bibfilesCache_.clear();
1387 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1388 if (it->lyxCode() == BIBTEX_CODE) {
1389 InsetBibtex const & inset =
1390 static_cast<InsetBibtex const &>(*it);
1391 EmbeddedFileList const bibfiles = inset.getFiles(*this);
1392 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1395 } else if (it->lyxCode() == INCLUDE_CODE) {
1396 InsetInclude & inset =
1397 static_cast<InsetInclude &>(*it);
1398 inset.updateBibfilesCache(*this);
1399 EmbeddedFileList const & bibfiles =
1400 inset.getBibfilesCache(*this);
1401 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1409 EmbeddedFileList const & Buffer::getBibfilesCache() const
1411 // if this is a child document and the parent is already loaded
1412 // use the parent's cache instead
1413 Buffer const * tmp = masterBuffer();
1416 return tmp->getBibfilesCache();
1418 // We update the cache when first used instead of at loading time.
1419 if (d->bibfilesCache_.empty())
1420 const_cast<Buffer *>(this)->updateBibfilesCache();
1422 return d->bibfilesCache_;
1426 bool Buffer::isDepClean(string const & name) const
1428 DepClean::const_iterator const it = d->dep_clean.find(name);
1429 if (it == d->dep_clean.end())
1435 void Buffer::markDepClean(string const & name)
1437 d->dep_clean[name] = true;
1441 bool Buffer::dispatch(string const & command, bool * result)
1443 return dispatch(lyxaction.lookupFunc(command), result);
1447 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1449 bool dispatched = true;
1451 switch (func.action) {
1452 case LFUN_BUFFER_EXPORT: {
1453 bool const tmp = doExport(to_utf8(func.argument()), false);
1466 void Buffer::changeLanguage(Language const * from, Language const * to)
1471 for_each(par_iterator_begin(),
1473 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1477 bool Buffer::isMultiLingual() const
1479 ParConstIterator end = par_iterator_end();
1480 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1481 if (it->isMultiLingual(params()))
1488 DocIterator Buffer::getParFromID(int const id) const
1491 // John says this is called with id == -1 from undo
1492 lyxerr << "getParFromID(), id: " << id << endl;
1493 return doc_iterator_end(inset());
1496 for (DocIterator it = doc_iterator_begin(inset()); !it.atEnd(); it.forwardPar())
1497 if (it.paragraph().id() == id)
1500 return doc_iterator_end(inset());
1504 bool Buffer::hasParWithID(int const id) const
1506 return !getParFromID(id).atEnd();
1510 ParIterator Buffer::par_iterator_begin()
1512 return ParIterator(doc_iterator_begin(inset()));
1516 ParIterator Buffer::par_iterator_end()
1518 return ParIterator(doc_iterator_end(inset()));
1522 ParConstIterator Buffer::par_iterator_begin() const
1524 return lyx::par_const_iterator_begin(inset());
1528 ParConstIterator Buffer::par_iterator_end() const
1530 return lyx::par_const_iterator_end(inset());
1534 Language const * Buffer::language() const
1536 return params().language;
1540 docstring const Buffer::B_(string const & l10n) const
1542 return params().B_(l10n);
1546 bool Buffer::isClean() const
1548 return d->lyx_clean;
1552 bool Buffer::isBakClean() const
1554 return d->bak_clean;
1558 bool Buffer::isExternallyModified(CheckMethod method) const
1560 BOOST_ASSERT(d->filename.exists());
1561 // if method == timestamp, check timestamp before checksum
1562 return (method == checksum_method
1563 || d->timestamp_ != d->filename.lastModified())
1564 && d->checksum_ != d->filename.checksum();
1568 void Buffer::saveCheckSum(FileName const & file) const
1570 if (file.exists()) {
1571 d->timestamp_ = file.lastModified();
1572 d->checksum_ = file.checksum();
1574 // in the case of save to a new file.
1581 void Buffer::markClean() const
1583 if (!d->lyx_clean) {
1584 d->lyx_clean = true;
1587 // if the .lyx file has been saved, we don't need an
1589 d->bak_clean = true;
1593 void Buffer::markBakClean() const
1595 d->bak_clean = true;
1599 void Buffer::setUnnamed(bool flag)
1605 bool Buffer::isUnnamed() const
1611 // FIXME: this function should be moved to buffer_pimpl.C
1612 void Buffer::markDirty()
1615 d->lyx_clean = false;
1618 d->bak_clean = false;
1620 DepClean::iterator it = d->dep_clean.begin();
1621 DepClean::const_iterator const end = d->dep_clean.end();
1623 for (; it != end; ++it)
1628 FileName Buffer::fileName() const
1634 string Buffer::absFileName() const
1636 return d->filename.absFilename();
1640 string Buffer::filePath() const
1642 return d->filename.onlyPath().absFilename() + "/";
1646 bool Buffer::isReadonly() const
1648 return d->read_only;
1652 void Buffer::setParent(Buffer const * buffer)
1654 // Avoids recursive include.
1655 d->parent_buffer = buffer == this ? 0 : buffer;
1660 Buffer const * Buffer::parent()
1662 return d->parent_buffer;
1666 Buffer const * Buffer::masterBuffer() const
1668 if (!d->parent_buffer)
1671 return d->parent_buffer->masterBuffer();
1675 template<typename M>
1676 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
1681 typename M::iterator it = m.lower_bound(x);
1682 if (it == m.begin())
1690 MacroData const * Buffer::getBufferMacro(docstring const & name,
1691 DocIterator const & pos) const
1693 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
1695 // if paragraphs have no macro context set, pos will be empty
1699 // we haven't found anything yet
1700 DocIterator bestPos = par_iterator_begin();
1701 MacroData const * bestData = 0;
1703 // find macro definitions for name
1704 Impl::NamePositionScopeMacroMap::iterator nameIt
1705 = d->macros.find(name);
1706 if (nameIt != d->macros.end()) {
1707 // find last definition in front of pos or at pos itself
1708 Impl::PositionScopeMacroMap::const_iterator it
1709 = greatest_below(nameIt->second, pos);
1710 if (it != nameIt->second.end()) {
1712 // scope ends behind pos?
1713 if (pos < it->second.first) {
1714 // Looks good, remember this. If there
1715 // is no external macro behind this,
1716 // we found the right one already.
1717 bestPos = it->first;
1718 bestData = &it->second.second;
1722 // try previous macro if there is one
1723 if (it == nameIt->second.begin())
1730 // find macros in included files
1731 Impl::PositionScopeBufferMap::const_iterator it
1732 = greatest_below(d->position_to_children, pos);
1733 if (it == d->position_to_children.end())
1734 // no children before
1738 // do we know something better (i.e. later) already?
1739 if (it->first < bestPos )
1742 // scope ends behind pos?
1743 if (pos < it->second.first) {
1744 // look for macro in external file
1745 d->macro_lock = true;
1746 MacroData const * data
1747 = it->second.second->getMacro(name, false);
1748 d->macro_lock = false;
1750 bestPos = it->first;
1756 // try previous file if there is one
1757 if (it == d->position_to_children.begin())
1762 // return the best macro we have found
1767 MacroData const * Buffer::getMacro(docstring const & name,
1768 DocIterator const & pos, bool global) const
1773 // query buffer macros
1774 MacroData const * data = getBufferMacro(name, pos);
1778 // If there is a master buffer, query that
1779 if (d->parent_buffer) {
1780 d->macro_lock = true;
1781 MacroData const * macro
1782 = d->parent_buffer->getMacro(name, *this, false);
1783 d->macro_lock = false;
1789 data = MacroTable::globalMacros().get(name);
1798 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
1800 // set scope end behind the last paragraph
1801 DocIterator scope = par_iterator_begin();
1802 scope.pit() = scope.lastpit() + 1;
1804 return getMacro(name, scope, global);
1808 MacroData const * Buffer::getMacro(docstring const & name, Buffer const & child, bool global) const
1810 // look where the child buffer is included first
1811 Impl::BufferPositionMap::iterator it
1812 = d->children_positions.find(&child);
1813 if (it == d->children_positions.end())
1816 // check for macros at the inclusion position
1817 return getMacro(name, it->second, global);
1821 void Buffer::updateEnvironmentMacros(DocIterator & it,
1823 DocIterator & scope) const
1825 Paragraph & par = it.paragraph();
1827 = par.params().depth();
1828 Length const & leftIndent
1829 = par.params().leftIndent();
1831 // look for macros in each paragraph
1832 while (it.pit() <= lastpit) {
1833 Paragraph & par = it.paragraph();
1836 if ((par.params().depth() > depth
1837 || par.params().leftIndent() != leftIndent)
1838 && par.layout()->isEnvironment()) {
1839 updateBlockMacros(it, scope);
1843 // iterate over the insets of the current paragraph
1844 InsetList const & insets = par.insetList();
1845 InsetList::const_iterator iit = insets.begin();
1846 InsetList::const_iterator end = insets.end();
1847 for (; iit != end; ++iit) {
1848 it.pos() = iit->pos;
1850 // is it a nested text inset?
1851 if (iit->inset->asInsetText()) {
1852 // Inset needs its own scope?
1853 InsetText const * itext
1854 = iit->inset->asInsetText();
1855 bool newScope = itext->isMacroScope(*this);
1857 // scope which ends just behind die inset
1858 DocIterator insetScope = it;
1861 // collect macros in inset
1862 it.push_back(CursorSlice(*iit->inset));
1863 updateInsetMacros(it, newScope ? insetScope : scope);
1868 // is it an external file?
1869 if (iit->inset->lyxCode() == INCLUDE_CODE) {
1870 // get buffer of external file
1871 InsetCommand const & inset
1872 = static_cast<InsetCommand const &>(*iit->inset);
1873 InsetCommandParams const & ip = inset.params();
1874 d->macro_lock = true;
1875 Buffer * child = loadIfNeeded(*this, ip);
1876 d->macro_lock = false;
1880 // register its position, but only when it is
1881 // included first in the buffer
1882 if (d->children_positions.find(child)
1883 == d->children_positions.end())
1884 d->children_positions[child] = it;
1886 // register child with its scope
1887 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
1892 if (iit->inset->lyxCode() != MATHMACRO_CODE)
1896 MathMacroTemplate & macroTemplate
1897 = static_cast<MathMacroTemplate &>(*iit->inset);
1898 MacroContext mc(*this, it);
1899 macroTemplate.updateToContext(mc);
1902 bool valid = macroTemplate.validMacro();
1903 // FIXME: Should be fixNameAndCheckIfValid() in fact,
1904 // then the BufferView's cursor will be invalid in
1905 // some cases which leads to crashes.
1910 d->macros[macroTemplate.name()][it]
1911 = Impl::ScopeMacro(scope, MacroData(*this, it));
1921 void Buffer::updateBlockMacros(DocIterator & it, DocIterator & scope) const
1923 Paragraph & par = it.paragraph();
1925 // set scope for macros in this paragraph:
1926 // * either the "old" outer scope
1927 // * or the scope ending after the environment
1928 if (par.layout()->isEnvironment()) {
1929 // find end of environment block,
1930 DocIterator envEnd = it;
1931 pit_type n = it.lastpit() + 1;
1932 depth_type depth = par.params().depth();
1933 Length const & length = par.params().leftIndent();
1934 // looping through the paragraph, basically until
1935 // the layout changes or the depth gets smaller.
1936 // (the logic of output_latex.cpp's TeXEnvironment)
1939 if (envEnd.pit() == n)
1941 } while (par.layout() == envEnd.paragraph().layout()
1942 || depth < envEnd.paragraph().params().depth()
1943 || length != envEnd.paragraph().params().leftIndent());
1945 // collect macros from environment block
1946 updateEnvironmentMacros(it, envEnd.pit() - 1, envEnd);
1948 // collect macros from paragraph
1949 updateEnvironmentMacros(it, it.pit(), scope);
1954 void Buffer::updateInsetMacros(DocIterator & it, DocIterator & scope) const
1956 // look for macros in each paragraph
1957 pit_type n = it.lastpit() + 1;
1958 while (it.pit() < n)
1959 updateBlockMacros(it, scope);
1963 void Buffer::updateMacros() const
1968 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
1970 // start with empty table
1972 d->children_positions.clear();
1973 d->position_to_children.clear();
1975 // Iterate over buffer, starting with first paragraph
1976 // The scope must be bigger than any lookup DocIterator
1977 // later. For the global lookup, lastpit+1 is used, hence
1978 // we use lastpit+2 here.
1979 DocIterator it = par_iterator_begin();
1980 DocIterator outerScope = it;
1981 outerScope.pit() = outerScope.lastpit() + 2;
1982 updateInsetMacros(it, outerScope);
1986 void Buffer::updateMacroInstances() const
1988 LYXERR(Debug::MACROS, "updateMacroInstances for "
1989 << d->filename.onlyFileName());
1990 DocIterator it = doc_iterator_begin(inset());
1991 DocIterator end = doc_iterator_end(inset());
1992 for (; it != end; it.forwardPos()) {
1993 // look for MathData cells in InsetMathNest insets
1994 Inset * inset = it.nextInset();
1998 InsetMath * minset = inset->asInsetMath();
2002 // update macro in all cells of the InsetMathNest
2003 DocIterator::idx_type n = minset->nargs();
2004 MacroContext mc = MacroContext(*this, it);
2005 for (DocIterator::idx_type i = 0; i < n; ++i) {
2006 MathData & data = minset->cell(i);
2007 data.updateMacros(0, mc);
2013 void Buffer::listMacroNames(MacroNameSet & macros) const
2018 d->macro_lock = true;
2020 // loop over macro names
2021 Impl::NamePositionScopeMacroMap::iterator nameIt
2022 = d->macros.begin();
2023 Impl::NamePositionScopeMacroMap::iterator nameEnd
2025 for (; nameIt != nameEnd; ++nameIt)
2026 macros.insert(nameIt->first);
2028 // loop over children
2029 Impl::BufferPositionMap::iterator it
2030 = d->children_positions.begin();
2031 Impl::BufferPositionMap::iterator end
2032 = d->children_positions.end();
2033 for (; it != end; ++it)
2034 it->first->listMacroNames(macros);
2037 if (d->parent_buffer)
2038 d->parent_buffer->listMacroNames(macros);
2040 d->macro_lock = false;
2044 void Buffer::writeParentMacros(odocstream & os) const
2046 if (!d->parent_buffer)
2049 // collect macro names
2051 d->parent_buffer->listMacroNames(names);
2053 // resolve and output them
2054 MacroNameSet::iterator it = names.begin();
2055 MacroNameSet::iterator end = names.end();
2056 for (; it != end; ++it) {
2058 MacroData const * data =
2059 d->parent_buffer->getMacro(*it, *this, false);
2061 data->write(os, true);
2066 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2069 //FIXME: This does not work for child documents yet.
2070 BOOST_ASSERT(code == CITE_CODE || code == REF_CODE);
2071 // Check if the label 'from' appears more than once
2072 vector<docstring> labels;
2075 if (code == CITE_CODE) {
2077 keys.fillWithBibKeys(this);
2078 BiblioInfo::const_iterator bit = keys.begin();
2079 BiblioInfo::const_iterator bend = keys.end();
2081 for (; bit != bend; ++bit)
2083 labels.push_back(bit->first);
2086 getLabelList(labels);
2087 paramName = "reference";
2090 if (count(labels.begin(), labels.end(), from) > 1)
2093 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2094 if (it->lyxCode() == code) {
2095 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2096 docstring const oldValue = inset.getParam(paramName);
2097 if (oldValue == from)
2098 inset.setParam(paramName, to);
2104 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2105 pit_type par_end, bool full_source)
2107 OutputParams runparams(¶ms().encoding());
2108 runparams.nice = true;
2109 runparams.flavor = OutputParams::LATEX;
2110 runparams.linelen = lyxrc.plaintext_linelen;
2111 // No side effect of file copying and image conversion
2112 runparams.dryrun = true;
2116 os << "% " << _("Preview source code") << "\n\n";
2117 d->texrow.newline();
2118 d->texrow.newline();
2120 writeLaTeXSource(os, filePath(), runparams, true, true);
2122 writeDocBookSource(os, absFileName(), runparams, false);
2125 runparams.par_begin = par_begin;
2126 runparams.par_end = par_end;
2127 if (par_begin + 1 == par_end)
2129 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2133 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2134 convert<docstring>(par_begin),
2135 convert<docstring>(par_end - 1))
2137 d->texrow.newline();
2138 d->texrow.newline();
2139 // output paragraphs
2141 latexParagraphs(*this, text(), os, d->texrow, runparams);
2144 docbookParagraphs(paragraphs(), *this, os, runparams);
2150 ErrorList & Buffer::errorList(string const & type) const
2152 static ErrorList emptyErrorList;
2153 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2154 if (I == d->errorLists.end())
2155 return emptyErrorList;
2161 void Buffer::structureChanged() const
2164 gui_->structureChanged();
2168 void Buffer::errors(string const & err) const
2175 void Buffer::message(docstring const & msg) const
2182 void Buffer::setBusy(bool on) const
2189 void Buffer::setReadOnly(bool on) const
2192 d->wa_->setReadOnly(on);
2196 void Buffer::updateTitles() const
2199 d->wa_->updateTitles();
2203 void Buffer::resetAutosaveTimers() const
2206 gui_->resetAutosaveTimers();
2210 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2219 class AutoSaveBuffer : public ForkedProcess {
2222 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2223 : buffer_(buffer), fname_(fname) {}
2225 virtual boost::shared_ptr<ForkedProcess> clone() const
2227 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2232 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2233 from_utf8(fname_.absFilename())));
2234 return run(DontWait);
2238 virtual int generateChild();
2240 Buffer const & buffer_;
2245 int AutoSaveBuffer::generateChild()
2247 // tmp_ret will be located (usually) in /tmp
2248 // will that be a problem?
2249 // Note that this calls ForkedCalls::fork(), so it's
2250 // ok cross-platform.
2251 pid_t const pid = fork();
2252 // If you want to debug the autosave
2253 // you should set pid to -1, and comment out the fork.
2254 if (pid != 0 && pid != -1)
2257 // pid = -1 signifies that lyx was unable
2258 // to fork. But we will do the save
2260 bool failed = false;
2261 FileName const tmp_ret = FileName::tempName("lyxauto");
2262 if (!tmp_ret.empty()) {
2263 buffer_.writeFile(tmp_ret);
2264 // assume successful write of tmp_ret
2265 if (!tmp_ret.moveTo(fname_))
2271 // failed to write/rename tmp_ret so try writing direct
2272 if (!buffer_.writeFile(fname_)) {
2273 // It is dangerous to do this in the child,
2274 // but safe in the parent, so...
2275 if (pid == -1) // emit message signal.
2276 buffer_.message(_("Autosave failed!"));
2280 if (pid == 0) // we are the child so...
2289 // Perfect target for a thread...
2290 void Buffer::autoSave() const
2292 if (isBakClean() || isReadonly()) {
2293 // We don't save now, but we'll try again later
2294 resetAutosaveTimers();
2298 // emit message signal.
2299 message(_("Autosaving current document..."));
2301 // create autosave filename
2302 string fname = filePath();
2304 fname += d->filename.onlyFileName();
2307 AutoSaveBuffer autosave(*this, FileName(fname));
2311 resetAutosaveTimers();
2315 void Buffer::resetChildDocuments(bool close_them) const
2317 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2318 if (it->lyxCode() != INCLUDE_CODE)
2320 InsetCommand const & inset = static_cast<InsetCommand const &>(*it);
2321 InsetCommandParams const & ip = inset.params();
2323 resetParentBuffer(this, ip, close_them);
2326 if (use_gui && masterBuffer() == this)
2327 updateLabels(*this);
2329 // clear references to children in macro tables
2330 d->children_positions.clear();
2331 d->position_to_children.clear();
2335 void Buffer::loadChildDocuments() const
2337 bool parse_error = false;
2339 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2340 if (it->lyxCode() != INCLUDE_CODE)
2342 InsetCommand const & inset = static_cast<InsetCommand const &>(*it);
2343 InsetCommandParams const & ip = inset.params();
2344 Buffer * child = loadIfNeeded(*this, ip);
2347 parse_error |= !child->errorList("Parse").empty();
2348 child->loadChildDocuments();
2351 if (use_gui && masterBuffer() == this)
2352 updateLabels(*this);
2358 string Buffer::bufferFormat() const
2368 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2369 string & result_file) const
2371 string backend_format;
2372 OutputParams runparams(¶ms().encoding());
2373 runparams.flavor = OutputParams::LATEX;
2374 runparams.linelen = lyxrc.plaintext_linelen;
2375 vector<string> backs = backends();
2376 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2377 // Get shortest path to format
2378 Graph::EdgePath path;
2379 for (vector<string>::const_iterator it = backs.begin();
2380 it != backs.end(); ++it) {
2381 Graph::EdgePath p = theConverters().getPath(*it, format);
2382 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2383 backend_format = *it;
2388 runparams.flavor = theConverters().getFlavor(path);
2390 Alert::error(_("Couldn't export file"),
2391 bformat(_("No information for exporting the format %1$s."),
2392 formats.prettyName(format)));
2396 backend_format = format;
2397 // FIXME: Don't hardcode format names here, but use a flag
2398 if (backend_format == "pdflatex")
2399 runparams.flavor = OutputParams::PDFLATEX;
2402 string filename = latexName(false);
2403 filename = addName(temppath(), filename);
2404 filename = changeExtension(filename,
2405 formats.extension(backend_format));
2408 updateMacroInstances();
2410 // Plain text backend
2411 if (backend_format == "text")
2412 writePlaintextFile(*this, FileName(filename), runparams);
2414 else if (backend_format == "lyx")
2415 writeFile(FileName(filename));
2417 else if (isDocBook()) {
2418 runparams.nice = !put_in_tempdir;
2419 makeDocBookFile(FileName(filename), runparams);
2422 else if (backend_format == format) {
2423 runparams.nice = true;
2424 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2426 } else if (!lyxrc.tex_allows_spaces
2427 && contains(filePath(), ' ')) {
2428 Alert::error(_("File name error"),
2429 _("The directory path to the document cannot contain spaces."));
2432 runparams.nice = false;
2433 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2437 string const error_type = (format == "program")
2438 ? "Build" : bufferFormat();
2439 string const ext = formats.extension(format);
2440 FileName const tmp_result_file(changeExtension(filename, ext));
2441 bool const success = theConverters().convert(this, FileName(filename),
2442 tmp_result_file, FileName(absFileName()), backend_format, format,
2443 errorList(error_type));
2444 // Emit the signal to show the error list.
2445 if (format != backend_format)
2450 if (put_in_tempdir) {
2451 result_file = tmp_result_file.absFilename();
2455 result_file = changeExtension(absFileName(), ext);
2456 // We need to copy referenced files (e. g. included graphics
2457 // if format == "dvi") to the result dir.
2458 vector<ExportedFile> const files =
2459 runparams.exportdata->externalFiles(format);
2460 string const dest = onlyPath(result_file);
2461 CopyStatus status = SUCCESS;
2462 for (vector<ExportedFile>::const_iterator it = files.begin();
2463 it != files.end() && status != CANCEL; ++it) {
2464 string const fmt = formats.getFormatFromFile(it->sourceName);
2465 status = copyFile(fmt, it->sourceName,
2466 makeAbsPath(it->exportName, dest),
2467 it->exportName, status == FORCE);
2469 if (status == CANCEL) {
2470 message(_("Document export cancelled."));
2471 } else if (tmp_result_file.exists()) {
2472 // Finally copy the main file
2473 status = copyFile(format, tmp_result_file,
2474 FileName(result_file), result_file,
2476 message(bformat(_("Document exported as %1$s "
2478 formats.prettyName(format),
2479 makeDisplayPath(result_file)));
2481 // This must be a dummy converter like fax (bug 1888)
2482 message(bformat(_("Document exported as %1$s"),
2483 formats.prettyName(format)));
2490 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2493 return doExport(format, put_in_tempdir, result_file);
2497 bool Buffer::preview(string const & format) const
2500 if (!doExport(format, true, result_file))
2502 return formats.view(*this, FileName(result_file), format);
2506 bool Buffer::isExportable(string const & format) const
2508 vector<string> backs = backends();
2509 for (vector<string>::const_iterator it = backs.begin();
2510 it != backs.end(); ++it)
2511 if (theConverters().isReachable(*it, format))
2517 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2519 vector<string> backs = backends();
2520 vector<Format const *> result =
2521 theConverters().getReachable(backs[0], only_viewable, true);
2522 for (vector<string>::const_iterator it = backs.begin() + 1;
2523 it != backs.end(); ++it) {
2524 vector<Format const *> r =
2525 theConverters().getReachable(*it, only_viewable, false);
2526 result.insert(result.end(), r.begin(), r.end());
2532 vector<string> Buffer::backends() const
2535 if (params().getTextClass().isTeXClassAvailable()) {
2536 v.push_back(bufferFormat());
2537 // FIXME: Don't hardcode format names here, but use a flag
2538 if (v.back() == "latex")
2539 v.push_back("pdflatex");
2541 v.push_back("text");
2547 bool Buffer::readFileHelper(FileName const & s)
2549 // File information about normal file
2551 docstring const file = makeDisplayPath(s.absFilename(), 50);
2552 docstring text = bformat(_("The specified document\n%1$s"
2553 "\ncould not be read."), file);
2554 Alert::error(_("Could not read document"), text);
2558 // Check if emergency save file exists and is newer.
2559 FileName const e(s.absFilename() + ".emergency");
2561 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2562 docstring const file = makeDisplayPath(s.absFilename(), 20);
2563 docstring const text =
2564 bformat(_("An emergency save of the document "
2566 "Recover emergency save?"), file);
2567 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2568 _("&Recover"), _("&Load Original"),
2572 // the file is not saved if we load the emergency file.
2582 // Now check if autosave file is newer.
2583 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2585 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2586 docstring const file = makeDisplayPath(s.absFilename(), 20);
2587 docstring const text =
2588 bformat(_("The backup of the document "
2589 "%1$s is newer.\n\nLoad the "
2590 "backup instead?"), file);
2591 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2592 _("&Load backup"), _("Load &original"),
2596 // the file is not saved if we load the autosave file.
2600 // Here we delete the autosave
2611 bool Buffer::loadLyXFile(FileName const & s)
2613 if (s.isReadableFile()) {
2614 if (readFileHelper(s)) {
2615 lyxvc().file_found_hook(s);
2616 if (!s.isWritable())
2621 docstring const file = makeDisplayPath(s.absFilename(), 20);
2622 // Here we probably should run
2623 if (LyXVC::file_not_found_hook(s)) {
2624 docstring const text =
2625 bformat(_("Do you want to retrieve the document"
2626 " %1$s from version control?"), file);
2627 int const ret = Alert::prompt(_("Retrieve from version control?"),
2628 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2631 // How can we know _how_ to do the checkout?
2632 // With the current VC support it has to be,
2633 // a RCS file since CVS do not have special ,v files.
2635 return loadLyXFile(s);
2643 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2645 TeXErrors::Errors::const_iterator cit = terr.begin();
2646 TeXErrors::Errors::const_iterator end = terr.end();
2648 for (; cit != end; ++cit) {
2651 int errorRow = cit->error_in_line;
2652 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2658 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2659 } while (found && id_start == id_end && pos_start == pos_end);
2661 errorList.push_back(ErrorItem(cit->error_desc,
2662 cit->error_text, id_start, pos_start, pos_end));