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 // fold macros if possible, still with parent buffer as the
1132 // macros will be put in the prefix anyway.
1134 updateMacroInstances();
1136 // if we are doing a real file with body, even if this is the
1137 // child of some other buffer, let's cut the link here.
1138 // This happens for example if only a child document is printed.
1139 Buffer const * save_parent = 0;
1140 if (output_preamble) {
1141 // output the macros visible for this buffer
1142 writeParentMacros(os);
1144 save_parent = d->parent_buffer;
1145 d->parent_buffer = 0;
1148 loadChildDocuments();
1151 latexParagraphs(*this, paragraphs(), os, d->texrow, runparams);
1153 // Restore the parenthood if needed
1154 if (output_preamble) {
1155 d->parent_buffer = save_parent;
1157 // restore macros with correct parent buffer (especially
1158 // important for the redefinition flag which depends on the
1163 // add this just in case after all the paragraphs
1165 d->texrow.newline();
1167 if (output_preamble) {
1168 os << "\\end{document}\n";
1169 d->texrow.newline();
1170 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1172 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1174 runparams_in.encoding = runparams.encoding;
1176 // Just to be sure. (Asger)
1177 d->texrow.newline();
1179 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1180 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1184 bool Buffer::isLatex() const
1186 return params().getTextClass().outputType() == LATEX;
1190 bool Buffer::isLiterate() const
1192 return params().getTextClass().outputType() == LITERATE;
1196 bool Buffer::isDocBook() const
1198 return params().getTextClass().outputType() == DOCBOOK;
1202 void Buffer::makeDocBookFile(FileName const & fname,
1203 OutputParams const & runparams,
1204 bool const body_only) const
1206 LYXERR(Debug::LATEX, "makeDocBookFile...");
1209 if (!openFileWrite(ofs, fname))
1212 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1216 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1220 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1221 OutputParams const & runparams,
1222 bool const only_body) const
1224 LaTeXFeatures features(*this, params(), runparams);
1229 TextClass const & tclass = params().getTextClass();
1230 string const top_element = tclass.latexname();
1233 if (runparams.flavor == OutputParams::XML)
1234 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1237 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1240 if (! tclass.class_header().empty())
1241 os << from_ascii(tclass.class_header());
1242 else if (runparams.flavor == OutputParams::XML)
1243 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1244 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1246 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1248 docstring preamble = from_utf8(params().preamble);
1249 if (runparams.flavor != OutputParams::XML ) {
1250 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1251 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1252 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1253 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1256 string const name = runparams.nice
1257 ? changeExtension(absFileName(), ".sgml") : fname;
1258 preamble += features.getIncludedFiles(name);
1259 preamble += features.getLyXSGMLEntities();
1261 if (!preamble.empty()) {
1262 os << "\n [ " << preamble << " ]";
1267 string top = top_element;
1269 if (runparams.flavor == OutputParams::XML)
1270 top += params().language->code();
1272 top += params().language->code().substr(0,2);
1275 if (!params().options.empty()) {
1277 top += params().options;
1280 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1281 << " file was created by LyX " << lyx_version
1282 << "\n See http://www.lyx.org/ for more information -->\n";
1284 params().getTextClass().counters().reset();
1286 loadChildDocuments();
1288 sgml::openTag(os, top);
1290 docbookParagraphs(paragraphs(), *this, os, runparams);
1291 sgml::closeTag(os, top_element);
1295 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1296 // Other flags: -wall -v0 -x
1297 int Buffer::runChktex()
1301 // get LaTeX-Filename
1302 FileName const path(temppath());
1303 string const name = addName(path.absFilename(), latexName());
1304 string const org_path = filePath();
1306 PathChanger p(path); // path to LaTeX file
1307 message(_("Running chktex..."));
1309 // Generate the LaTeX file if neccessary
1310 OutputParams runparams(¶ms().encoding());
1311 runparams.flavor = OutputParams::LATEX;
1312 runparams.nice = false;
1313 makeLaTeXFile(FileName(name), org_path, runparams);
1316 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1317 int const res = chktex.run(terr); // run chktex
1320 Alert::error(_("chktex failure"),
1321 _("Could not run chktex successfully."));
1322 } else if (res > 0) {
1323 ErrorList & errlist = d->errorLists["ChkTeX"];
1325 bufferErrors(terr, errlist);
1336 void Buffer::validate(LaTeXFeatures & features) const
1338 params().validate(features);
1340 loadChildDocuments();
1342 for_each(paragraphs().begin(), paragraphs().end(),
1343 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1345 if (lyxerr.debugging(Debug::LATEX)) {
1346 features.showStruct();
1351 void Buffer::getLabelList(vector<docstring> & list) const
1353 /// if this is a child document and the parent is already loaded
1354 /// Use the parent's list instead [ale990407]
1355 Buffer const * tmp = masterBuffer();
1357 lyxerr << "masterBuffer() failed!" << endl;
1361 tmp->getLabelList(list);
1365 loadChildDocuments();
1367 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1368 it.nextInset()->getLabelList(*this, list);
1372 void Buffer::updateBibfilesCache() const
1374 // if this is a child document and the parent is already loaded
1375 // update the parent's cache instead
1376 Buffer const * tmp = masterBuffer();
1379 tmp->updateBibfilesCache();
1383 d->bibfilesCache_.clear();
1384 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1385 if (it->lyxCode() == BIBTEX_CODE) {
1386 InsetBibtex const & inset =
1387 static_cast<InsetBibtex const &>(*it);
1388 EmbeddedFileList const bibfiles = inset.getFiles(*this);
1389 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1392 } else if (it->lyxCode() == INCLUDE_CODE) {
1393 InsetInclude & inset =
1394 static_cast<InsetInclude &>(*it);
1395 inset.updateBibfilesCache(*this);
1396 EmbeddedFileList const & bibfiles =
1397 inset.getBibfilesCache(*this);
1398 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1406 EmbeddedFileList const & Buffer::getBibfilesCache() const
1408 // if this is a child document and the parent is already loaded
1409 // use the parent's cache instead
1410 Buffer const * tmp = masterBuffer();
1413 return tmp->getBibfilesCache();
1415 // We update the cache when first used instead of at loading time.
1416 if (d->bibfilesCache_.empty())
1417 const_cast<Buffer *>(this)->updateBibfilesCache();
1419 return d->bibfilesCache_;
1423 bool Buffer::isDepClean(string const & name) const
1425 DepClean::const_iterator const it = d->dep_clean.find(name);
1426 if (it == d->dep_clean.end())
1432 void Buffer::markDepClean(string const & name)
1434 d->dep_clean[name] = true;
1438 bool Buffer::dispatch(string const & command, bool * result)
1440 return dispatch(lyxaction.lookupFunc(command), result);
1444 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1446 bool dispatched = true;
1448 switch (func.action) {
1449 case LFUN_BUFFER_EXPORT: {
1450 bool const tmp = doExport(to_utf8(func.argument()), false);
1463 void Buffer::changeLanguage(Language const * from, Language const * to)
1468 for_each(par_iterator_begin(),
1470 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1474 bool Buffer::isMultiLingual() const
1476 ParConstIterator end = par_iterator_end();
1477 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1478 if (it->isMultiLingual(params()))
1485 ParConstIterator Buffer::getParFromID(int const id) const
1487 ParConstIterator it = par_iterator_begin();
1488 ParConstIterator const end = par_iterator_end();
1491 // John says this is called with id == -1 from undo
1492 lyxerr << "getParFromID(), id: " << id << endl;
1496 for (; it != end; ++it)
1504 ParIterator Buffer::getParFromID(int const id)
1506 ParIterator it = par_iterator_begin();
1507 ParIterator const end = par_iterator_end();
1510 // John says this is called with id == -1 from undo
1511 lyxerr << "getParFromID(), id: " << id << endl;
1515 for (; it != end; ++it)
1523 bool Buffer::hasParWithID(int const id) const
1525 ParConstIterator const it = getParFromID(id);
1526 return it != par_iterator_end();
1530 ParIterator Buffer::par_iterator_begin()
1532 return lyx::par_iterator_begin(inset());
1536 ParIterator Buffer::par_iterator_end()
1538 return lyx::par_iterator_end(inset());
1542 ParConstIterator Buffer::par_iterator_begin() const
1544 return lyx::par_const_iterator_begin(inset());
1548 ParConstIterator Buffer::par_iterator_end() const
1550 return lyx::par_const_iterator_end(inset());
1554 Language const * Buffer::language() const
1556 return params().language;
1560 docstring const Buffer::B_(string const & l10n) const
1562 return params().B_(l10n);
1566 bool Buffer::isClean() const
1568 return d->lyx_clean;
1572 bool Buffer::isBakClean() const
1574 return d->bak_clean;
1578 bool Buffer::isExternallyModified(CheckMethod method) const
1580 BOOST_ASSERT(d->filename.exists());
1581 // if method == timestamp, check timestamp before checksum
1582 return (method == checksum_method
1583 || d->timestamp_ != d->filename.lastModified())
1584 && d->checksum_ != d->filename.checksum();
1588 void Buffer::saveCheckSum(FileName const & file) const
1590 if (file.exists()) {
1591 d->timestamp_ = file.lastModified();
1592 d->checksum_ = file.checksum();
1594 // in the case of save to a new file.
1601 void Buffer::markClean() const
1603 if (!d->lyx_clean) {
1604 d->lyx_clean = true;
1607 // if the .lyx file has been saved, we don't need an
1609 d->bak_clean = true;
1613 void Buffer::markBakClean() const
1615 d->bak_clean = true;
1619 void Buffer::setUnnamed(bool flag)
1625 bool Buffer::isUnnamed() const
1631 // FIXME: this function should be moved to buffer_pimpl.C
1632 void Buffer::markDirty()
1635 d->lyx_clean = false;
1638 d->bak_clean = false;
1640 DepClean::iterator it = d->dep_clean.begin();
1641 DepClean::const_iterator const end = d->dep_clean.end();
1643 for (; it != end; ++it)
1648 FileName Buffer::fileName() const
1654 string Buffer::absFileName() const
1656 return d->filename.absFilename();
1660 string Buffer::filePath() const
1662 return d->filename.onlyPath().absFilename() + "/";
1666 bool Buffer::isReadonly() const
1668 return d->read_only;
1672 void Buffer::setParent(Buffer const * buffer)
1674 // Avoids recursive include.
1675 d->parent_buffer = buffer == this ? 0 : buffer;
1680 Buffer const * Buffer::parent()
1682 return d->parent_buffer;
1686 Buffer const * Buffer::masterBuffer() const
1688 if (!d->parent_buffer)
1691 return d->parent_buffer->masterBuffer();
1695 template<typename M>
1696 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
1701 typename M::iterator it = m.lower_bound(x);
1702 if (it == m.begin())
1710 MacroData const * Buffer::getBufferMacro(docstring const & name,
1711 DocIterator const & pos) const
1713 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
1715 // if paragraphs have no macro context set, pos will be empty
1719 // we haven't found anything yet
1720 DocIterator bestPos = par_iterator_begin();
1721 MacroData const * bestData = 0;
1723 // find macro definitions for name
1724 Impl::NamePositionScopeMacroMap::iterator nameIt
1725 = d->macros.find(name);
1726 if (nameIt != d->macros.end()) {
1727 // find last definition in front of pos or at pos itself
1728 Impl::PositionScopeMacroMap::const_iterator it
1729 = greatest_below(nameIt->second, pos);
1730 if (it != nameIt->second.end()) {
1732 // scope ends behind pos?
1733 if (pos < it->second.first) {
1734 // Looks good, remember this. If there
1735 // is no external macro behind this,
1736 // we found the right one already.
1737 bestPos = it->first;
1738 bestData = &it->second.second;
1742 // try previous macro if there is one
1743 if (it == nameIt->second.begin())
1750 // find macros in included files
1751 Impl::PositionScopeBufferMap::const_iterator it
1752 = greatest_below(d->position_to_children, pos);
1753 if (it != d->position_to_children.end()) {
1755 // do we know something better (i.e. later) already?
1756 if (it->first < bestPos )
1759 // scope ends behind pos?
1760 if (pos < it->second.first) {
1761 // look for macro in external file
1762 d->macro_lock = true;
1763 MacroData const * data
1764 = it->second.second->getMacro(name, false);
1765 d->macro_lock = false;
1767 bestPos = it->first;
1773 // try previous file if there is one
1774 if (it == d->position_to_children.begin())
1780 // return the best macro we have found
1785 MacroData const * Buffer::getMacro(docstring const & name,
1786 DocIterator const & pos, bool global) const
1791 // query buffer macros
1792 MacroData const * data = getBufferMacro(name, pos);
1796 // If there is a master buffer, query that
1797 if (d->parent_buffer) {
1798 d->macro_lock = true;
1799 MacroData const * macro
1800 = d->parent_buffer->getMacro(name, *this, false);
1801 d->macro_lock = false;
1807 data = MacroTable::globalMacros().get(name);
1816 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
1818 // set scope end behind the last paragraph
1819 DocIterator scope = par_iterator_begin();
1820 scope.pit() = scope.lastpit() + 1;
1822 return getMacro(name, scope, global);
1826 MacroData const * Buffer::getMacro(docstring const & name, Buffer const & child, bool global) const
1828 // look where the child buffer is included first
1829 Impl::BufferPositionMap::iterator it
1830 = d->children_positions.find(&child);
1831 if (it == d->children_positions.end())
1834 // check for macros at the inclusion position
1835 return getMacro(name, it->second, global);
1839 void Buffer::updateEnvironmentMacros(DocIterator & it,
1841 DocIterator & scope) const
1843 Paragraph & par = it.paragraph();
1845 = par.params().depth();
1846 Length const & leftIndent
1847 = par.params().leftIndent();
1849 // look for macros in each paragraph
1850 while (it.pit() <= lastpit) {
1851 Paragraph & par = it.paragraph();
1854 if ((par.params().depth() > depth
1855 || par.params().leftIndent() != leftIndent)
1856 && par.layout()->isEnvironment()) {
1857 updateBlockMacros(it, scope);
1861 // iterate over the insets of the current paragraph
1862 InsetList const & insets = par.insetList();
1863 InsetList::const_iterator iit = insets.begin();
1864 InsetList::const_iterator end = insets.end();
1865 for (; iit != end; ++iit) {
1866 it.pos() = iit->pos;
1868 // is it a nested text inset?
1869 if (iit->inset->asInsetText()) {
1870 // Inset needs its own scope?
1871 InsetText const * itext
1872 = iit->inset->asInsetText();
1873 bool newScope = itext->isMacroScope(*this);
1875 // scope which ends just behind die inset
1876 DocIterator insetScope = it;
1879 // collect macros in inset
1880 it.push_back(CursorSlice(*iit->inset));
1881 updateInsetMacros(it, newScope ? insetScope : scope);
1886 // is it an external file?
1887 if (iit->inset->lyxCode() == INCLUDE_CODE) {
1888 // get buffer of external file
1889 InsetCommand const & inset
1890 = static_cast<InsetCommand const &>(*iit->inset);
1891 InsetCommandParams const & ip = inset.params();
1892 d->macro_lock = true;
1893 Buffer * child = loadIfNeeded(*this, ip);
1894 d->macro_lock = false;
1898 // register it, but only when it is
1899 // included first in the buffer
1900 if (d->children_positions.find(child)
1901 == d->children_positions.end())
1902 d->children_positions[child] = it;
1904 // register child with its scope
1905 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
1910 if (iit->inset->lyxCode() != MATHMACRO_CODE)
1914 MathMacroTemplate & macroTemplate
1915 = static_cast<MathMacroTemplate &>(*iit->inset);
1916 MacroContext mc(*this, it);
1917 macroTemplate.updateToContext(mc);
1920 bool valid = macroTemplate.validMacro();
1921 // FIXME: Should be fixNameAndCheckIfValid() in fact,
1922 // then the BufferView's cursor will be invalid in
1923 // some cases which leads to crashes.
1928 d->macros[macroTemplate.name()][it]
1929 = Impl::ScopeMacro(scope, MacroData(*this, it));
1939 void Buffer::updateBlockMacros(DocIterator & it, DocIterator & scope) const
1941 Paragraph & par = it.paragraph();
1943 // set scope for macros in this paragraph:
1944 // * either the "old" outer scope
1945 // * or the scope ending after the environment
1946 if (par.layout()->isEnvironment()) {
1947 // find end of environment block,
1948 DocIterator envEnd = it;
1949 pit_type n = it.lastpit() + 1;
1950 depth_type depth = par.params().depth();
1951 Length const & length = par.params().leftIndent();
1952 // looping through the paragraph, basically until
1953 // the layout changes or the depth gets smaller.
1954 // (the logic of output_latex.cpp's TeXEnvironment)
1957 if (envEnd.pit() == n)
1959 } while (par.layout() == envEnd.paragraph().layout()
1960 || depth < envEnd.paragraph().params().depth()
1961 || length != envEnd.paragraph().params().leftIndent());
1963 // collect macros from environment block
1964 updateEnvironmentMacros(it, envEnd.pit() - 1, envEnd);
1966 // collect macros from paragraph
1967 updateEnvironmentMacros(it, it.pit(), scope);
1972 void Buffer::updateInsetMacros(DocIterator & it, DocIterator & scope) const
1974 // look for macros in each paragraph
1975 pit_type n = it.lastpit() + 1;
1976 while (it.pit() < n)
1977 updateBlockMacros(it, scope);
1981 void Buffer::updateMacros() const
1986 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
1988 // start with empty table
1990 d->children_positions.clear();
1991 d->position_to_children.clear();
1993 // Iterate over buffer, starting with first paragraph
1994 // The scope must be bigger than any lookup DocIterator
1995 // later. For the global lookup, lastpit+1 is used, hence
1996 // we use lastpit+2 here.
1997 DocIterator it = par_iterator_begin();
1998 DocIterator outerScope = it;
1999 outerScope.pit() = outerScope.lastpit() + 2;
2000 updateInsetMacros(it, outerScope);
2004 void Buffer::updateMacroInstances() const
2006 LYXERR(Debug::MACROS, "updateMacroInstances for "
2007 << d->filename.onlyFileName());
2008 ParConstIterator it = par_iterator_begin();
2009 ParConstIterator end = par_iterator_end();
2010 for (; it != end; it.forwardPos()) {
2011 // look for MathData cells in InsetMathNest insets
2012 Inset * inset = it.nextInset();
2016 InsetMath * minset = inset->asInsetMath();
2020 // update macro in all cells of the InsetMathNest
2021 DocIterator::idx_type n = minset->nargs();
2022 MacroContext mc = MacroContext(*this, it);
2023 for (DocIterator::idx_type i = 0; i < n; ++i) {
2024 MathData & data = minset->cell(i);
2025 data.updateMacros(0, mc);
2031 void Buffer::listMacroNames(MacroNameSet & macros) const
2036 d->macro_lock = true;
2038 // loop over macro names
2039 Impl::NamePositionScopeMacroMap::iterator nameIt
2040 = d->macros.begin();
2041 Impl::NamePositionScopeMacroMap::iterator nameEnd
2043 for (; nameIt != nameEnd; ++nameIt)
2044 macros.insert(nameIt->first);
2046 // loop over children
2047 Impl::BufferPositionMap::iterator it
2048 = d->children_positions.begin();
2049 Impl::BufferPositionMap::iterator end
2050 = d->children_positions.end();
2051 for (; it != end; ++it)
2052 it->first->listMacroNames(macros);
2055 if (d->parent_buffer)
2056 d->parent_buffer->listMacroNames(macros);
2058 d->macro_lock = false;
2062 void Buffer::writeParentMacros(odocstream & os) const
2064 if (!d->parent_buffer)
2067 // collect macro names
2069 d->parent_buffer->listMacroNames(names);
2071 // resolve and output them
2072 MacroNameSet::iterator it = names.begin();
2073 MacroNameSet::iterator end = names.end();
2074 for (; it != end; ++it) {
2076 MacroData const * data =
2077 d->parent_buffer->getMacro(*it, *this, false);
2079 data->write(os, true);
2084 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2087 //FIXME: This does not work for child documents yet.
2088 BOOST_ASSERT(code == CITE_CODE || code == REF_CODE);
2089 // Check if the label 'from' appears more than once
2090 vector<docstring> labels;
2093 if (code == CITE_CODE) {
2095 keys.fillWithBibKeys(this);
2096 BiblioInfo::const_iterator bit = keys.begin();
2097 BiblioInfo::const_iterator bend = keys.end();
2099 for (; bit != bend; ++bit)
2101 labels.push_back(bit->first);
2104 getLabelList(labels);
2105 paramName = "reference";
2108 if (count(labels.begin(), labels.end(), from) > 1)
2111 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2112 if (it->lyxCode() == code) {
2113 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2114 docstring const oldValue = inset.getParam(paramName);
2115 if (oldValue == from)
2116 inset.setParam(paramName, to);
2122 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2123 pit_type par_end, bool full_source)
2125 OutputParams runparams(¶ms().encoding());
2126 runparams.nice = true;
2127 runparams.flavor = OutputParams::LATEX;
2128 runparams.linelen = lyxrc.plaintext_linelen;
2129 // No side effect of file copying and image conversion
2130 runparams.dryrun = true;
2134 os << "% " << _("Preview source code") << "\n\n";
2135 d->texrow.newline();
2136 d->texrow.newline();
2138 writeLaTeXSource(os, filePath(), runparams, true, true);
2140 writeDocBookSource(os, absFileName(), runparams, false);
2143 runparams.par_begin = par_begin;
2144 runparams.par_end = par_end;
2145 if (par_begin + 1 == par_end)
2147 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2151 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2152 convert<docstring>(par_begin),
2153 convert<docstring>(par_end - 1))
2155 d->texrow.newline();
2156 d->texrow.newline();
2157 // output paragraphs
2159 latexParagraphs(*this, paragraphs(), os, d->texrow, runparams);
2162 docbookParagraphs(paragraphs(), *this, os, runparams);
2168 ErrorList & Buffer::errorList(string const & type) const
2170 static ErrorList emptyErrorList;
2171 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2172 if (I == d->errorLists.end())
2173 return emptyErrorList;
2179 void Buffer::structureChanged() const
2182 gui_->structureChanged();
2186 void Buffer::errors(string const & err) const
2193 void Buffer::message(docstring const & msg) const
2200 void Buffer::setBusy(bool on) const
2207 void Buffer::setReadOnly(bool on) const
2210 d->wa_->setReadOnly(on);
2214 void Buffer::updateTitles() const
2217 d->wa_->updateTitles();
2221 void Buffer::resetAutosaveTimers() const
2224 gui_->resetAutosaveTimers();
2228 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2237 class AutoSaveBuffer : public ForkedProcess {
2240 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2241 : buffer_(buffer), fname_(fname) {}
2243 virtual boost::shared_ptr<ForkedProcess> clone() const
2245 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2250 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2251 from_utf8(fname_.absFilename())));
2252 return run(DontWait);
2256 virtual int generateChild();
2258 Buffer const & buffer_;
2263 #if !defined (HAVE_FORK)
2267 int AutoSaveBuffer::generateChild()
2269 // tmp_ret will be located (usually) in /tmp
2270 // will that be a problem?
2271 pid_t const pid = fork();
2272 // If you want to debug the autosave
2273 // you should set pid to -1, and comment out the fork.
2274 if (pid != 0 && pid != -1)
2277 // pid = -1 signifies that lyx was unable
2278 // to fork. But we will do the save
2280 bool failed = false;
2281 FileName const tmp_ret = FileName::tempName("lyxauto");
2282 if (!tmp_ret.empty()) {
2283 buffer_.writeFile(tmp_ret);
2284 // assume successful write of tmp_ret
2285 if (!tmp_ret.moveTo(fname_))
2291 // failed to write/rename tmp_ret so try writing direct
2292 if (!buffer_.writeFile(fname_)) {
2293 // It is dangerous to do this in the child,
2294 // but safe in the parent, so...
2295 if (pid == -1) // emit message signal.
2296 buffer_.message(_("Autosave failed!"));
2300 if (pid == 0) // we are the child so...
2309 // Perfect target for a thread...
2310 void Buffer::autoSave() const
2312 if (isBakClean() || isReadonly()) {
2313 // We don't save now, but we'll try again later
2314 resetAutosaveTimers();
2318 // emit message signal.
2319 message(_("Autosaving current document..."));
2321 // create autosave filename
2322 string fname = filePath();
2324 fname += d->filename.onlyFileName();
2327 AutoSaveBuffer autosave(*this, FileName(fname));
2331 resetAutosaveTimers();
2335 void Buffer::resetChildDocuments(bool close_them) const
2337 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2338 if (it->lyxCode() != INCLUDE_CODE)
2340 InsetCommand const & inset = static_cast<InsetCommand const &>(*it);
2341 InsetCommandParams const & ip = inset.params();
2343 resetParentBuffer(this, ip, close_them);
2346 if (use_gui && masterBuffer() == this)
2347 updateLabels(*this);
2349 // clear references to children in macro tables
2350 d->children_positions.clear();
2351 d->position_to_children.clear();
2355 void Buffer::loadChildDocuments() const
2357 bool parse_error = false;
2359 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2360 if (it->lyxCode() != INCLUDE_CODE)
2362 InsetCommand const & inset = static_cast<InsetCommand const &>(*it);
2363 InsetCommandParams const & ip = inset.params();
2364 Buffer * child = loadIfNeeded(*this, ip);
2367 parse_error |= !child->errorList("Parse").empty();
2368 child->loadChildDocuments();
2371 if (use_gui && masterBuffer() == this)
2372 updateLabels(*this);
2378 string Buffer::bufferFormat() const
2388 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2389 string & result_file) const
2391 string backend_format;
2392 OutputParams runparams(¶ms().encoding());
2393 runparams.flavor = OutputParams::LATEX;
2394 runparams.linelen = lyxrc.plaintext_linelen;
2395 vector<string> backs = backends();
2396 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2397 // Get shortest path to format
2398 Graph::EdgePath path;
2399 for (vector<string>::const_iterator it = backs.begin();
2400 it != backs.end(); ++it) {
2401 Graph::EdgePath p = theConverters().getPath(*it, format);
2402 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2403 backend_format = *it;
2408 runparams.flavor = theConverters().getFlavor(path);
2410 Alert::error(_("Couldn't export file"),
2411 bformat(_("No information for exporting the format %1$s."),
2412 formats.prettyName(format)));
2416 backend_format = format;
2417 // FIXME: Don't hardcode format names here, but use a flag
2418 if (backend_format == "pdflatex")
2419 runparams.flavor = OutputParams::PDFLATEX;
2422 string filename = latexName(false);
2423 filename = addName(temppath(), filename);
2424 filename = changeExtension(filename,
2425 formats.extension(backend_format));
2428 updateMacroInstances();
2430 // Plain text backend
2431 if (backend_format == "text")
2432 writePlaintextFile(*this, FileName(filename), runparams);
2434 else if (backend_format == "lyx")
2435 writeFile(FileName(filename));
2437 else if (isDocBook()) {
2438 runparams.nice = !put_in_tempdir;
2439 makeDocBookFile(FileName(filename), runparams);
2442 else if (backend_format == format) {
2443 runparams.nice = true;
2444 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2446 } else if (!lyxrc.tex_allows_spaces
2447 && contains(filePath(), ' ')) {
2448 Alert::error(_("File name error"),
2449 _("The directory path to the document cannot contain spaces."));
2452 runparams.nice = false;
2453 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2457 string const error_type = (format == "program")
2458 ? "Build" : bufferFormat();
2459 string const ext = formats.extension(format);
2460 FileName const tmp_result_file(changeExtension(filename, ext));
2461 bool const success = theConverters().convert(this, FileName(filename),
2462 tmp_result_file, FileName(absFileName()), backend_format, format,
2463 errorList(error_type));
2464 // Emit the signal to show the error list.
2465 if (format != backend_format)
2471 result_file = tmp_result_file.absFilename();
2473 result_file = changeExtension(absFileName(), ext);
2474 // We need to copy referenced files (e. g. included graphics
2475 // if format == "dvi") to the result dir.
2476 vector<ExportedFile> const files =
2477 runparams.exportdata->externalFiles(format);
2478 string const dest = onlyPath(result_file);
2479 CopyStatus status = SUCCESS;
2480 for (vector<ExportedFile>::const_iterator it = files.begin();
2481 it != files.end() && status != CANCEL; ++it) {
2483 formats.getFormatFromFile(it->sourceName);
2484 status = copyFile(fmt, it->sourceName,
2485 makeAbsPath(it->exportName, dest),
2486 it->exportName, status == FORCE);
2488 if (status == CANCEL) {
2489 message(_("Document export cancelled."));
2490 } else if (tmp_result_file.exists()) {
2491 // Finally copy the main file
2492 status = copyFile(format, tmp_result_file,
2493 FileName(result_file), result_file,
2495 message(bformat(_("Document exported as %1$s "
2497 formats.prettyName(format),
2498 makeDisplayPath(result_file)));
2500 // This must be a dummy converter like fax (bug 1888)
2501 message(bformat(_("Document exported as %1$s"),
2502 formats.prettyName(format)));
2510 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2513 return doExport(format, put_in_tempdir, result_file);
2517 bool Buffer::preview(string const & format) const
2520 if (!doExport(format, true, result_file))
2522 return formats.view(*this, FileName(result_file), format);
2526 bool Buffer::isExportable(string const & format) const
2528 vector<string> backs = backends();
2529 for (vector<string>::const_iterator it = backs.begin();
2530 it != backs.end(); ++it)
2531 if (theConverters().isReachable(*it, format))
2537 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2539 vector<string> backs = backends();
2540 vector<Format const *> result =
2541 theConverters().getReachable(backs[0], only_viewable, true);
2542 for (vector<string>::const_iterator it = backs.begin() + 1;
2543 it != backs.end(); ++it) {
2544 vector<Format const *> r =
2545 theConverters().getReachable(*it, only_viewable, false);
2546 result.insert(result.end(), r.begin(), r.end());
2552 vector<string> Buffer::backends() const
2555 if (params().getTextClass().isTeXClassAvailable()) {
2556 v.push_back(bufferFormat());
2557 // FIXME: Don't hardcode format names here, but use a flag
2558 if (v.back() == "latex")
2559 v.push_back("pdflatex");
2561 v.push_back("text");
2567 bool Buffer::readFileHelper(FileName const & s)
2569 // File information about normal file
2571 docstring const file = makeDisplayPath(s.absFilename(), 50);
2572 docstring text = bformat(_("The specified document\n%1$s"
2573 "\ncould not be read."), file);
2574 Alert::error(_("Could not read document"), text);
2578 // Check if emergency save file exists and is newer.
2579 FileName const e(s.absFilename() + ".emergency");
2581 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2582 docstring const file = makeDisplayPath(s.absFilename(), 20);
2583 docstring const text =
2584 bformat(_("An emergency save of the document "
2586 "Recover emergency save?"), file);
2587 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2588 _("&Recover"), _("&Load Original"),
2592 // the file is not saved if we load the emergency file.
2602 // Now check if autosave file is newer.
2603 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2605 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2606 docstring const file = makeDisplayPath(s.absFilename(), 20);
2607 docstring const text =
2608 bformat(_("The backup of the document "
2609 "%1$s is newer.\n\nLoad the "
2610 "backup instead?"), file);
2611 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2612 _("&Load backup"), _("Load &original"),
2616 // the file is not saved if we load the autosave file.
2620 // Here we delete the autosave
2631 bool Buffer::loadLyXFile(FileName const & s)
2633 if (s.isReadableFile()) {
2634 if (readFileHelper(s)) {
2635 lyxvc().file_found_hook(s);
2636 if (!s.isWritable())
2641 docstring const file = makeDisplayPath(s.absFilename(), 20);
2642 // Here we probably should run
2643 if (LyXVC::file_not_found_hook(s)) {
2644 docstring const text =
2645 bformat(_("Do you want to retrieve the document"
2646 " %1$s from version control?"), file);
2647 int const ret = Alert::prompt(_("Retrieve from version control?"),
2648 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2651 // How can we know _how_ to do the checkout?
2652 // With the current VC support it has to be,
2653 // a RCS file since CVS do not have special ,v files.
2655 return loadLyXFile(s);
2663 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2665 TeXErrors::Errors::const_iterator cit = terr.begin();
2666 TeXErrors::Errors::const_iterator end = terr.end();
2668 for (; cit != end; ++cit) {
2671 int errorRow = cit->error_in_line;
2672 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2678 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2679 } while (found && id_start == id_end && pos_start == pos_end);
2681 errorList.push_back(ErrorItem(cit->error_desc,
2682 cit->error_text, id_start, pos_start, pos_end));