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/FileFilterList.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 = 313; // Richard Heck: conversion of module representations
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_;
209 /// Creates the per buffer temporary directory
210 static FileName createBufferTmpDir()
213 // We are in our own directory. Why bother to mangle name?
214 // In fact I wrote this code to circumvent a problematic behaviour
215 // (bug?) of EMX mkstemp().
216 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
217 convert<string>(count++));
219 if (!tmpfl.createDirectory(0777)) {
220 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
221 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
222 from_utf8(tmpfl.absFilename())));
228 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
229 : parent_buffer(0), lyx_clean(true), bak_clean(true), unnamed(false),
230 read_only(readonly_), filename(file), file_fully_loaded(false),
231 inset(params), toc_backend(&parent), macro_lock(false),
232 embedded_files(), timestamp_(0), checksum_(0), wa_(0),
235 temppath = createBufferTmpDir();
236 inset.setAutoBreakRows(true);
237 lyxvc.setBuffer(&parent);
239 wa_ = new frontend::WorkAreaManager;
243 Buffer::Buffer(string const & file, bool readonly)
244 : d(new Impl(*this, FileName(file), readonly)), gui_(0)
246 LYXERR(Debug::INFO, "Buffer::Buffer()");
248 d->inset.getText(0)->setMacrocontextPosition(par_iterator_begin());
254 LYXERR(Debug::INFO, "Buffer::~Buffer()");
255 // here the buffer should take care that it is
256 // saved properly, before it goes into the void.
258 // GuiView already destroyed
261 Buffer const * master = masterBuffer();
262 if (master != this && use_gui) {
263 // We are closing buf which was a child document so we
264 // must update the labels and section numbering of its master
266 updateLabels(*master);
267 master->updateMacros();
270 resetChildDocuments(false);
272 if (!d->temppath.destroyDirectory()) {
273 Alert::warning(_("Could not remove temporary directory"),
274 bformat(_("Could not remove the temporary directory %1$s"),
275 from_utf8(d->temppath.absFilename())));
278 // Remove any previewed LaTeX snippets associated with this buffer.
279 graphics::Previews::get().removeLoader(*this);
285 void Buffer::changed() const
292 frontend::WorkAreaManager & Buffer::workAreaManager() const
294 BOOST_ASSERT(d->wa_);
299 Text & Buffer::text() const
301 return const_cast<Text &>(d->inset.text_);
305 Inset & Buffer::inset() const
307 return const_cast<InsetText &>(d->inset);
311 BufferParams & Buffer::params()
317 BufferParams const & Buffer::params() const
323 ParagraphList & Buffer::paragraphs()
325 return text().paragraphs();
329 ParagraphList const & Buffer::paragraphs() const
331 return text().paragraphs();
335 LyXVC & Buffer::lyxvc()
341 LyXVC const & Buffer::lyxvc() const
347 string const Buffer::temppath() const
349 return d->temppath.absFilename();
353 TexRow const & Buffer::texrow() const
359 TocBackend & Buffer::tocBackend() const
361 return d->toc_backend;
365 EmbeddedFileList & Buffer::embeddedFiles()
367 return d->embedded_files;
371 EmbeddedFileList const & Buffer::embeddedFiles() const
373 return d->embedded_files;
377 bool Buffer::embedded() const
379 return params().embedded;
383 Undo & Buffer::undo()
389 string Buffer::latexName(bool const no_path) const
391 FileName latex_name = makeLatexName(d->filename);
392 return no_path ? latex_name.onlyFileName()
393 : latex_name.absFilename();
397 string Buffer::logName(LogType * type) const
399 string const filename = latexName(false);
401 if (filename.empty()) {
407 string const path = temppath();
409 FileName const fname(addName(temppath(),
410 onlyFilename(changeExtension(filename,
412 FileName const bname(
413 addName(path, onlyFilename(
414 changeExtension(filename,
415 formats.extension("literate") + ".out"))));
417 // If no Latex log or Build log is newer, show Build log
419 if (bname.exists() &&
420 (!fname.exists() || fname.lastModified() < bname.lastModified())) {
421 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
424 return bname.absFilename();
426 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
429 return fname.absFilename();
433 void Buffer::setReadonly(bool const flag)
435 if (d->read_only != flag) {
442 void Buffer::setFileName(string const & newfile)
444 d->filename = makeAbsPath(newfile);
445 setReadonly(d->filename.isReadOnly());
450 int Buffer::readHeader(Lexer & lex)
452 int unknown_tokens = 0;
454 int begin_header_line = -1;
456 // Initialize parameters that may be/go lacking in header:
457 params().branchlist().clear();
458 params().preamble.erase();
459 params().options.erase();
460 params().float_placement.erase();
461 params().paperwidth.erase();
462 params().paperheight.erase();
463 params().leftmargin.erase();
464 params().rightmargin.erase();
465 params().topmargin.erase();
466 params().bottommargin.erase();
467 params().headheight.erase();
468 params().headsep.erase();
469 params().footskip.erase();
470 params().listings_params.clear();
471 params().clearLayoutModules();
472 params().pdfoptions().clear();
474 for (int i = 0; i < 4; ++i) {
475 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
476 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
479 ErrorList & errorList = d->errorLists["Parse"];
483 string const token = lex.getString();
488 if (token == "\\end_header")
492 if (token == "\\begin_header") {
493 begin_header_line = line;
497 LYXERR(Debug::PARSER, "Handling document header token: `"
500 string unknown = params().readToken(lex, token, d->filename.onlyPath());
501 if (!unknown.empty()) {
502 if (unknown[0] != '\\' && token == "\\textclass") {
503 Alert::warning(_("Unknown document class"),
504 bformat(_("Using the default document class, because the "
505 "class %1$s is unknown."), from_utf8(unknown)));
508 docstring const s = bformat(_("Unknown token: "
512 errorList.push_back(ErrorItem(_("Document header error"),
517 if (begin_header_line) {
518 docstring const s = _("\\begin_header is missing");
519 errorList.push_back(ErrorItem(_("Document header error"),
523 params().makeTextClass();
525 return unknown_tokens;
530 // changed to be public and have one parameter
531 // Returns false if "\end_document" is not read (Asger)
532 bool Buffer::readDocument(Lexer & lex)
534 ErrorList & errorList = d->errorLists["Parse"];
538 string const token = lex.getString();
539 if (token != "\\begin_document") {
540 docstring const s = _("\\begin_document is missing");
541 errorList.push_back(ErrorItem(_("Document header error"),
545 // we are reading in a brand new document
546 BOOST_ASSERT(paragraphs().empty());
550 if (params().outputChanges) {
551 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
552 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
553 LaTeXFeatures::isAvailable("xcolor");
555 if (!dvipost && !xcolorsoul) {
556 Alert::warning(_("Changes not shown in LaTeX output"),
557 _("Changes will not be highlighted in LaTeX output, "
558 "because neither dvipost nor xcolor/soul are installed.\n"
559 "Please install these packages or redefine "
560 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
561 } else if (!xcolorsoul) {
562 Alert::warning(_("Changes not shown in LaTeX output"),
563 _("Changes will not be highlighted in LaTeX output "
564 "when using pdflatex, because xcolor and soul are not installed.\n"
565 "Please install both packages or redefine "
566 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
571 bool const res = text().read(*this, lex, errorList);
572 for_each(text().paragraphs().begin(),
573 text().paragraphs().end(),
574 bind(&Paragraph::setInsetOwner, _1, &inset()));
577 updateMacroInstances();
582 // needed to insert the selection
583 void Buffer::insertStringAsLines(ParagraphList & pars,
584 pit_type & pit, pos_type & pos,
585 Font const & fn, docstring const & str, bool autobreakrows)
589 // insert the string, don't insert doublespace
590 bool space_inserted = true;
591 for (docstring::const_iterator cit = str.begin();
592 cit != str.end(); ++cit) {
593 Paragraph & par = pars[pit];
595 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
596 breakParagraph(params(), pars, pit, pos,
597 par.layout()->isEnvironment());
600 space_inserted = true;
604 // do not insert consecutive spaces if !free_spacing
605 } else if ((*cit == ' ' || *cit == '\t') &&
606 space_inserted && !par.isFreeSpacing()) {
608 } else if (*cit == '\t') {
609 if (!par.isFreeSpacing()) {
610 // tabs are like spaces here
611 par.insertChar(pos, ' ', font, params().trackChanges);
613 space_inserted = true;
615 const pos_type n = 8 - pos % 8;
616 for (pos_type i = 0; i < n; ++i) {
617 par.insertChar(pos, ' ', font, params().trackChanges);
620 space_inserted = true;
622 } else if (!isPrintable(*cit)) {
623 // Ignore unprintables
626 // just insert the character
627 par.insertChar(pos, *cit, font, params().trackChanges);
629 space_inserted = (*cit == ' ');
636 bool Buffer::readString(string const & s)
638 params().compressed = false;
640 // remove dummy empty par
641 paragraphs().clear();
645 FileName const name = FileName::tempName();
646 switch (readFile(lex, name, true)) {
650 // We need to call lyx2lyx, so write the input to a file
651 ofstream os(name.toFilesystemEncoding().c_str());
654 return readFile(name);
664 bool Buffer::readFile(FileName const & filename)
666 FileName fname(filename);
667 // Check if the file is compressed.
668 string format = filename.guessFormatFromContents();
669 if (format == "zip") {
670 // decompress to a temp directory
671 LYXERR(Debug::FILES, filename << " is in zip format. Unzip to " << temppath());
672 ::unzipToDir(filename.toFilesystemEncoding(), temppath());
674 FileName lyxfile(addName(temppath(), "content.lyx"));
675 // if both manifest.txt and file.lyx exist, this is am embedded file
676 if (lyxfile.exists()) {
677 // if in bundled format, save checksum of the compressed file, not content.lyx
678 saveCheckSum(filename);
679 params().embedded = true;
683 // The embedded lyx file can also be compressed, for backward compatibility
684 format = fname.guessFormatFromContents();
685 if (format == "gzip" || format == "zip" || format == "compress")
686 params().compressed = true;
688 // remove dummy empty par
689 paragraphs().clear();
692 if (readFile(lex, fname) != success)
699 bool Buffer::isFullyLoaded() const
701 return d->file_fully_loaded;
705 void Buffer::setFullyLoaded(bool value)
707 d->file_fully_loaded = value;
711 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
714 BOOST_ASSERT(!filename.empty());
717 Alert::error(_("Document could not be read"),
718 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
723 string const token = lex.getString();
726 Alert::error(_("Document could not be read"),
727 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
731 // the first token _must_ be...
732 if (token != "\\lyxformat") {
733 lyxerr << "Token: " << token << endl;
735 Alert::error(_("Document format failure"),
736 bformat(_("%1$s is not a LyX document."),
737 from_utf8(filename.absFilename())));
742 string tmp_format = lex.getString();
743 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
744 // if present remove ".," from string.
745 string::size_type dot = tmp_format.find_first_of(".,");
746 //lyxerr << " dot found at " << dot << endl;
747 if (dot != string::npos)
748 tmp_format.erase(dot, 1);
749 int const file_format = convert<int>(tmp_format);
750 //lyxerr << "format: " << file_format << endl;
752 // save timestamp and checksum of the original disk file, making sure
753 // to not overwrite them with those of the file created in the tempdir
754 // when it has to be converted to the current format.
756 // Save the timestamp and checksum of disk file. If filename is an
757 // emergency file, save the timestamp and checksum of the original lyx file
758 // because isExternallyModified will check for this file. (BUG4193)
759 string diskfile = filename.absFilename();
760 if (suffixIs(diskfile, ".emergency"))
761 diskfile = diskfile.substr(0, diskfile.size() - 10);
762 saveCheckSum(FileName(diskfile));
765 if (file_format != LYX_FORMAT) {
768 // lyx2lyx would fail
771 FileName const tmpfile = FileName::tempName();
772 if (tmpfile.empty()) {
773 Alert::error(_("Conversion failed"),
774 bformat(_("%1$s is from a different"
775 " version of LyX, but a temporary"
776 " file for converting it could"
778 from_utf8(filename.absFilename())));
781 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
782 if (lyx2lyx.empty()) {
783 Alert::error(_("Conversion script not found"),
784 bformat(_("%1$s is from a different"
785 " version of LyX, but the"
786 " conversion script lyx2lyx"
787 " could not be found."),
788 from_utf8(filename.absFilename())));
791 ostringstream command;
792 command << os::python()
793 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
794 << " -t " << convert<string>(LYX_FORMAT)
795 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
796 << ' ' << quoteName(filename.toFilesystemEncoding());
797 string const command_str = command.str();
799 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
801 cmd_ret const ret = runCommand(command_str);
802 if (ret.first != 0) {
803 Alert::error(_("Conversion script failed"),
804 bformat(_("%1$s is from a different version"
805 " of LyX, but the lyx2lyx script"
806 " failed to convert it."),
807 from_utf8(filename.absFilename())));
810 bool const ret = readFile(tmpfile);
811 // Do stuff with tmpfile name and buffer name here.
812 return ret ? success : failure;
817 if (readDocument(lex)) {
818 Alert::error(_("Document format failure"),
819 bformat(_("%1$s ended unexpectedly, which means"
820 " that it is probably corrupted."),
821 from_utf8(filename.absFilename())));
824 d->file_fully_loaded = true;
829 // Should probably be moved to somewhere else: BufferView? LyXView?
830 bool Buffer::save() const
832 // We don't need autosaves in the immediate future. (Asger)
833 resetAutosaveTimers();
835 string const encodedFilename = d->filename.toFilesystemEncoding();
838 bool madeBackup = false;
840 // make a backup if the file already exists
841 if (lyxrc.make_backup && fileName().exists()) {
842 backupName = FileName(absFileName() + '~');
843 if (!lyxrc.backupdir_path.empty()) {
844 string const mangledName =
845 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
846 backupName = FileName(addName(lyxrc.backupdir_path,
849 if (fileName().copyTo(backupName)) {
852 Alert::error(_("Backup failure"),
853 bformat(_("Cannot create backup file %1$s.\n"
854 "Please check whether the directory exists and is writeable."),
855 from_utf8(backupName.absFilename())));
856 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
860 // ask if the disk file has been externally modified (use checksum method)
861 if (fileName().exists() && isExternallyModified(checksum_method)) {
862 docstring const file = makeDisplayPath(absFileName(), 20);
863 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
864 "you want to overwrite this file?"), file);
865 int const ret = Alert::prompt(_("Overwrite modified file?"),
866 text, 1, 1, _("&Overwrite"), _("&Cancel"));
871 if (writeFile(d->filename)) {
875 // Saving failed, so backup is not backup
877 backupName.moveTo(d->filename);
883 bool Buffer::writeFile(FileName const & fname) const
885 if (d->read_only && fname == d->filename)
891 if (params().embedded)
892 // first write the .lyx file to the temporary directory
893 content = FileName(addName(temppath(), "content.lyx"));
897 docstring const str = bformat(_("Saving document %1$s..."),
898 makeDisplayPath(content.absFilename()));
901 if (params().compressed) {
902 gz::ogzstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
903 retval = ofs && write(ofs);
905 ofstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
906 retval = ofs && write(ofs);
910 message(str + _(" could not write file!."));
914 removeAutosaveFile(d->filename.absFilename());
916 if (params().embedded) {
917 message(str + _(" writing embedded files!."));
918 // if embedding is enabled, write file.lyx and all the embedded files
919 // to the zip file fname.
920 if (!d->embedded_files.writeFile(fname, *this)) {
921 message(str + _(" could not write embedded files!."));
925 saveCheckSum(d->filename);
926 message(str + _(" done."));
932 bool Buffer::write(ostream & ofs) const
935 // Use the standard "C" locale for file output.
936 ofs.imbue(locale::classic());
939 // The top of the file should not be written by params().
941 // write out a comment in the top of the file
942 ofs << "#LyX " << lyx_version
943 << " created this file. For more info see http://www.lyx.org/\n"
944 << "\\lyxformat " << LYX_FORMAT << "\n"
945 << "\\begin_document\n";
947 /// For each author, set 'used' to true if there is a change
948 /// by this author in the document; otherwise set it to 'false'.
949 AuthorList::Authors::const_iterator a_it = params().authors().begin();
950 AuthorList::Authors::const_iterator a_end = params().authors().end();
951 for (; a_it != a_end; ++a_it)
952 a_it->second.setUsed(false);
954 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
955 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
956 for ( ; it != end; ++it)
957 it->checkAuthors(params().authors());
959 // now write out the buffer parameters.
960 ofs << "\\begin_header\n";
961 params().writeFile(ofs);
962 ofs << "\\end_header\n";
965 ofs << "\n\\begin_body\n";
966 text().write(*this, ofs);
967 ofs << "\n\\end_body\n";
969 // Write marker that shows file is complete
970 ofs << "\\end_document" << endl;
972 // Shouldn't really be needed....
975 // how to check if close went ok?
976 // Following is an attempt... (BE 20001011)
978 // good() returns false if any error occured, including some
980 // bad() returns true if something bad happened in the buffer,
981 // which should include file system full errors.
986 lyxerr << "File was not closed properly." << endl;
993 bool Buffer::makeLaTeXFile(FileName const & fname,
994 string const & original_path,
995 OutputParams const & runparams,
996 bool output_preamble, bool output_body) const
998 string const encoding = runparams.encoding->iconvName();
999 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1002 try { ofs.reset(encoding); }
1003 catch (iconv_codecvt_facet_exception & e) {
1004 lyxerr << "Caught iconv exception: " << e.what() << endl;
1005 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1006 "verify that the support software for your encoding (%1$s) is "
1007 "properly installed"), from_ascii(encoding)));
1010 if (!openFileWrite(ofs, fname))
1013 //TexStream ts(ofs.rdbuf(), &texrow());
1014 ErrorList & errorList = d->errorLists["Export"];
1016 bool failed_export = false;
1019 writeLaTeXSource(ofs, original_path,
1020 runparams, output_preamble, output_body);
1022 catch (EncodingException & e) {
1023 odocstringstream ods;
1024 ods.put(e.failed_char);
1026 oss << "0x" << hex << e.failed_char << dec;
1027 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1028 " (code point %2$s)"),
1029 ods.str(), from_utf8(oss.str()));
1030 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1031 "representable in the chosen encoding.\n"
1032 "Changing the document encoding to utf8 could help."),
1033 e.par_id, e.pos, e.pos + 1));
1034 failed_export = true;
1036 catch (iconv_codecvt_facet_exception & e) {
1037 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1038 _(e.what()), -1, 0, 0));
1039 failed_export = true;
1041 catch (exception const & e) {
1042 errorList.push_back(ErrorItem(_("conversion failed"),
1043 _(e.what()), -1, 0, 0));
1044 failed_export = true;
1047 lyxerr << "Caught some really weird exception..." << endl;
1048 LyX::cref().exit(1);
1053 failed_export = true;
1054 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1058 return !failed_export;
1062 void Buffer::writeLaTeXSource(odocstream & os,
1063 string const & original_path,
1064 OutputParams const & runparams_in,
1065 bool const output_preamble, bool const output_body) const
1067 OutputParams runparams = runparams_in;
1069 // validate the buffer.
1070 LYXERR(Debug::LATEX, " Validating buffer...");
1071 LaTeXFeatures features(*this, params(), runparams);
1073 LYXERR(Debug::LATEX, " Buffer validation done.");
1075 // The starting paragraph of the coming rows is the
1076 // first paragraph of the document. (Asger)
1077 if (output_preamble && runparams.nice) {
1078 os << "%% LyX " << lyx_version << " created this file. "
1079 "For more info, see http://www.lyx.org/.\n"
1080 "%% Do not edit unless you really know what "
1082 d->texrow.newline();
1083 d->texrow.newline();
1085 LYXERR(Debug::INFO, "lyx document header finished");
1086 // There are a few differences between nice LaTeX and usual files:
1087 // usual is \batchmode and has a
1088 // special input@path to allow the including of figures
1089 // with either \input or \includegraphics (what figinsets do).
1090 // input@path is set when the actual parameter
1091 // original_path is set. This is done for usual tex-file, but not
1092 // for nice-latex-file. (Matthias 250696)
1093 // Note that input@path is only needed for something the user does
1094 // in the preamble, included .tex files or ERT, files included by
1095 // LyX work without it.
1096 if (output_preamble) {
1097 if (!runparams.nice) {
1098 // code for usual, NOT nice-latex-file
1099 os << "\\batchmode\n"; // changed
1100 // from \nonstopmode
1101 d->texrow.newline();
1103 if (!original_path.empty()) {
1105 // We don't know the encoding of inputpath
1106 docstring const inputpath = from_utf8(latex_path(original_path));
1107 os << "\\makeatletter\n"
1108 << "\\def\\input@path{{"
1109 << inputpath << "/}}\n"
1110 << "\\makeatother\n";
1111 d->texrow.newline();
1112 d->texrow.newline();
1113 d->texrow.newline();
1116 // Write the preamble
1117 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1123 os << "\\begin{document}\n";
1124 d->texrow.newline();
1125 } // output_preamble
1127 d->texrow.start(paragraphs().begin()->id(), 0);
1129 LYXERR(Debug::INFO, "preamble finished, now the body.");
1131 // load children, if not already done.
1132 // This includes an updateMacro() call.
1133 // Don't move this behind the parent_buffer=0 code below,
1134 // because then the macros will not get the right "redefinition"
1135 // flag as they don't see the parent macros which are output before.
1136 loadChildDocuments();
1138 // fold macros if possible, still with parent buffer as the
1139 // macros will be put in the prefix anyway.
1140 updateMacroInstances();
1142 // if we are doing a real file with body, even if this is the
1143 // child of some other buffer, let's cut the link here.
1144 // This happens for example if only a child document is printed.
1145 Buffer const * save_parent = 0;
1146 if (output_preamble) {
1147 // output the macros visible for this buffer
1148 writeParentMacros(os);
1150 save_parent = d->parent_buffer;
1151 d->parent_buffer = 0;
1155 latexParagraphs(*this, text(), os, d->texrow, runparams);
1157 // Restore the parenthood if needed
1158 if (output_preamble) {
1159 d->parent_buffer = save_parent;
1161 // restore macros with correct parent buffer (especially
1162 // important for the redefinition flag which depends on the
1167 // add this just in case after all the paragraphs
1169 d->texrow.newline();
1171 if (output_preamble) {
1172 os << "\\end{document}\n";
1173 d->texrow.newline();
1174 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1176 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1178 runparams_in.encoding = runparams.encoding;
1180 // Just to be sure. (Asger)
1181 d->texrow.newline();
1183 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1184 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1188 bool Buffer::isLatex() const
1190 return params().getTextClass().outputType() == LATEX;
1194 bool Buffer::isLiterate() const
1196 return params().getTextClass().outputType() == LITERATE;
1200 bool Buffer::isDocBook() const
1202 return params().getTextClass().outputType() == DOCBOOK;
1206 void Buffer::makeDocBookFile(FileName const & fname,
1207 OutputParams const & runparams,
1208 bool const body_only) const
1210 LYXERR(Debug::LATEX, "makeDocBookFile...");
1213 if (!openFileWrite(ofs, fname))
1216 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1220 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1224 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1225 OutputParams const & runparams,
1226 bool const only_body) const
1228 LaTeXFeatures features(*this, params(), runparams);
1233 TextClass const & tclass = params().getTextClass();
1234 string const top_element = tclass.latexname();
1237 if (runparams.flavor == OutputParams::XML)
1238 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1241 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1244 if (! tclass.class_header().empty())
1245 os << from_ascii(tclass.class_header());
1246 else if (runparams.flavor == OutputParams::XML)
1247 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1248 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1250 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1252 docstring preamble = from_utf8(params().preamble);
1253 if (runparams.flavor != OutputParams::XML ) {
1254 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1255 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1256 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1257 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1260 string const name = runparams.nice
1261 ? changeExtension(absFileName(), ".sgml") : fname;
1262 preamble += features.getIncludedFiles(name);
1263 preamble += features.getLyXSGMLEntities();
1265 if (!preamble.empty()) {
1266 os << "\n [ " << preamble << " ]";
1271 string top = top_element;
1273 if (runparams.flavor == OutputParams::XML)
1274 top += params().language->code();
1276 top += params().language->code().substr(0,2);
1279 if (!params().options.empty()) {
1281 top += params().options;
1284 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1285 << " file was created by LyX " << lyx_version
1286 << "\n See http://www.lyx.org/ for more information -->\n";
1288 params().getTextClass().counters().reset();
1290 loadChildDocuments();
1292 sgml::openTag(os, top);
1294 docbookParagraphs(paragraphs(), *this, os, runparams);
1295 sgml::closeTag(os, top_element);
1299 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1300 // Other flags: -wall -v0 -x
1301 int Buffer::runChktex()
1305 // get LaTeX-Filename
1306 FileName const path(temppath());
1307 string const name = addName(path.absFilename(), latexName());
1308 string const org_path = filePath();
1310 PathChanger p(path); // path to LaTeX file
1311 message(_("Running chktex..."));
1313 // Generate the LaTeX file if neccessary
1314 OutputParams runparams(¶ms().encoding());
1315 runparams.flavor = OutputParams::LATEX;
1316 runparams.nice = false;
1317 makeLaTeXFile(FileName(name), org_path, runparams);
1320 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1321 int const res = chktex.run(terr); // run chktex
1324 Alert::error(_("chktex failure"),
1325 _("Could not run chktex successfully."));
1326 } else if (res > 0) {
1327 ErrorList & errlist = d->errorLists["ChkTeX"];
1329 bufferErrors(terr, errlist);
1340 void Buffer::validate(LaTeXFeatures & features) const
1342 params().validate(features);
1344 loadChildDocuments();
1346 for_each(paragraphs().begin(), paragraphs().end(),
1347 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1349 if (lyxerr.debugging(Debug::LATEX)) {
1350 features.showStruct();
1355 void Buffer::getLabelList(vector<docstring> & list) const
1357 /// if this is a child document and the parent is already loaded
1358 /// Use the parent's list instead [ale990407]
1359 Buffer const * tmp = masterBuffer();
1361 lyxerr << "masterBuffer() failed!" << endl;
1365 tmp->getLabelList(list);
1369 loadChildDocuments();
1371 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1372 it.nextInset()->getLabelList(*this, list);
1376 void Buffer::updateBibfilesCache() const
1378 // if this is a child document and the parent is already loaded
1379 // update the parent's cache instead
1380 Buffer const * tmp = masterBuffer();
1383 tmp->updateBibfilesCache();
1387 d->bibfilesCache_.clear();
1388 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1389 if (it->lyxCode() == BIBTEX_CODE) {
1390 InsetBibtex const & inset =
1391 static_cast<InsetBibtex const &>(*it);
1392 EmbeddedFileList const bibfiles = inset.getFiles(*this);
1393 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1396 } else if (it->lyxCode() == INCLUDE_CODE) {
1397 InsetInclude & inset =
1398 static_cast<InsetInclude &>(*it);
1399 inset.updateBibfilesCache(*this);
1400 EmbeddedFileList const & bibfiles =
1401 inset.getBibfilesCache(*this);
1402 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1410 EmbeddedFileList const & Buffer::getBibfilesCache() const
1412 // if this is a child document and the parent is already loaded
1413 // use the parent's cache instead
1414 Buffer const * tmp = masterBuffer();
1417 return tmp->getBibfilesCache();
1419 // We update the cache when first used instead of at loading time.
1420 if (d->bibfilesCache_.empty())
1421 const_cast<Buffer *>(this)->updateBibfilesCache();
1423 return d->bibfilesCache_;
1427 bool Buffer::isDepClean(string const & name) const
1429 DepClean::const_iterator const it = d->dep_clean.find(name);
1430 if (it == d->dep_clean.end())
1436 void Buffer::markDepClean(string const & name)
1438 d->dep_clean[name] = true;
1442 bool Buffer::dispatch(string const & command, bool * result)
1444 return dispatch(lyxaction.lookupFunc(command), result);
1448 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1450 bool dispatched = true;
1452 switch (func.action) {
1453 case LFUN_BUFFER_EXPORT: {
1454 bool const tmp = doExport(to_utf8(func.argument()), false);
1467 void Buffer::changeLanguage(Language const * from, Language const * to)
1472 for_each(par_iterator_begin(),
1474 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1478 bool Buffer::isMultiLingual() const
1480 ParConstIterator end = par_iterator_end();
1481 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1482 if (it->isMultiLingual(params()))
1489 ParConstIterator Buffer::getParFromID(int const id) const
1491 ParConstIterator it = par_iterator_begin();
1492 ParConstIterator const end = par_iterator_end();
1495 // John says this is called with id == -1 from undo
1496 lyxerr << "getParFromID(), id: " << id << endl;
1500 for (; it != end; ++it)
1508 ParIterator Buffer::getParFromID(int const id)
1510 ParIterator it = par_iterator_begin();
1511 ParIterator const end = par_iterator_end();
1514 // John says this is called with id == -1 from undo
1515 lyxerr << "getParFromID(), id: " << id << endl;
1519 for (; it != end; ++it)
1527 bool Buffer::hasParWithID(int const id) const
1529 ParConstIterator const it = getParFromID(id);
1530 return it != par_iterator_end();
1534 ParIterator Buffer::par_iterator_begin()
1536 return lyx::par_iterator_begin(inset());
1540 ParIterator Buffer::par_iterator_end()
1542 return lyx::par_iterator_end(inset());
1546 ParConstIterator Buffer::par_iterator_begin() const
1548 return lyx::par_const_iterator_begin(inset());
1552 ParConstIterator Buffer::par_iterator_end() const
1554 return lyx::par_const_iterator_end(inset());
1558 Language const * Buffer::language() const
1560 return params().language;
1564 docstring const Buffer::B_(string const & l10n) const
1566 return params().B_(l10n);
1570 bool Buffer::isClean() const
1572 return d->lyx_clean;
1576 bool Buffer::isBakClean() const
1578 return d->bak_clean;
1582 bool Buffer::isExternallyModified(CheckMethod method) const
1584 BOOST_ASSERT(d->filename.exists());
1585 // if method == timestamp, check timestamp before checksum
1586 return (method == checksum_method
1587 || d->timestamp_ != d->filename.lastModified())
1588 && d->checksum_ != d->filename.checksum();
1592 void Buffer::saveCheckSum(FileName const & file) const
1594 if (file.exists()) {
1595 d->timestamp_ = file.lastModified();
1596 d->checksum_ = file.checksum();
1598 // in the case of save to a new file.
1605 void Buffer::markClean() const
1607 if (!d->lyx_clean) {
1608 d->lyx_clean = true;
1611 // if the .lyx file has been saved, we don't need an
1613 d->bak_clean = true;
1617 void Buffer::markBakClean() const
1619 d->bak_clean = true;
1623 void Buffer::setUnnamed(bool flag)
1629 bool Buffer::isUnnamed() const
1635 // FIXME: this function should be moved to buffer_pimpl.C
1636 void Buffer::markDirty()
1639 d->lyx_clean = false;
1642 d->bak_clean = false;
1644 DepClean::iterator it = d->dep_clean.begin();
1645 DepClean::const_iterator const end = d->dep_clean.end();
1647 for (; it != end; ++it)
1652 FileName Buffer::fileName() const
1658 string Buffer::absFileName() const
1660 return d->filename.absFilename();
1664 string Buffer::filePath() const
1666 return d->filename.onlyPath().absFilename() + "/";
1670 bool Buffer::isReadonly() const
1672 return d->read_only;
1676 void Buffer::setParent(Buffer const * buffer)
1678 // Avoids recursive include.
1679 d->parent_buffer = buffer == this ? 0 : buffer;
1684 Buffer const * Buffer::parent()
1686 return d->parent_buffer;
1690 Buffer const * Buffer::masterBuffer() const
1692 if (!d->parent_buffer)
1695 return d->parent_buffer->masterBuffer();
1699 template<typename M>
1700 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
1705 typename M::iterator it = m.lower_bound(x);
1706 if (it == m.begin())
1714 MacroData const * Buffer::getBufferMacro(docstring const & name,
1715 DocIterator const & pos) const
1717 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
1719 // if paragraphs have no macro context set, pos will be empty
1723 // we haven't found anything yet
1724 DocIterator bestPos = par_iterator_begin();
1725 MacroData const * bestData = 0;
1727 // find macro definitions for name
1728 Impl::NamePositionScopeMacroMap::iterator nameIt
1729 = d->macros.find(name);
1730 if (nameIt != d->macros.end()) {
1731 // find last definition in front of pos or at pos itself
1732 Impl::PositionScopeMacroMap::const_iterator it
1733 = greatest_below(nameIt->second, pos);
1734 if (it != nameIt->second.end()) {
1736 // scope ends behind pos?
1737 if (pos < it->second.first) {
1738 // Looks good, remember this. If there
1739 // is no external macro behind this,
1740 // we found the right one already.
1741 bestPos = it->first;
1742 bestData = &it->second.second;
1746 // try previous macro if there is one
1747 if (it == nameIt->second.begin())
1754 // find macros in included files
1755 Impl::PositionScopeBufferMap::const_iterator it
1756 = greatest_below(d->position_to_children, pos);
1757 if (it != d->position_to_children.end()) {
1759 // do we know something better (i.e. later) already?
1760 if (it->first < bestPos )
1763 // scope ends behind pos?
1764 if (pos < it->second.first) {
1765 // look for macro in external file
1766 d->macro_lock = true;
1767 MacroData const * data
1768 = it->second.second->getMacro(name, false);
1769 d->macro_lock = false;
1771 bestPos = it->first;
1777 // try previous file if there is one
1778 if (it == d->position_to_children.begin())
1784 // return the best macro we have found
1789 MacroData const * Buffer::getMacro(docstring const & name,
1790 DocIterator const & pos, bool global) const
1795 // query buffer macros
1796 MacroData const * data = getBufferMacro(name, pos);
1800 // If there is a master buffer, query that
1801 if (d->parent_buffer) {
1802 d->macro_lock = true;
1803 MacroData const * macro
1804 = d->parent_buffer->getMacro(name, *this, false);
1805 d->macro_lock = false;
1811 data = MacroTable::globalMacros().get(name);
1820 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
1822 // set scope end behind the last paragraph
1823 DocIterator scope = par_iterator_begin();
1824 scope.pit() = scope.lastpit() + 1;
1826 return getMacro(name, scope, global);
1830 MacroData const * Buffer::getMacro(docstring const & name, Buffer const & child, bool global) const
1832 // look where the child buffer is included first
1833 Impl::BufferPositionMap::iterator it
1834 = d->children_positions.find(&child);
1835 if (it == d->children_positions.end())
1838 // check for macros at the inclusion position
1839 return getMacro(name, it->second, global);
1843 void Buffer::updateEnvironmentMacros(DocIterator & it,
1845 DocIterator & scope) const
1847 Paragraph & par = it.paragraph();
1849 = par.params().depth();
1850 Length const & leftIndent
1851 = par.params().leftIndent();
1853 // look for macros in each paragraph
1854 while (it.pit() <= lastpit) {
1855 Paragraph & par = it.paragraph();
1858 if ((par.params().depth() > depth
1859 || par.params().leftIndent() != leftIndent)
1860 && par.layout()->isEnvironment()) {
1861 updateBlockMacros(it, scope);
1865 // iterate over the insets of the current paragraph
1866 InsetList const & insets = par.insetList();
1867 InsetList::const_iterator iit = insets.begin();
1868 InsetList::const_iterator end = insets.end();
1869 for (; iit != end; ++iit) {
1870 it.pos() = iit->pos;
1872 // is it a nested text inset?
1873 if (iit->inset->asInsetText()) {
1874 // Inset needs its own scope?
1875 InsetText const * itext
1876 = iit->inset->asInsetText();
1877 bool newScope = itext->isMacroScope(*this);
1879 // scope which ends just behind die inset
1880 DocIterator insetScope = it;
1883 // collect macros in inset
1884 it.push_back(CursorSlice(*iit->inset));
1885 updateInsetMacros(it, newScope ? insetScope : scope);
1890 // is it an external file?
1891 if (iit->inset->lyxCode() == INCLUDE_CODE) {
1892 // get buffer of external file
1893 InsetCommand const & inset
1894 = static_cast<InsetCommand const &>(*iit->inset);
1895 InsetCommandParams const & ip = inset.params();
1896 d->macro_lock = true;
1897 Buffer * child = loadIfNeeded(*this, ip);
1898 d->macro_lock = false;
1902 // register it, but only when it is
1903 // included first in the buffer
1904 if (d->children_positions.find(child)
1905 == d->children_positions.end())
1906 d->children_positions[child] = it;
1908 // register child with its scope
1909 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
1914 if (iit->inset->lyxCode() != MATHMACRO_CODE)
1918 MathMacroTemplate & macroTemplate
1919 = static_cast<MathMacroTemplate &>(*iit->inset);
1920 MacroContext mc(*this, it);
1921 macroTemplate.updateToContext(mc);
1924 bool valid = macroTemplate.validMacro();
1925 // FIXME: Should be fixNameAndCheckIfValid() in fact,
1926 // then the BufferView's cursor will be invalid in
1927 // some cases which leads to crashes.
1932 d->macros[macroTemplate.name()][it]
1933 = Impl::ScopeMacro(scope, MacroData(*this, it));
1943 void Buffer::updateBlockMacros(DocIterator & it, DocIterator & scope) const
1945 Paragraph & par = it.paragraph();
1947 // set scope for macros in this paragraph:
1948 // * either the "old" outer scope
1949 // * or the scope ending after the environment
1950 if (par.layout()->isEnvironment()) {
1951 // find end of environment block,
1952 DocIterator envEnd = it;
1953 pit_type n = it.lastpit() + 1;
1954 depth_type depth = par.params().depth();
1955 Length const & length = par.params().leftIndent();
1956 // looping through the paragraph, basically until
1957 // the layout changes or the depth gets smaller.
1958 // (the logic of output_latex.cpp's TeXEnvironment)
1961 if (envEnd.pit() == n)
1963 } while (par.layout() == envEnd.paragraph().layout()
1964 || depth < envEnd.paragraph().params().depth()
1965 || length != envEnd.paragraph().params().leftIndent());
1967 // collect macros from environment block
1968 updateEnvironmentMacros(it, envEnd.pit() - 1, envEnd);
1970 // collect macros from paragraph
1971 updateEnvironmentMacros(it, it.pit(), scope);
1976 void Buffer::updateInsetMacros(DocIterator & it, DocIterator & scope) const
1978 // look for macros in each paragraph
1979 pit_type n = it.lastpit() + 1;
1980 while (it.pit() < n)
1981 updateBlockMacros(it, scope);
1985 void Buffer::updateMacros() const
1990 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
1992 // start with empty table
1994 d->children_positions.clear();
1995 d->position_to_children.clear();
1997 // Iterate over buffer, starting with first paragraph
1998 // The scope must be bigger than any lookup DocIterator
1999 // later. For the global lookup, lastpit+1 is used, hence
2000 // we use lastpit+2 here.
2001 DocIterator it = par_iterator_begin();
2002 DocIterator outerScope = it;
2003 outerScope.pit() = outerScope.lastpit() + 2;
2004 updateInsetMacros(it, outerScope);
2008 void Buffer::updateMacroInstances() const
2010 LYXERR(Debug::MACROS, "updateMacroInstances for "
2011 << d->filename.onlyFileName());
2012 ParConstIterator it = par_iterator_begin();
2013 ParConstIterator end = par_iterator_end();
2014 for (; it != end; it.forwardPos()) {
2015 // look for MathData cells in InsetMathNest insets
2016 Inset * inset = it.nextInset();
2020 InsetMath * minset = inset->asInsetMath();
2024 // update macro in all cells of the InsetMathNest
2025 DocIterator::idx_type n = minset->nargs();
2026 MacroContext mc = MacroContext(*this, it);
2027 for (DocIterator::idx_type i = 0; i < n; ++i) {
2028 MathData & data = minset->cell(i);
2029 data.updateMacros(0, mc);
2035 void Buffer::listMacroNames(MacroNameSet & macros) const
2040 d->macro_lock = true;
2042 // loop over macro names
2043 Impl::NamePositionScopeMacroMap::iterator nameIt
2044 = d->macros.begin();
2045 Impl::NamePositionScopeMacroMap::iterator nameEnd
2047 for (; nameIt != nameEnd; ++nameIt)
2048 macros.insert(nameIt->first);
2050 // loop over children
2051 Impl::BufferPositionMap::iterator it
2052 = d->children_positions.begin();
2053 Impl::BufferPositionMap::iterator end
2054 = d->children_positions.end();
2055 for (; it != end; ++it)
2056 it->first->listMacroNames(macros);
2059 if (d->parent_buffer)
2060 d->parent_buffer->listMacroNames(macros);
2062 d->macro_lock = false;
2066 void Buffer::writeParentMacros(odocstream & os) const
2068 if (!d->parent_buffer)
2071 // collect macro names
2073 d->parent_buffer->listMacroNames(names);
2075 // resolve and output them
2076 MacroNameSet::iterator it = names.begin();
2077 MacroNameSet::iterator end = names.end();
2078 for (; it != end; ++it) {
2080 MacroData const * data =
2081 d->parent_buffer->getMacro(*it, *this, false);
2083 data->write(os, true);
2088 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2091 //FIXME: This does not work for child documents yet.
2092 BOOST_ASSERT(code == CITE_CODE || code == REF_CODE);
2093 // Check if the label 'from' appears more than once
2094 vector<docstring> labels;
2097 if (code == CITE_CODE) {
2099 keys.fillWithBibKeys(this);
2100 BiblioInfo::const_iterator bit = keys.begin();
2101 BiblioInfo::const_iterator bend = keys.end();
2103 for (; bit != bend; ++bit)
2105 labels.push_back(bit->first);
2108 getLabelList(labels);
2109 paramName = "reference";
2112 if (count(labels.begin(), labels.end(), from) > 1)
2115 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2116 if (it->lyxCode() == code) {
2117 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2118 docstring const oldValue = inset.getParam(paramName);
2119 if (oldValue == from)
2120 inset.setParam(paramName, to);
2126 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2127 pit_type par_end, bool full_source)
2129 OutputParams runparams(¶ms().encoding());
2130 runparams.nice = true;
2131 runparams.flavor = OutputParams::LATEX;
2132 runparams.linelen = lyxrc.plaintext_linelen;
2133 // No side effect of file copying and image conversion
2134 runparams.dryrun = true;
2138 os << "% " << _("Preview source code") << "\n\n";
2139 d->texrow.newline();
2140 d->texrow.newline();
2142 writeLaTeXSource(os, filePath(), runparams, true, true);
2144 writeDocBookSource(os, absFileName(), runparams, false);
2147 runparams.par_begin = par_begin;
2148 runparams.par_end = par_end;
2149 if (par_begin + 1 == par_end)
2151 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2155 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2156 convert<docstring>(par_begin),
2157 convert<docstring>(par_end - 1))
2159 d->texrow.newline();
2160 d->texrow.newline();
2161 // output paragraphs
2163 latexParagraphs(*this, text(), os, d->texrow, runparams);
2166 docbookParagraphs(paragraphs(), *this, os, runparams);
2172 ErrorList & Buffer::errorList(string const & type) const
2174 static ErrorList emptyErrorList;
2175 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2176 if (I == d->errorLists.end())
2177 return emptyErrorList;
2183 void Buffer::structureChanged() const
2186 gui_->structureChanged();
2190 void Buffer::errors(string const & err) const
2197 void Buffer::message(docstring const & msg) const
2204 void Buffer::setBusy(bool on) const
2211 void Buffer::setReadOnly(bool on) const
2214 d->wa_->setReadOnly(on);
2218 void Buffer::updateTitles() const
2221 d->wa_->updateTitles();
2225 void Buffer::resetAutosaveTimers() const
2228 gui_->resetAutosaveTimers();
2232 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2241 class AutoSaveBuffer : public ForkedProcess {
2244 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2245 : buffer_(buffer), fname_(fname) {}
2247 virtual boost::shared_ptr<ForkedProcess> clone() const
2249 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2254 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2255 from_utf8(fname_.absFilename())));
2256 return run(DontWait);
2260 virtual int generateChild();
2262 Buffer const & buffer_;
2267 int AutoSaveBuffer::generateChild()
2269 // tmp_ret will be located (usually) in /tmp
2270 // will that be a problem?
2271 // Note that this calls ForkedCalls::fork(), so it's
2272 // ok cross-platform.
2273 pid_t const pid = fork();
2274 // If you want to debug the autosave
2275 // you should set pid to -1, and comment out the fork.
2276 if (pid != 0 && pid != -1)
2279 // pid = -1 signifies that lyx was unable
2280 // to fork. But we will do the save
2282 bool failed = false;
2283 FileName const tmp_ret = FileName::tempName("lyxauto");
2284 if (!tmp_ret.empty()) {
2285 buffer_.writeFile(tmp_ret);
2286 // assume successful write of tmp_ret
2287 if (!tmp_ret.moveTo(fname_))
2293 // failed to write/rename tmp_ret so try writing direct
2294 if (!buffer_.writeFile(fname_)) {
2295 // It is dangerous to do this in the child,
2296 // but safe in the parent, so...
2297 if (pid == -1) // emit message signal.
2298 buffer_.message(_("Autosave failed!"));
2302 if (pid == 0) // we are the child so...
2311 // Perfect target for a thread...
2312 void Buffer::autoSave() const
2314 if (isBakClean() || isReadonly()) {
2315 // We don't save now, but we'll try again later
2316 resetAutosaveTimers();
2320 // emit message signal.
2321 message(_("Autosaving current document..."));
2323 // create autosave filename
2324 string fname = filePath();
2326 fname += d->filename.onlyFileName();
2329 AutoSaveBuffer autosave(*this, FileName(fname));
2333 resetAutosaveTimers();
2337 void Buffer::resetChildDocuments(bool close_them) const
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();
2345 resetParentBuffer(this, ip, close_them);
2348 if (use_gui && masterBuffer() == this)
2349 updateLabels(*this);
2351 // clear references to children in macro tables
2352 d->children_positions.clear();
2353 d->position_to_children.clear();
2357 void Buffer::loadChildDocuments() const
2359 bool parse_error = false;
2361 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2362 if (it->lyxCode() != INCLUDE_CODE)
2364 InsetCommand const & inset = static_cast<InsetCommand const &>(*it);
2365 InsetCommandParams const & ip = inset.params();
2366 Buffer * child = loadIfNeeded(*this, ip);
2369 parse_error |= !child->errorList("Parse").empty();
2370 child->loadChildDocuments();
2373 if (use_gui && masterBuffer() == this)
2374 updateLabels(*this);
2380 string Buffer::bufferFormat() const
2390 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2391 string & result_file) const
2393 string backend_format;
2394 OutputParams runparams(¶ms().encoding());
2395 runparams.flavor = OutputParams::LATEX;
2396 runparams.linelen = lyxrc.plaintext_linelen;
2397 vector<string> backs = backends();
2398 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2399 // Get shortest path to format
2400 Graph::EdgePath path;
2401 for (vector<string>::const_iterator it = backs.begin();
2402 it != backs.end(); ++it) {
2403 Graph::EdgePath p = theConverters().getPath(*it, format);
2404 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2405 backend_format = *it;
2410 runparams.flavor = theConverters().getFlavor(path);
2412 Alert::error(_("Couldn't export file"),
2413 bformat(_("No information for exporting the format %1$s."),
2414 formats.prettyName(format)));
2418 backend_format = format;
2419 // FIXME: Don't hardcode format names here, but use a flag
2420 if (backend_format == "pdflatex")
2421 runparams.flavor = OutputParams::PDFLATEX;
2424 string filename = latexName(false);
2425 filename = addName(temppath(), filename);
2426 filename = changeExtension(filename,
2427 formats.extension(backend_format));
2430 updateMacroInstances();
2432 // Plain text backend
2433 if (backend_format == "text")
2434 writePlaintextFile(*this, FileName(filename), runparams);
2436 else if (backend_format == "lyx")
2437 writeFile(FileName(filename));
2439 else if (isDocBook()) {
2440 runparams.nice = !put_in_tempdir;
2441 makeDocBookFile(FileName(filename), runparams);
2444 else if (backend_format == format) {
2445 runparams.nice = true;
2446 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2448 } else if (!lyxrc.tex_allows_spaces
2449 && contains(filePath(), ' ')) {
2450 Alert::error(_("File name error"),
2451 _("The directory path to the document cannot contain spaces."));
2454 runparams.nice = false;
2455 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2459 string const error_type = (format == "program")
2460 ? "Build" : bufferFormat();
2461 string const ext = formats.extension(format);
2462 FileName const tmp_result_file(changeExtension(filename, ext));
2463 bool const success = theConverters().convert(this, FileName(filename),
2464 tmp_result_file, FileName(absFileName()), backend_format, format,
2465 errorList(error_type));
2466 // Emit the signal to show the error list.
2467 if (format != backend_format)
2472 if (put_in_tempdir) {
2473 result_file = tmp_result_file.absFilename();
2477 result_file = changeExtension(absFileName(), ext);
2478 // We need to copy referenced files (e. g. included graphics
2479 // if format == "dvi") to the result dir.
2480 vector<ExportedFile> const files =
2481 runparams.exportdata->externalFiles(format);
2482 string const dest = onlyPath(result_file);
2483 CopyStatus status = SUCCESS;
2484 for (vector<ExportedFile>::const_iterator it = files.begin();
2485 it != files.end() && status != CANCEL; ++it) {
2486 string const fmt = formats.getFormatFromFile(it->sourceName);
2487 status = copyFile(fmt, it->sourceName,
2488 makeAbsPath(it->exportName, dest),
2489 it->exportName, status == FORCE);
2491 if (status == CANCEL) {
2492 message(_("Document export cancelled."));
2493 } else if (tmp_result_file.exists()) {
2494 // Finally copy the main file
2495 status = copyFile(format, tmp_result_file,
2496 FileName(result_file), result_file,
2498 message(bformat(_("Document exported as %1$s "
2500 formats.prettyName(format),
2501 makeDisplayPath(result_file)));
2503 // This must be a dummy converter like fax (bug 1888)
2504 message(bformat(_("Document exported as %1$s"),
2505 formats.prettyName(format)));
2512 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2515 return doExport(format, put_in_tempdir, result_file);
2519 bool Buffer::preview(string const & format) const
2522 if (!doExport(format, true, result_file))
2524 return formats.view(*this, FileName(result_file), format);
2528 bool Buffer::isExportable(string const & format) const
2530 vector<string> backs = backends();
2531 for (vector<string>::const_iterator it = backs.begin();
2532 it != backs.end(); ++it)
2533 if (theConverters().isReachable(*it, format))
2539 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2541 vector<string> backs = backends();
2542 vector<Format const *> result =
2543 theConverters().getReachable(backs[0], only_viewable, true);
2544 for (vector<string>::const_iterator it = backs.begin() + 1;
2545 it != backs.end(); ++it) {
2546 vector<Format const *> r =
2547 theConverters().getReachable(*it, only_viewable, false);
2548 result.insert(result.end(), r.begin(), r.end());
2554 vector<string> Buffer::backends() const
2557 if (params().getTextClass().isTeXClassAvailable()) {
2558 v.push_back(bufferFormat());
2559 // FIXME: Don't hardcode format names here, but use a flag
2560 if (v.back() == "latex")
2561 v.push_back("pdflatex");
2563 v.push_back("text");
2569 bool Buffer::readFileHelper(FileName const & s)
2571 // File information about normal file
2573 docstring const file = makeDisplayPath(s.absFilename(), 50);
2574 docstring text = bformat(_("The specified document\n%1$s"
2575 "\ncould not be read."), file);
2576 Alert::error(_("Could not read document"), text);
2580 // Check if emergency save file exists and is newer.
2581 FileName const e(s.absFilename() + ".emergency");
2583 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2584 docstring const file = makeDisplayPath(s.absFilename(), 20);
2585 docstring const text =
2586 bformat(_("An emergency save of the document "
2588 "Recover emergency save?"), file);
2589 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2590 _("&Recover"), _("&Load Original"),
2594 // the file is not saved if we load the emergency file.
2604 // Now check if autosave file is newer.
2605 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2607 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2608 docstring const file = makeDisplayPath(s.absFilename(), 20);
2609 docstring const text =
2610 bformat(_("The backup of the document "
2611 "%1$s is newer.\n\nLoad the "
2612 "backup instead?"), file);
2613 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2614 _("&Load backup"), _("Load &original"),
2618 // the file is not saved if we load the autosave file.
2622 // Here we delete the autosave
2633 bool Buffer::loadLyXFile(FileName const & s)
2635 if (s.isReadableFile()) {
2636 if (readFileHelper(s)) {
2637 lyxvc().file_found_hook(s);
2638 if (!s.isWritable())
2643 docstring const file = makeDisplayPath(s.absFilename(), 20);
2644 // Here we probably should run
2645 if (LyXVC::file_not_found_hook(s)) {
2646 docstring const text =
2647 bformat(_("Do you want to retrieve the document"
2648 " %1$s from version control?"), file);
2649 int const ret = Alert::prompt(_("Retrieve from version control?"),
2650 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2653 // How can we know _how_ to do the checkout?
2654 // With the current VC support it has to be,
2655 // a RCS file since CVS do not have special ,v files.
2657 return loadLyXFile(s);
2665 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2667 TeXErrors::Errors::const_iterator cit = terr.begin();
2668 TeXErrors::Errors::const_iterator end = terr.end();
2670 for (; cit != end; ++cit) {
2673 int errorRow = cit->error_in_line;
2674 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2680 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2681 } while (found && id_start == id_end && pos_start == pos_end);
2683 errorList.push_back(ErrorItem(cit->error_desc,
2684 cit->error_text, id_start, pos_start, pos_end));