3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Stefan Schimanski
9 * Full author contact details are available in file CREDITS.
17 #include "BaseClassList.h"
18 #include "BiblioInfo.h"
19 #include "BranchList.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
25 #include "Converter.h"
27 #include "DocIterator.h"
28 #include "EmbeddedFiles.h"
30 #include "ErrorList.h"
33 #include "FuncRequest.h"
34 #include "InsetIterator.h"
35 #include "InsetList.h"
37 #include "LaTeXFeatures.h"
41 #include "LyXAction.h"
45 #include "output_docbook.h"
47 #include "output_latex.h"
48 #include "output_plaintext.h"
49 #include "paragraph_funcs.h"
50 #include "Paragraph.h"
51 #include "ParagraphParameters.h"
52 #include "ParIterator.h"
53 #include "PDFOptions.h"
57 #include "TexStream.h"
59 #include "TextClass.h"
60 #include "TocBackend.h"
62 #include "VCBackend.h"
66 #include "insets/InsetBibitem.h"
67 #include "insets/InsetBibtex.h"
68 #include "insets/InsetInclude.h"
69 #include "insets/InsetText.h"
71 #include "mathed/MacroTable.h"
72 #include "mathed/MathMacroTemplate.h"
73 #include "mathed/MathSupport.h"
75 #include "frontends/alert.h"
76 #include "frontends/Delegates.h"
77 #include "frontends/WorkAreaManager.h"
79 #include "graphics/Previews.h"
81 #include "support/convert.h"
82 #include "support/debug.h"
83 #include "support/ExceptionMessage.h"
84 #include "support/FileName.h"
85 #include "support/FileNameList.h"
86 #include "support/filetools.h"
87 #include "support/ForkedCalls.h"
88 #include "support/gettext.h"
89 #include "support/gzstream.h"
90 #include "support/lstrings.h"
91 #include "support/lyxalgo.h"
92 #include "support/os.h"
93 #include "support/Package.h"
94 #include "support/Path.h"
95 #include "support/textutils.h"
96 #include "support/types.h"
97 #include "support/FileZipListDir.h"
99 #include <boost/bind.hpp>
100 #include <boost/shared_ptr.hpp>
111 using namespace lyx::support;
115 namespace Alert = frontend::Alert;
116 namespace os = support::os;
120 int const LYX_FORMAT = 317; // Uwe Stöhr: float placement support for wrap floats
122 typedef map<string, bool> DepClean;
123 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
130 Impl(Buffer & parent, FileName const & file, bool readonly);
143 mutable TexRow texrow;
144 Buffer const * parent_buffer;
146 /// need to regenerate .tex?
150 mutable bool lyx_clean;
152 /// is autosave needed?
153 mutable bool bak_clean;
155 /// is this a unnamed file (New...)?
161 /// name of the file the buffer is associated with.
164 /** Set to true only when the file is fully loaded.
165 * Used to prevent the premature generation of previews
166 * and by the citation inset.
168 bool file_fully_loaded;
170 /// our Text that should be wrapped in an InsetText
174 mutable TocBackend toc_backend;
177 typedef pair<DocIterator, MacroData> ScopeMacro;
178 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
179 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
180 NamePositionScopeMacroMap macros;
183 /// positions of child buffers in the buffer
184 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
185 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
186 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
187 BufferPositionMap children_positions;
188 PositionScopeBufferMap position_to_children;
190 /// Container for all sort of Buffer dependant errors.
191 map<string, ErrorList> errorLists;
193 /// all embedded files of this buffer
194 EmbeddedFileList embedded_files;
196 /// timestamp and checksum used to test if the file has been externally
197 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
199 unsigned long checksum_;
202 frontend::WorkAreaManager * wa_;
207 /// A cache for the bibfiles (including bibfiles of loaded child
208 /// documents), needed for appropriate update of natbib labels.
209 mutable EmbeddedFileList bibfilesCache_;
211 mutable RefCache ref_cache_;
214 /// Creates the per buffer temporary directory
215 static FileName createBufferTmpDir()
218 // We are in our own directory. Why bother to mangle name?
219 // In fact I wrote this code to circumvent a problematic behaviour
220 // (bug?) of EMX mkstemp().
221 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
222 convert<string>(count++));
224 if (!tmpfl.createDirectory(0777)) {
225 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
226 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
227 from_utf8(tmpfl.absFilename())));
233 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
234 : parent_buffer(0), lyx_clean(true), bak_clean(true), unnamed(false),
235 read_only(readonly_), filename(file), file_fully_loaded(false),
236 inset(params), toc_backend(&parent), macro_lock(false),
237 embedded_files(), timestamp_(0), checksum_(0), wa_(0),
240 temppath = createBufferTmpDir();
241 inset.setBuffer(parent);
242 inset.setAutoBreakRows(true);
243 lyxvc.setBuffer(&parent);
245 wa_ = new frontend::WorkAreaManager;
249 Buffer::Buffer(string const & file, bool readonly)
250 : d(new Impl(*this, FileName(file), readonly)), gui_(0)
252 LYXERR(Debug::INFO, "Buffer::Buffer()");
254 d->inset.getText(0)->setMacrocontextPosition(par_iterator_begin());
260 LYXERR(Debug::INFO, "Buffer::~Buffer()");
261 // here the buffer should take care that it is
262 // saved properly, before it goes into the void.
264 // GuiView already destroyed
267 Buffer const * master = masterBuffer();
268 if (master != this && use_gui) {
269 // We are closing buf which was a child document so we
270 // must update the labels and section numbering of its master
272 updateLabels(*master);
273 master->updateMacros();
276 resetChildDocuments(false);
278 if (!d->temppath.destroyDirectory()) {
279 Alert::warning(_("Could not remove temporary directory"),
280 bformat(_("Could not remove the temporary directory %1$s"),
281 from_utf8(d->temppath.absFilename())));
284 // Remove any previewed LaTeX snippets associated with this buffer.
285 graphics::Previews::get().removeLoader(*this);
291 void Buffer::changed() const
298 frontend::WorkAreaManager & Buffer::workAreaManager() const
300 BOOST_ASSERT(d->wa_);
305 Text & Buffer::text() const
307 return const_cast<Text &>(d->inset.text_);
311 Inset & Buffer::inset() const
313 return const_cast<InsetText &>(d->inset);
317 BufferParams & Buffer::params()
323 BufferParams const & Buffer::params() const
329 ParagraphList & Buffer::paragraphs()
331 return text().paragraphs();
335 ParagraphList const & Buffer::paragraphs() const
337 return text().paragraphs();
341 LyXVC & Buffer::lyxvc()
347 LyXVC const & Buffer::lyxvc() const
353 string const Buffer::temppath() const
355 return d->temppath.absFilename();
359 TexRow const & Buffer::texrow() const
365 TocBackend & Buffer::tocBackend() const
367 return d->toc_backend;
371 EmbeddedFileList & Buffer::embeddedFiles()
373 return d->embedded_files;
377 EmbeddedFileList const & Buffer::embeddedFiles() const
379 return d->embedded_files;
383 bool Buffer::embedded() const
385 return params().embedded;
389 Undo & Buffer::undo()
395 string Buffer::latexName(bool const no_path) const
397 FileName latex_name = makeLatexName(d->filename);
398 return no_path ? latex_name.onlyFileName()
399 : latex_name.absFilename();
403 string Buffer::logName(LogType * type) const
405 string const filename = latexName(false);
407 if (filename.empty()) {
413 string const path = temppath();
415 FileName const fname(addName(temppath(),
416 onlyFilename(changeExtension(filename,
418 FileName const bname(
419 addName(path, onlyFilename(
420 changeExtension(filename,
421 formats.extension("literate") + ".out"))));
423 // If no Latex log or Build log is newer, show Build log
425 if (bname.exists() &&
426 (!fname.exists() || fname.lastModified() < bname.lastModified())) {
427 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
430 return bname.absFilename();
432 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
435 return fname.absFilename();
439 void Buffer::setReadonly(bool const flag)
441 if (d->read_only != flag) {
448 void Buffer::setFileName(string const & newfile)
450 d->filename = makeAbsPath(newfile);
451 setReadonly(d->filename.isReadOnly());
456 int Buffer::readHeader(Lexer & lex)
458 int unknown_tokens = 0;
460 int begin_header_line = -1;
462 // Initialize parameters that may be/go lacking in header:
463 params().branchlist().clear();
464 params().preamble.erase();
465 params().options.erase();
466 params().float_placement.erase();
467 params().paperwidth.erase();
468 params().paperheight.erase();
469 params().leftmargin.erase();
470 params().rightmargin.erase();
471 params().topmargin.erase();
472 params().bottommargin.erase();
473 params().headheight.erase();
474 params().headsep.erase();
475 params().footskip.erase();
476 params().columnsep.erase();
477 params().listings_params.clear();
478 params().clearLayoutModules();
479 params().pdfoptions().clear();
481 for (int i = 0; i < 4; ++i) {
482 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
483 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
486 ErrorList & errorList = d->errorLists["Parse"];
490 string const token = lex.getString();
495 if (token == "\\end_header")
499 if (token == "\\begin_header") {
500 begin_header_line = line;
504 LYXERR(Debug::PARSER, "Handling document header token: `"
507 string unknown = params().readToken(lex, token, d->filename.onlyPath());
508 if (!unknown.empty()) {
509 if (unknown[0] != '\\' && token == "\\textclass") {
510 Alert::warning(_("Unknown document class"),
511 bformat(_("Using the default document class, because the "
512 "class %1$s is unknown."), from_utf8(unknown)));
515 docstring const s = bformat(_("Unknown token: "
519 errorList.push_back(ErrorItem(_("Document header error"),
524 if (begin_header_line) {
525 docstring const s = _("\\begin_header is missing");
526 errorList.push_back(ErrorItem(_("Document header error"),
530 params().makeDocumentClass();
532 return unknown_tokens;
537 // changed to be public and have one parameter
538 // Returns false if "\end_document" is not read (Asger)
539 bool Buffer::readDocument(Lexer & lex)
541 ErrorList & errorList = d->errorLists["Parse"];
545 string const token = lex.getString();
546 if (token != "\\begin_document") {
547 docstring const s = _("\\begin_document is missing");
548 errorList.push_back(ErrorItem(_("Document header error"),
552 // we are reading in a brand new document
553 BOOST_ASSERT(paragraphs().empty());
557 if (params().outputChanges) {
558 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
559 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
560 LaTeXFeatures::isAvailable("xcolor");
562 if (!dvipost && !xcolorsoul) {
563 Alert::warning(_("Changes not shown in LaTeX output"),
564 _("Changes will not be highlighted in LaTeX output, "
565 "because neither dvipost nor xcolor/soul are installed.\n"
566 "Please install these packages or redefine "
567 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
568 } else if (!xcolorsoul) {
569 Alert::warning(_("Changes not shown in LaTeX output"),
570 _("Changes will not be highlighted in LaTeX output "
571 "when using pdflatex, because xcolor and soul are not installed.\n"
572 "Please install both packages or redefine "
573 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
578 bool const res = text().read(*this, lex, errorList, &(d->inset));
581 updateMacroInstances();
586 // needed to insert the selection
587 void Buffer::insertStringAsLines(ParagraphList & pars,
588 pit_type & pit, pos_type & pos,
589 Font const & fn, docstring const & str, bool autobreakrows)
593 // insert the string, don't insert doublespace
594 bool space_inserted = true;
595 for (docstring::const_iterator cit = str.begin();
596 cit != str.end(); ++cit) {
597 Paragraph & par = pars[pit];
599 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
600 breakParagraph(params(), pars, pit, pos,
601 par.layout()->isEnvironment());
604 space_inserted = true;
608 // do not insert consecutive spaces if !free_spacing
609 } else if ((*cit == ' ' || *cit == '\t') &&
610 space_inserted && !par.isFreeSpacing()) {
612 } else if (*cit == '\t') {
613 if (!par.isFreeSpacing()) {
614 // tabs are like spaces here
615 par.insertChar(pos, ' ', font, params().trackChanges);
617 space_inserted = true;
619 const pos_type n = 8 - pos % 8;
620 for (pos_type i = 0; i < n; ++i) {
621 par.insertChar(pos, ' ', font, params().trackChanges);
624 space_inserted = true;
626 } else if (!isPrintable(*cit)) {
627 // Ignore unprintables
630 // just insert the character
631 par.insertChar(pos, *cit, font, params().trackChanges);
633 space_inserted = (*cit == ' ');
640 bool Buffer::readString(string const & s)
642 params().compressed = false;
644 // remove dummy empty par
645 paragraphs().clear();
649 FileName const name = FileName::tempName();
650 switch (readFile(lex, name, true)) {
654 // We need to call lyx2lyx, so write the input to a file
655 ofstream os(name.toFilesystemEncoding().c_str());
658 return readFile(name);
668 bool Buffer::readFile(FileName const & filename)
670 FileName fname(filename);
671 // Check if the file is compressed.
672 string format = filename.guessFormatFromContents();
673 if (format == "zip") {
674 // decompress to a temp directory
675 LYXERR(Debug::FILES, filename << " is in zip format. Unzip to " << temppath());
676 ::unzipToDir(filename.toFilesystemEncoding(), temppath());
678 FileName lyxfile(addName(temppath(), "content.lyx"));
679 // if both manifest.txt and file.lyx exist, this is am embedded file
680 if (lyxfile.exists()) {
681 // if in bundled format, save checksum of the compressed file, not content.lyx
682 saveCheckSum(filename);
683 params().embedded = true;
687 // The embedded lyx file can also be compressed, for backward compatibility
688 format = fname.guessFormatFromContents();
689 if (format == "gzip" || format == "zip" || format == "compress")
690 params().compressed = true;
692 // remove dummy empty par
693 paragraphs().clear();
696 if (readFile(lex, fname) != success)
703 bool Buffer::isFullyLoaded() const
705 return d->file_fully_loaded;
709 void Buffer::setFullyLoaded(bool value)
711 d->file_fully_loaded = value;
715 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
718 BOOST_ASSERT(!filename.empty());
721 Alert::error(_("Document could not be read"),
722 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
727 string const token = lex.getString();
730 Alert::error(_("Document could not be read"),
731 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
735 // the first token _must_ be...
736 if (token != "\\lyxformat") {
737 lyxerr << "Token: " << token << endl;
739 Alert::error(_("Document format failure"),
740 bformat(_("%1$s is not a LyX document."),
741 from_utf8(filename.absFilename())));
746 string tmp_format = lex.getString();
747 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
748 // if present remove ".," from string.
749 string::size_type dot = tmp_format.find_first_of(".,");
750 //lyxerr << " dot found at " << dot << endl;
751 if (dot != string::npos)
752 tmp_format.erase(dot, 1);
753 int const file_format = convert<int>(tmp_format);
754 //lyxerr << "format: " << file_format << endl;
756 // save timestamp and checksum of the original disk file, making sure
757 // to not overwrite them with those of the file created in the tempdir
758 // when it has to be converted to the current format.
760 // Save the timestamp and checksum of disk file. If filename is an
761 // emergency file, save the timestamp and checksum of the original lyx file
762 // because isExternallyModified will check for this file. (BUG4193)
763 string diskfile = filename.absFilename();
764 if (suffixIs(diskfile, ".emergency"))
765 diskfile = diskfile.substr(0, diskfile.size() - 10);
766 saveCheckSum(FileName(diskfile));
769 if (file_format != LYX_FORMAT) {
772 // lyx2lyx would fail
775 FileName const tmpfile = FileName::tempName();
776 if (tmpfile.empty()) {
777 Alert::error(_("Conversion failed"),
778 bformat(_("%1$s is from a different"
779 " version of LyX, but a temporary"
780 " file for converting it could"
782 from_utf8(filename.absFilename())));
785 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
786 if (lyx2lyx.empty()) {
787 Alert::error(_("Conversion script not found"),
788 bformat(_("%1$s is from a different"
789 " version of LyX, but the"
790 " conversion script lyx2lyx"
791 " could not be found."),
792 from_utf8(filename.absFilename())));
795 ostringstream command;
796 command << os::python()
797 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
798 << " -t " << convert<string>(LYX_FORMAT)
799 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
800 << ' ' << quoteName(filename.toFilesystemEncoding());
801 string const command_str = command.str();
803 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
805 cmd_ret const ret = runCommand(command_str);
806 if (ret.first != 0) {
807 Alert::error(_("Conversion script failed"),
808 bformat(_("%1$s is from a different version"
809 " of LyX, but the lyx2lyx script"
810 " failed to convert it."),
811 from_utf8(filename.absFilename())));
814 bool const ret = readFile(tmpfile);
815 // Do stuff with tmpfile name and buffer name here.
816 return ret ? success : failure;
821 if (readDocument(lex)) {
822 Alert::error(_("Document format failure"),
823 bformat(_("%1$s ended unexpectedly, which means"
824 " that it is probably corrupted."),
825 from_utf8(filename.absFilename())));
828 d->file_fully_loaded = true;
833 // Should probably be moved to somewhere else: BufferView? LyXView?
834 bool Buffer::save() const
836 // We don't need autosaves in the immediate future. (Asger)
837 resetAutosaveTimers();
839 string const encodedFilename = d->filename.toFilesystemEncoding();
842 bool madeBackup = false;
844 // make a backup if the file already exists
845 if (lyxrc.make_backup && fileName().exists()) {
846 backupName = FileName(absFileName() + '~');
847 if (!lyxrc.backupdir_path.empty()) {
848 string const mangledName =
849 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
850 backupName = FileName(addName(lyxrc.backupdir_path,
853 if (fileName().copyTo(backupName)) {
856 Alert::error(_("Backup failure"),
857 bformat(_("Cannot create backup file %1$s.\n"
858 "Please check whether the directory exists and is writeable."),
859 from_utf8(backupName.absFilename())));
860 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
864 // ask if the disk file has been externally modified (use checksum method)
865 if (fileName().exists() && isExternallyModified(checksum_method)) {
866 docstring const file = makeDisplayPath(absFileName(), 20);
867 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
868 "you want to overwrite this file?"), file);
869 int const ret = Alert::prompt(_("Overwrite modified file?"),
870 text, 1, 1, _("&Overwrite"), _("&Cancel"));
875 if (writeFile(d->filename)) {
879 // Saving failed, so backup is not backup
881 backupName.moveTo(d->filename);
887 bool Buffer::writeFile(FileName const & fname) const
889 if (d->read_only && fname == d->filename)
895 if (params().embedded)
896 // first write the .lyx file to the temporary directory
897 content = FileName(addName(temppath(), "content.lyx"));
901 docstring const str = bformat(_("Saving document %1$s..."),
902 makeDisplayPath(content.absFilename()));
905 if (params().compressed) {
906 gz::ogzstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
907 retval = ofs && write(ofs);
909 ofstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
910 retval = ofs && write(ofs);
914 message(str + _(" could not write file!."));
918 removeAutosaveFile(d->filename.absFilename());
920 if (params().embedded) {
921 message(str + _(" writing embedded files!."));
922 // if embedding is enabled, write file.lyx and all the embedded files
923 // to the zip file fname.
924 if (!d->embedded_files.writeFile(fname, *this)) {
925 message(str + _(" could not write embedded files!."));
929 saveCheckSum(d->filename);
930 message(str + _(" done."));
936 bool Buffer::write(ostream & ofs) const
939 // Use the standard "C" locale for file output.
940 ofs.imbue(locale::classic());
943 // The top of the file should not be written by params().
945 // write out a comment in the top of the file
946 ofs << "#LyX " << lyx_version
947 << " created this file. For more info see http://www.lyx.org/\n"
948 << "\\lyxformat " << LYX_FORMAT << "\n"
949 << "\\begin_document\n";
951 /// For each author, set 'used' to true if there is a change
952 /// by this author in the document; otherwise set it to 'false'.
953 AuthorList::Authors::const_iterator a_it = params().authors().begin();
954 AuthorList::Authors::const_iterator a_end = params().authors().end();
955 for (; a_it != a_end; ++a_it)
956 a_it->second.setUsed(false);
958 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
959 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
960 for ( ; it != end; ++it)
961 it->checkAuthors(params().authors());
963 // now write out the buffer parameters.
964 ofs << "\\begin_header\n";
965 params().writeFile(ofs);
966 ofs << "\\end_header\n";
969 ofs << "\n\\begin_body\n";
970 text().write(*this, ofs);
971 ofs << "\n\\end_body\n";
973 // Write marker that shows file is complete
974 ofs << "\\end_document" << endl;
976 // Shouldn't really be needed....
979 // how to check if close went ok?
980 // Following is an attempt... (BE 20001011)
982 // good() returns false if any error occured, including some
984 // bad() returns true if something bad happened in the buffer,
985 // which should include file system full errors.
990 lyxerr << "File was not closed properly." << endl;
997 bool Buffer::makeLaTeXFile(FileName const & fname,
998 string const & original_path,
999 OutputParams const & runparams,
1000 bool output_preamble, bool output_body) const
1002 string const encoding = runparams.encoding->iconvName();
1003 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1006 try { ofs.reset(encoding); }
1007 catch (iconv_codecvt_facet_exception & e) {
1008 lyxerr << "Caught iconv exception: " << e.what() << endl;
1009 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1010 "verify that the support software for your encoding (%1$s) is "
1011 "properly installed"), from_ascii(encoding)));
1014 if (!openFileWrite(ofs, fname))
1017 //TexStream ts(ofs.rdbuf(), &texrow());
1018 ErrorList & errorList = d->errorLists["Export"];
1020 bool failed_export = false;
1023 writeLaTeXSource(ofs, original_path,
1024 runparams, output_preamble, output_body);
1026 catch (EncodingException & e) {
1027 odocstringstream ods;
1028 ods.put(e.failed_char);
1030 oss << "0x" << hex << e.failed_char << dec;
1031 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1032 " (code point %2$s)"),
1033 ods.str(), from_utf8(oss.str()));
1034 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1035 "representable in the chosen encoding.\n"
1036 "Changing the document encoding to utf8 could help."),
1037 e.par_id, e.pos, e.pos + 1));
1038 failed_export = true;
1040 catch (iconv_codecvt_facet_exception & e) {
1041 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1042 _(e.what()), -1, 0, 0));
1043 failed_export = true;
1045 catch (exception const & e) {
1046 errorList.push_back(ErrorItem(_("conversion failed"),
1047 _(e.what()), -1, 0, 0));
1048 failed_export = true;
1051 lyxerr << "Caught some really weird exception..." << endl;
1052 LyX::cref().exit(1);
1057 failed_export = true;
1058 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1062 return !failed_export;
1066 void Buffer::writeLaTeXSource(odocstream & os,
1067 string const & original_path,
1068 OutputParams const & runparams_in,
1069 bool const output_preamble, bool const output_body) const
1071 OutputParams runparams = runparams_in;
1073 // validate the buffer.
1074 LYXERR(Debug::LATEX, " Validating buffer...");
1075 LaTeXFeatures features(*this, params(), runparams);
1077 LYXERR(Debug::LATEX, " Buffer validation done.");
1079 // The starting paragraph of the coming rows is the
1080 // first paragraph of the document. (Asger)
1081 if (output_preamble && runparams.nice) {
1082 os << "%% LyX " << lyx_version << " created this file. "
1083 "For more info, see http://www.lyx.org/.\n"
1084 "%% Do not edit unless you really know what "
1086 d->texrow.newline();
1087 d->texrow.newline();
1089 LYXERR(Debug::INFO, "lyx document header finished");
1090 // There are a few differences between nice LaTeX and usual files:
1091 // usual is \batchmode and has a
1092 // special input@path to allow the including of figures
1093 // with either \input or \includegraphics (what figinsets do).
1094 // input@path is set when the actual parameter
1095 // original_path is set. This is done for usual tex-file, but not
1096 // for nice-latex-file. (Matthias 250696)
1097 // Note that input@path is only needed for something the user does
1098 // in the preamble, included .tex files or ERT, files included by
1099 // LyX work without it.
1100 if (output_preamble) {
1101 if (!runparams.nice) {
1102 // code for usual, NOT nice-latex-file
1103 os << "\\batchmode\n"; // changed
1104 // from \nonstopmode
1105 d->texrow.newline();
1107 if (!original_path.empty()) {
1109 // We don't know the encoding of inputpath
1110 docstring const inputpath = from_utf8(latex_path(original_path));
1111 os << "\\makeatletter\n"
1112 << "\\def\\input@path{{"
1113 << inputpath << "/}}\n"
1114 << "\\makeatother\n";
1115 d->texrow.newline();
1116 d->texrow.newline();
1117 d->texrow.newline();
1120 // Write the preamble
1121 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1127 os << "\\begin{document}\n";
1128 d->texrow.newline();
1129 } // output_preamble
1131 d->texrow.start(paragraphs().begin()->id(), 0);
1133 LYXERR(Debug::INFO, "preamble finished, now the body.");
1135 // load children, if not already done.
1136 // This includes an updateMacro() call.
1137 // Don't move this behind the parent_buffer=0 code below,
1138 // because then the macros will not get the right "redefinition"
1139 // flag as they don't see the parent macros which are output before.
1140 loadChildDocuments();
1142 // fold macros if possible, still with parent buffer as the
1143 // macros will be put in the prefix anyway.
1144 updateMacroInstances();
1146 // if we are doing a real file with body, even if this is the
1147 // child of some other buffer, let's cut the link here.
1148 // This happens for example if only a child document is printed.
1149 Buffer const * save_parent = 0;
1150 if (output_preamble) {
1151 // output the macros visible for this buffer
1152 writeParentMacros(os);
1154 save_parent = d->parent_buffer;
1155 d->parent_buffer = 0;
1159 latexParagraphs(*this, text(), os, d->texrow, runparams);
1161 // Restore the parenthood if needed
1162 if (output_preamble) {
1163 d->parent_buffer = save_parent;
1165 // restore macros with correct parent buffer (especially
1166 // important for the redefinition flag which depends on the
1171 // add this just in case after all the paragraphs
1173 d->texrow.newline();
1175 if (output_preamble) {
1176 os << "\\end{document}\n";
1177 d->texrow.newline();
1178 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1180 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1182 runparams_in.encoding = runparams.encoding;
1184 // Just to be sure. (Asger)
1185 d->texrow.newline();
1187 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1188 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1192 bool Buffer::isLatex() const
1194 return params().documentClass().outputType() == LATEX;
1198 bool Buffer::isLiterate() const
1200 return params().documentClass().outputType() == LITERATE;
1204 bool Buffer::isDocBook() const
1206 return params().documentClass().outputType() == DOCBOOK;
1210 void Buffer::makeDocBookFile(FileName const & fname,
1211 OutputParams const & runparams,
1212 bool const body_only) const
1214 LYXERR(Debug::LATEX, "makeDocBookFile...");
1217 if (!openFileWrite(ofs, fname))
1220 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1224 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1228 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1229 OutputParams const & runparams,
1230 bool const only_body) const
1232 LaTeXFeatures features(*this, params(), runparams);
1237 DocumentClass const & tclass = params().documentClass();
1238 string const top_element = tclass.latexname();
1241 if (runparams.flavor == OutputParams::XML)
1242 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1245 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1248 if (! tclass.class_header().empty())
1249 os << from_ascii(tclass.class_header());
1250 else if (runparams.flavor == OutputParams::XML)
1251 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1252 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1254 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1256 docstring preamble = from_utf8(params().preamble);
1257 if (runparams.flavor != OutputParams::XML ) {
1258 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1259 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1260 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1261 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1264 string const name = runparams.nice
1265 ? changeExtension(absFileName(), ".sgml") : fname;
1266 preamble += features.getIncludedFiles(name);
1267 preamble += features.getLyXSGMLEntities();
1269 if (!preamble.empty()) {
1270 os << "\n [ " << preamble << " ]";
1275 string top = top_element;
1277 if (runparams.flavor == OutputParams::XML)
1278 top += params().language->code();
1280 top += params().language->code().substr(0,2);
1283 if (!params().options.empty()) {
1285 top += params().options;
1288 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1289 << " file was created by LyX " << lyx_version
1290 << "\n See http://www.lyx.org/ for more information -->\n";
1292 params().documentClass().counters().reset();
1294 loadChildDocuments();
1296 sgml::openTag(os, top);
1298 docbookParagraphs(paragraphs(), *this, os, runparams);
1299 sgml::closeTag(os, top_element);
1303 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1304 // Other flags: -wall -v0 -x
1305 int Buffer::runChktex()
1309 // get LaTeX-Filename
1310 FileName const path(temppath());
1311 string const name = addName(path.absFilename(), latexName());
1312 string const org_path = filePath();
1314 PathChanger p(path); // path to LaTeX file
1315 message(_("Running chktex..."));
1317 // Generate the LaTeX file if neccessary
1318 OutputParams runparams(¶ms().encoding());
1319 runparams.flavor = OutputParams::LATEX;
1320 runparams.nice = false;
1321 makeLaTeXFile(FileName(name), org_path, runparams);
1324 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1325 int const res = chktex.run(terr); // run chktex
1328 Alert::error(_("chktex failure"),
1329 _("Could not run chktex successfully."));
1330 } else if (res > 0) {
1331 ErrorList & errlist = d->errorLists["ChkTeX"];
1333 bufferErrors(terr, errlist);
1344 void Buffer::validate(LaTeXFeatures & features) const
1346 params().validate(features);
1348 loadChildDocuments();
1350 for_each(paragraphs().begin(), paragraphs().end(),
1351 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1353 if (lyxerr.debugging(Debug::LATEX)) {
1354 features.showStruct();
1359 void Buffer::getLabelList(vector<docstring> & list) const
1361 /// if this is a child document and the parent is already loaded
1362 /// Use the parent's list instead [ale990407]
1363 Buffer const * tmp = masterBuffer();
1365 lyxerr << "masterBuffer() failed!" << endl;
1369 tmp->getLabelList(list);
1373 loadChildDocuments();
1375 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1376 it.nextInset()->getLabelList(list);
1380 void Buffer::updateBibfilesCache() const
1382 // if this is a child document and the parent is already loaded
1383 // update the parent's cache instead
1384 Buffer const * tmp = masterBuffer();
1387 tmp->updateBibfilesCache();
1391 d->bibfilesCache_.clear();
1392 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1393 if (it->lyxCode() == BIBTEX_CODE) {
1394 InsetBibtex const & inset =
1395 static_cast<InsetBibtex const &>(*it);
1396 EmbeddedFileList const bibfiles = inset.embeddedFiles();
1397 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1400 } else if (it->lyxCode() == INCLUDE_CODE) {
1401 InsetInclude & inset =
1402 static_cast<InsetInclude &>(*it);
1403 inset.updateBibfilesCache();
1404 EmbeddedFileList const & bibfiles =
1405 inset.getBibfilesCache(*this);
1406 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1414 EmbeddedFileList const & Buffer::getBibfilesCache() const
1416 // if this is a child document and the parent is already loaded
1417 // use the parent's cache instead
1418 Buffer const * tmp = masterBuffer();
1421 return tmp->getBibfilesCache();
1423 // We update the cache when first used instead of at loading time.
1424 if (d->bibfilesCache_.empty())
1425 const_cast<Buffer *>(this)->updateBibfilesCache();
1427 return d->bibfilesCache_;
1431 bool Buffer::isDepClean(string const & name) const
1433 DepClean::const_iterator const it = d->dep_clean.find(name);
1434 if (it == d->dep_clean.end())
1440 void Buffer::markDepClean(string const & name)
1442 d->dep_clean[name] = true;
1446 bool Buffer::dispatch(string const & command, bool * result)
1448 return dispatch(lyxaction.lookupFunc(command), result);
1452 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1454 bool dispatched = true;
1456 switch (func.action) {
1457 case LFUN_BUFFER_EXPORT: {
1458 bool const tmp = doExport(to_utf8(func.argument()), false);
1471 void Buffer::changeLanguage(Language const * from, Language const * to)
1476 for_each(par_iterator_begin(),
1478 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1482 bool Buffer::isMultiLingual() const
1484 ParConstIterator end = par_iterator_end();
1485 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1486 if (it->isMultiLingual(params()))
1493 DocIterator Buffer::getParFromID(int const id) const
1496 // John says this is called with id == -1 from undo
1497 lyxerr << "getParFromID(), id: " << id << endl;
1498 return doc_iterator_end(inset());
1501 for (DocIterator it = doc_iterator_begin(inset()); !it.atEnd(); it.forwardPar())
1502 if (it.paragraph().id() == id)
1505 return doc_iterator_end(inset());
1509 bool Buffer::hasParWithID(int const id) const
1511 return !getParFromID(id).atEnd();
1515 ParIterator Buffer::par_iterator_begin()
1517 return ParIterator(doc_iterator_begin(inset()));
1521 ParIterator Buffer::par_iterator_end()
1523 return ParIterator(doc_iterator_end(inset()));
1527 ParConstIterator Buffer::par_iterator_begin() const
1529 return lyx::par_const_iterator_begin(inset());
1533 ParConstIterator Buffer::par_iterator_end() const
1535 return lyx::par_const_iterator_end(inset());
1539 Language const * Buffer::language() const
1541 return params().language;
1545 docstring const Buffer::B_(string const & l10n) const
1547 return params().B_(l10n);
1551 bool Buffer::isClean() const
1553 return d->lyx_clean;
1557 bool Buffer::isBakClean() const
1559 return d->bak_clean;
1563 bool Buffer::isExternallyModified(CheckMethod method) const
1565 BOOST_ASSERT(d->filename.exists());
1566 // if method == timestamp, check timestamp before checksum
1567 return (method == checksum_method
1568 || d->timestamp_ != d->filename.lastModified())
1569 && d->checksum_ != d->filename.checksum();
1573 void Buffer::saveCheckSum(FileName const & file) const
1575 if (file.exists()) {
1576 d->timestamp_ = file.lastModified();
1577 d->checksum_ = file.checksum();
1579 // in the case of save to a new file.
1586 void Buffer::markClean() const
1588 if (!d->lyx_clean) {
1589 d->lyx_clean = true;
1592 // if the .lyx file has been saved, we don't need an
1594 d->bak_clean = true;
1598 void Buffer::markBakClean() const
1600 d->bak_clean = true;
1604 void Buffer::setUnnamed(bool flag)
1610 bool Buffer::isUnnamed() const
1616 // FIXME: this function should be moved to buffer_pimpl.C
1617 void Buffer::markDirty()
1620 d->lyx_clean = false;
1623 d->bak_clean = false;
1625 DepClean::iterator it = d->dep_clean.begin();
1626 DepClean::const_iterator const end = d->dep_clean.end();
1628 for (; it != end; ++it)
1633 FileName Buffer::fileName() const
1639 string Buffer::absFileName() const
1641 return d->filename.absFilename();
1645 string Buffer::filePath() const
1647 return d->filename.onlyPath().absFilename() + "/";
1651 bool Buffer::isReadonly() const
1653 return d->read_only;
1657 void Buffer::setParent(Buffer const * buffer)
1659 // Avoids recursive include.
1660 d->parent_buffer = buffer == this ? 0 : buffer;
1665 Buffer const * Buffer::parent()
1667 return d->parent_buffer;
1671 Buffer const * Buffer::masterBuffer() const
1673 if (!d->parent_buffer)
1676 return d->parent_buffer->masterBuffer();
1680 template<typename M>
1681 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
1686 typename M::iterator it = m.lower_bound(x);
1687 if (it == m.begin())
1695 MacroData const * Buffer::getBufferMacro(docstring const & name,
1696 DocIterator const & pos) const
1698 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
1700 // if paragraphs have no macro context set, pos will be empty
1704 // we haven't found anything yet
1705 DocIterator bestPos = par_iterator_begin();
1706 MacroData const * bestData = 0;
1708 // find macro definitions for name
1709 Impl::NamePositionScopeMacroMap::iterator nameIt
1710 = d->macros.find(name);
1711 if (nameIt != d->macros.end()) {
1712 // find last definition in front of pos or at pos itself
1713 Impl::PositionScopeMacroMap::const_iterator it
1714 = greatest_below(nameIt->second, pos);
1715 if (it != nameIt->second.end()) {
1717 // scope ends behind pos?
1718 if (pos < it->second.first) {
1719 // Looks good, remember this. If there
1720 // is no external macro behind this,
1721 // we found the right one already.
1722 bestPos = it->first;
1723 bestData = &it->second.second;
1727 // try previous macro if there is one
1728 if (it == nameIt->second.begin())
1735 // find macros in included files
1736 Impl::PositionScopeBufferMap::const_iterator it
1737 = greatest_below(d->position_to_children, pos);
1738 if (it == d->position_to_children.end())
1739 // no children before
1743 // do we know something better (i.e. later) already?
1744 if (it->first < bestPos )
1747 // scope ends behind pos?
1748 if (pos < it->second.first) {
1749 // look for macro in external file
1750 d->macro_lock = true;
1751 MacroData const * data
1752 = it->second.second->getMacro(name, false);
1753 d->macro_lock = false;
1755 bestPos = it->first;
1761 // try previous file if there is one
1762 if (it == d->position_to_children.begin())
1767 // return the best macro we have found
1772 MacroData const * Buffer::getMacro(docstring const & name,
1773 DocIterator const & pos, bool global) const
1778 // query buffer macros
1779 MacroData const * data = getBufferMacro(name, pos);
1783 // If there is a master buffer, query that
1784 if (d->parent_buffer) {
1785 d->macro_lock = true;
1786 MacroData const * macro
1787 = d->parent_buffer->getMacro(name, *this, false);
1788 d->macro_lock = false;
1794 data = MacroTable::globalMacros().get(name);
1803 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
1805 // set scope end behind the last paragraph
1806 DocIterator scope = par_iterator_begin();
1807 scope.pit() = scope.lastpit() + 1;
1809 return getMacro(name, scope, global);
1813 MacroData const * Buffer::getMacro(docstring const & name, Buffer const & child, bool global) const
1815 // look where the child buffer is included first
1816 Impl::BufferPositionMap::iterator it
1817 = d->children_positions.find(&child);
1818 if (it == d->children_positions.end())
1821 // check for macros at the inclusion position
1822 return getMacro(name, it->second, global);
1826 void Buffer::updateEnvironmentMacros(DocIterator & it,
1828 DocIterator & scope) const
1830 Paragraph & par = it.paragraph();
1832 = par.params().depth();
1833 Length const & leftIndent
1834 = par.params().leftIndent();
1836 // look for macros in each paragraph
1837 while (it.pit() <= lastpit) {
1838 Paragraph & par = it.paragraph();
1841 if ((par.params().depth() > depth
1842 || par.params().leftIndent() != leftIndent)
1843 && par.layout()->isEnvironment()) {
1844 updateBlockMacros(it, scope);
1848 // iterate over the insets of the current paragraph
1849 InsetList const & insets = par.insetList();
1850 InsetList::const_iterator iit = insets.begin();
1851 InsetList::const_iterator end = insets.end();
1852 for (; iit != end; ++iit) {
1853 it.pos() = iit->pos;
1855 // is it a nested text inset?
1856 if (iit->inset->asInsetText()) {
1857 // Inset needs its own scope?
1858 InsetText const * itext
1859 = iit->inset->asInsetText();
1860 bool newScope = itext->isMacroScope();
1862 // scope which ends just behind the inset
1863 DocIterator insetScope = it;
1866 // collect macros in inset
1867 it.push_back(CursorSlice(*iit->inset));
1868 updateInsetMacros(it, newScope ? insetScope : scope);
1873 // is it an external file?
1874 if (iit->inset->lyxCode() == INCLUDE_CODE) {
1875 // get buffer of external file
1876 InsetCommand const & inset
1877 = static_cast<InsetCommand const &>(*iit->inset);
1878 InsetCommandParams const & ip = inset.params();
1879 d->macro_lock = true;
1880 Buffer * child = loadIfNeeded(*this, ip);
1881 d->macro_lock = false;
1885 // register its position, but only when it is
1886 // included first in the buffer
1887 if (d->children_positions.find(child)
1888 == d->children_positions.end())
1889 d->children_positions[child] = it;
1891 // register child with its scope
1892 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
1897 if (iit->inset->lyxCode() != MATHMACRO_CODE)
1901 MathMacroTemplate & macroTemplate
1902 = static_cast<MathMacroTemplate &>(*iit->inset);
1903 MacroContext mc(*this, it);
1904 macroTemplate.updateToContext(mc);
1907 bool valid = macroTemplate.validMacro();
1908 // FIXME: Should be fixNameAndCheckIfValid() in fact,
1909 // then the BufferView's cursor will be invalid in
1910 // some cases which leads to crashes.
1915 d->macros[macroTemplate.name()][it]
1916 = Impl::ScopeMacro(scope, MacroData(*this, it));
1926 void Buffer::updateBlockMacros(DocIterator & it, DocIterator & scope) const
1928 Paragraph & par = it.paragraph();
1930 // set scope for macros in this paragraph:
1931 // * either the "old" outer scope
1932 // * or the scope ending after the environment
1933 if (par.layout()->isEnvironment()) {
1934 // find end of environment block,
1935 DocIterator envEnd = it;
1936 pit_type n = it.lastpit() + 1;
1937 depth_type depth = par.params().depth();
1938 Length const & length = par.params().leftIndent();
1939 // looping through the paragraph, basically until
1940 // the layout changes or the depth gets smaller.
1941 // (the logic of output_latex.cpp's TeXEnvironment)
1944 if (envEnd.pit() == n)
1946 } while (par.layout() == envEnd.paragraph().layout()
1947 || depth < envEnd.paragraph().params().depth()
1948 || length != envEnd.paragraph().params().leftIndent());
1950 // collect macros from environment block
1951 updateEnvironmentMacros(it, envEnd.pit() - 1, envEnd);
1953 // collect macros from paragraph
1954 updateEnvironmentMacros(it, it.pit(), scope);
1959 void Buffer::updateInsetMacros(DocIterator & it, DocIterator & scope) const
1961 // look for macros in each paragraph
1962 pit_type n = it.lastpit() + 1;
1963 while (it.pit() < n)
1964 updateBlockMacros(it, scope);
1968 void Buffer::updateMacros() const
1973 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
1975 // start with empty table
1977 d->children_positions.clear();
1978 d->position_to_children.clear();
1980 // Iterate over buffer, starting with first paragraph
1981 // The scope must be bigger than any lookup DocIterator
1982 // later. For the global lookup, lastpit+1 is used, hence
1983 // we use lastpit+2 here.
1984 DocIterator it = par_iterator_begin();
1985 DocIterator outerScope = it;
1986 outerScope.pit() = outerScope.lastpit() + 2;
1987 updateInsetMacros(it, outerScope);
1991 void Buffer::updateMacroInstances() const
1993 LYXERR(Debug::MACROS, "updateMacroInstances for "
1994 << d->filename.onlyFileName());
1995 DocIterator it = doc_iterator_begin(inset());
1996 DocIterator end = doc_iterator_end(inset());
1997 for (; it != end; it.forwardPos()) {
1998 // look for MathData cells in InsetMathNest insets
1999 Inset * inset = it.nextInset();
2003 InsetMath * minset = inset->asInsetMath();
2007 // update macro in all cells of the InsetMathNest
2008 DocIterator::idx_type n = minset->nargs();
2009 MacroContext mc = MacroContext(*this, it);
2010 for (DocIterator::idx_type i = 0; i < n; ++i) {
2011 MathData & data = minset->cell(i);
2012 data.updateMacros(0, mc);
2018 void Buffer::listMacroNames(MacroNameSet & macros) const
2023 d->macro_lock = true;
2025 // loop over macro names
2026 Impl::NamePositionScopeMacroMap::iterator nameIt
2027 = d->macros.begin();
2028 Impl::NamePositionScopeMacroMap::iterator nameEnd
2030 for (; nameIt != nameEnd; ++nameIt)
2031 macros.insert(nameIt->first);
2033 // loop over children
2034 Impl::BufferPositionMap::iterator it
2035 = d->children_positions.begin();
2036 Impl::BufferPositionMap::iterator end
2037 = d->children_positions.end();
2038 for (; it != end; ++it)
2039 it->first->listMacroNames(macros);
2042 if (d->parent_buffer)
2043 d->parent_buffer->listMacroNames(macros);
2045 d->macro_lock = false;
2049 void Buffer::writeParentMacros(odocstream & os) const
2051 if (!d->parent_buffer)
2054 // collect macro names
2056 d->parent_buffer->listMacroNames(names);
2058 // resolve and output them
2059 MacroNameSet::iterator it = names.begin();
2060 MacroNameSet::iterator end = names.end();
2061 for (; it != end; ++it) {
2063 MacroData const * data =
2064 d->parent_buffer->getMacro(*it, *this, false);
2066 data->write(os, true);
2071 Buffer::References & Buffer::references(docstring const & label)
2073 if (d->parent_buffer)
2074 return const_cast<Buffer *>(masterBuffer())->references(label);
2076 RefCache::iterator it = d->ref_cache_.find(label);
2077 if (it != d->ref_cache_.end())
2078 return it->second.second;
2080 static InsetLabel const * dummy_il = 0;
2081 static References const dummy_refs;
2082 it = d->ref_cache_.insert(make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2083 return it->second.second;
2087 Buffer::References const & Buffer::references(docstring const & label) const
2089 return const_cast<Buffer *>(this)->references(label);
2093 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2095 masterBuffer()->d->ref_cache_[label].first = il;
2099 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2101 return masterBuffer()->d->ref_cache_[label].first;
2105 void Buffer::clearReferenceCache() const
2107 if (!d->parent_buffer)
2108 d->ref_cache_.clear();
2112 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2115 //FIXME: This does not work for child documents yet.
2116 BOOST_ASSERT(code == CITE_CODE || code == REF_CODE);
2117 // Check if the label 'from' appears more than once
2118 vector<docstring> labels;
2121 if (code == CITE_CODE) {
2123 keys.fillWithBibKeys(this);
2124 BiblioInfo::const_iterator bit = keys.begin();
2125 BiblioInfo::const_iterator bend = keys.end();
2127 for (; bit != bend; ++bit)
2129 labels.push_back(bit->first);
2132 getLabelList(labels);
2133 paramName = "reference";
2136 if (count(labels.begin(), labels.end(), from) > 1)
2139 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2140 if (it->lyxCode() == code) {
2141 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2142 docstring const oldValue = inset.getParam(paramName);
2143 if (oldValue == from)
2144 inset.setParam(paramName, to);
2150 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2151 pit_type par_end, bool full_source)
2153 OutputParams runparams(¶ms().encoding());
2154 runparams.nice = true;
2155 runparams.flavor = OutputParams::LATEX;
2156 runparams.linelen = lyxrc.plaintext_linelen;
2157 // No side effect of file copying and image conversion
2158 runparams.dryrun = true;
2162 os << "% " << _("Preview source code") << "\n\n";
2163 d->texrow.newline();
2164 d->texrow.newline();
2166 writeLaTeXSource(os, filePath(), runparams, true, true);
2168 writeDocBookSource(os, absFileName(), runparams, false);
2171 runparams.par_begin = par_begin;
2172 runparams.par_end = par_end;
2173 if (par_begin + 1 == par_end)
2175 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2179 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2180 convert<docstring>(par_begin),
2181 convert<docstring>(par_end - 1))
2183 d->texrow.newline();
2184 d->texrow.newline();
2185 // output paragraphs
2187 latexParagraphs(*this, text(), os, d->texrow, runparams);
2190 docbookParagraphs(paragraphs(), *this, os, runparams);
2196 ErrorList & Buffer::errorList(string const & type) const
2198 static ErrorList emptyErrorList;
2199 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2200 if (I == d->errorLists.end())
2201 return emptyErrorList;
2207 void Buffer::structureChanged() const
2210 gui_->structureChanged();
2214 void Buffer::errors(string const & err) const
2221 void Buffer::message(docstring const & msg) const
2228 void Buffer::setBusy(bool on) const
2235 void Buffer::setReadOnly(bool on) const
2238 d->wa_->setReadOnly(on);
2242 void Buffer::updateTitles() const
2245 d->wa_->updateTitles();
2249 void Buffer::resetAutosaveTimers() const
2252 gui_->resetAutosaveTimers();
2256 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2265 class AutoSaveBuffer : public ForkedProcess {
2268 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2269 : buffer_(buffer), fname_(fname) {}
2271 virtual boost::shared_ptr<ForkedProcess> clone() const
2273 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2278 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2279 from_utf8(fname_.absFilename())));
2280 return run(DontWait);
2284 virtual int generateChild();
2286 Buffer const & buffer_;
2291 int AutoSaveBuffer::generateChild()
2293 // tmp_ret will be located (usually) in /tmp
2294 // will that be a problem?
2295 // Note that this calls ForkedCalls::fork(), so it's
2296 // ok cross-platform.
2297 pid_t const pid = fork();
2298 // If you want to debug the autosave
2299 // you should set pid to -1, and comment out the fork.
2300 if (pid != 0 && pid != -1)
2303 // pid = -1 signifies that lyx was unable
2304 // to fork. But we will do the save
2306 bool failed = false;
2307 FileName const tmp_ret = FileName::tempName("lyxauto");
2308 if (!tmp_ret.empty()) {
2309 buffer_.writeFile(tmp_ret);
2310 // assume successful write of tmp_ret
2311 if (!tmp_ret.moveTo(fname_))
2317 // failed to write/rename tmp_ret so try writing direct
2318 if (!buffer_.writeFile(fname_)) {
2319 // It is dangerous to do this in the child,
2320 // but safe in the parent, so...
2321 if (pid == -1) // emit message signal.
2322 buffer_.message(_("Autosave failed!"));
2326 if (pid == 0) // we are the child so...
2335 // Perfect target for a thread...
2336 void Buffer::autoSave() const
2338 if (isBakClean() || isReadonly()) {
2339 // We don't save now, but we'll try again later
2340 resetAutosaveTimers();
2344 // emit message signal.
2345 message(_("Autosaving current document..."));
2347 // create autosave filename
2348 string fname = filePath();
2350 fname += d->filename.onlyFileName();
2353 AutoSaveBuffer autosave(*this, FileName(fname));
2357 resetAutosaveTimers();
2361 void Buffer::resetChildDocuments(bool close_them) const
2366 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2367 if (it->lyxCode() != INCLUDE_CODE)
2369 InsetCommand const & inset = static_cast<InsetCommand const &>(*it);
2370 InsetCommandParams const & ip = inset.params();
2372 resetParentBuffer(this, ip, close_them);
2375 // clear references to children in macro tables
2376 d->children_positions.clear();
2377 d->position_to_children.clear();
2381 void Buffer::loadChildDocuments() const
2383 bool parse_error = false;
2385 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2386 if (it->lyxCode() != INCLUDE_CODE)
2388 InsetCommand const & inset = static_cast<InsetCommand const &>(*it);
2389 InsetCommandParams const & ip = inset.params();
2390 Buffer * child = loadIfNeeded(*this, ip);
2393 parse_error |= !child->errorList("Parse").empty();
2394 child->loadChildDocuments();
2397 if (use_gui && masterBuffer() == this)
2398 updateLabels(*this);
2404 string Buffer::bufferFormat() const
2414 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2415 string & result_file) const
2417 string backend_format;
2418 OutputParams runparams(¶ms().encoding());
2419 runparams.flavor = OutputParams::LATEX;
2420 runparams.linelen = lyxrc.plaintext_linelen;
2421 vector<string> backs = backends();
2422 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2423 // Get shortest path to format
2424 Graph::EdgePath path;
2425 for (vector<string>::const_iterator it = backs.begin();
2426 it != backs.end(); ++it) {
2427 Graph::EdgePath p = theConverters().getPath(*it, format);
2428 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2429 backend_format = *it;
2434 runparams.flavor = theConverters().getFlavor(path);
2436 Alert::error(_("Couldn't export file"),
2437 bformat(_("No information for exporting the format %1$s."),
2438 formats.prettyName(format)));
2442 backend_format = format;
2443 // FIXME: Don't hardcode format names here, but use a flag
2444 if (backend_format == "pdflatex")
2445 runparams.flavor = OutputParams::PDFLATEX;
2448 string filename = latexName(false);
2449 filename = addName(temppath(), filename);
2450 filename = changeExtension(filename,
2451 formats.extension(backend_format));
2454 updateMacroInstances();
2456 // Plain text backend
2457 if (backend_format == "text")
2458 writePlaintextFile(*this, FileName(filename), runparams);
2460 else if (backend_format == "lyx")
2461 writeFile(FileName(filename));
2463 else if (isDocBook()) {
2464 runparams.nice = !put_in_tempdir;
2465 makeDocBookFile(FileName(filename), runparams);
2468 else if (backend_format == format) {
2469 runparams.nice = true;
2470 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2472 } else if (!lyxrc.tex_allows_spaces
2473 && contains(filePath(), ' ')) {
2474 Alert::error(_("File name error"),
2475 _("The directory path to the document cannot contain spaces."));
2478 runparams.nice = false;
2479 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2483 string const error_type = (format == "program")
2484 ? "Build" : bufferFormat();
2485 string const ext = formats.extension(format);
2486 FileName const tmp_result_file(changeExtension(filename, ext));
2487 bool const success = theConverters().convert(this, FileName(filename),
2488 tmp_result_file, FileName(absFileName()), backend_format, format,
2489 errorList(error_type));
2490 // Emit the signal to show the error list.
2491 if (format != backend_format)
2496 if (put_in_tempdir) {
2497 result_file = tmp_result_file.absFilename();
2501 result_file = changeExtension(absFileName(), ext);
2502 // We need to copy referenced files (e. g. included graphics
2503 // if format == "dvi") to the result dir.
2504 vector<ExportedFile> const files =
2505 runparams.exportdata->externalFiles(format);
2506 string const dest = onlyPath(result_file);
2507 CopyStatus status = SUCCESS;
2508 for (vector<ExportedFile>::const_iterator it = files.begin();
2509 it != files.end() && status != CANCEL; ++it) {
2510 string const fmt = formats.getFormatFromFile(it->sourceName);
2511 status = copyFile(fmt, it->sourceName,
2512 makeAbsPath(it->exportName, dest),
2513 it->exportName, status == FORCE);
2515 if (status == CANCEL) {
2516 message(_("Document export cancelled."));
2517 } else if (tmp_result_file.exists()) {
2518 // Finally copy the main file
2519 status = copyFile(format, tmp_result_file,
2520 FileName(result_file), result_file,
2522 message(bformat(_("Document exported as %1$s "
2524 formats.prettyName(format),
2525 makeDisplayPath(result_file)));
2527 // This must be a dummy converter like fax (bug 1888)
2528 message(bformat(_("Document exported as %1$s"),
2529 formats.prettyName(format)));
2536 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2539 return doExport(format, put_in_tempdir, result_file);
2543 bool Buffer::preview(string const & format) const
2546 if (!doExport(format, true, result_file))
2548 return formats.view(*this, FileName(result_file), format);
2552 bool Buffer::isExportable(string const & format) const
2554 vector<string> backs = backends();
2555 for (vector<string>::const_iterator it = backs.begin();
2556 it != backs.end(); ++it)
2557 if (theConverters().isReachable(*it, format))
2563 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2565 vector<string> backs = backends();
2566 vector<Format const *> result =
2567 theConverters().getReachable(backs[0], only_viewable, true);
2568 for (vector<string>::const_iterator it = backs.begin() + 1;
2569 it != backs.end(); ++it) {
2570 vector<Format const *> r =
2571 theConverters().getReachable(*it, only_viewable, false);
2572 result.insert(result.end(), r.begin(), r.end());
2578 vector<string> Buffer::backends() const
2581 if (params().baseClass()->isTeXClassAvailable()) {
2582 v.push_back(bufferFormat());
2583 // FIXME: Don't hardcode format names here, but use a flag
2584 if (v.back() == "latex")
2585 v.push_back("pdflatex");
2587 v.push_back("text");
2593 bool Buffer::readFileHelper(FileName const & s)
2595 // File information about normal file
2597 docstring const file = makeDisplayPath(s.absFilename(), 50);
2598 docstring text = bformat(_("The specified document\n%1$s"
2599 "\ncould not be read."), file);
2600 Alert::error(_("Could not read document"), text);
2604 // Check if emergency save file exists and is newer.
2605 FileName const e(s.absFilename() + ".emergency");
2607 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2608 docstring const file = makeDisplayPath(s.absFilename(), 20);
2609 docstring const text =
2610 bformat(_("An emergency save of the document "
2612 "Recover emergency save?"), file);
2613 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2614 _("&Recover"), _("&Load Original"),
2618 // the file is not saved if we load the emergency file.
2628 // Now check if autosave file is newer.
2629 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2631 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2632 docstring const file = makeDisplayPath(s.absFilename(), 20);
2633 docstring const text =
2634 bformat(_("The backup of the document "
2635 "%1$s is newer.\n\nLoad the "
2636 "backup instead?"), file);
2637 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2638 _("&Load backup"), _("Load &original"),
2642 // the file is not saved if we load the autosave file.
2646 // Here we delete the autosave
2657 bool Buffer::loadLyXFile(FileName const & s)
2659 if (s.isReadableFile()) {
2660 if (readFileHelper(s)) {
2661 lyxvc().file_found_hook(s);
2662 if (!s.isWritable())
2667 docstring const file = makeDisplayPath(s.absFilename(), 20);
2668 // Here we probably should run
2669 if (LyXVC::file_not_found_hook(s)) {
2670 docstring const text =
2671 bformat(_("Do you want to retrieve the document"
2672 " %1$s from version control?"), file);
2673 int const ret = Alert::prompt(_("Retrieve from version control?"),
2674 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2677 // How can we know _how_ to do the checkout?
2678 // With the current VC support it has to be,
2679 // a RCS file since CVS do not have special ,v files.
2681 return loadLyXFile(s);
2689 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2691 TeXErrors::Errors::const_iterator cit = terr.begin();
2692 TeXErrors::Errors::const_iterator end = terr.end();
2694 for (; cit != end; ++cit) {
2697 int errorRow = cit->error_in_line;
2698 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2704 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2705 } while (found && id_start == id_end && pos_start == pos_end);
2707 errorList.push_back(ErrorItem(cit->error_desc,
2708 cit->error_text, id_start, pos_start, pos_end));