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 #if !defined (HAVE_FORK)
102 #include <boost/bind.hpp>
103 #include <boost/shared_ptr.hpp>
112 using namespace lyx::support;
116 namespace Alert = frontend::Alert;
117 namespace os = support::os;
121 int const LYX_FORMAT = 311; // Richard Heck: a dummy format to drive the AMS conversion
126 typedef map<string, bool> DepClean;
131 Impl(Buffer & parent, FileName const & file, bool readonly);
144 mutable TexRow texrow;
145 Buffer const * parent_buffer;
147 /// need to regenerate .tex?
151 mutable bool lyx_clean;
153 /// is autosave needed?
154 mutable bool bak_clean;
156 /// is this a unnamed file (New...)?
162 /// name of the file the buffer is associated with.
165 /** Set to true only when the file is fully loaded.
166 * Used to prevent the premature generation of previews
167 * and by the citation inset.
169 bool file_fully_loaded;
171 /// our Text that should be wrapped in an InsetText
175 mutable TocBackend toc_backend;
178 typedef pair<DocIterator, MacroData> ScopeMacro;
179 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
180 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
181 NamePositionScopeMacroMap macros;
184 /// positions of child buffers in the buffer
185 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
186 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
187 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
188 BufferPositionMap children_positions;
189 PositionScopeBufferMap position_to_children;
191 /// Container for all sort of Buffer dependant errors.
192 map<string, ErrorList> errorLists;
194 /// all embedded files of this buffer
195 EmbeddedFileList embedded_files;
197 /// timestamp and checksum used to test if the file has been externally
198 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
200 unsigned long checksum_;
203 frontend::WorkAreaManager * wa_;
208 /// A cache for the bibfiles (including bibfiles of loaded child
209 /// documents), needed for appropriate update of natbib labels.
210 mutable EmbeddedFileList bibfilesCache_;
213 /// Creates the per buffer temporary directory
214 static FileName createBufferTmpDir()
217 // We are in our own directory. Why bother to mangle name?
218 // In fact I wrote this code to circumvent a problematic behaviour
219 // (bug?) of EMX mkstemp().
220 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
221 convert<string>(count++));
223 if (!tmpfl.createDirectory(0777)) {
224 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
225 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
226 from_utf8(tmpfl.absFilename())));
232 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
233 : parent_buffer(0), lyx_clean(true), bak_clean(true), unnamed(false),
234 read_only(readonly_), filename(file), file_fully_loaded(false),
235 inset(params), toc_backend(&parent), macro_lock(false),
236 embedded_files(), timestamp_(0), checksum_(0), wa_(0),
239 temppath = createBufferTmpDir();
240 inset.setAutoBreakRows(true);
241 lyxvc.setBuffer(&parent);
243 wa_ = new frontend::WorkAreaManager;
247 Buffer::Buffer(string const & file, bool readonly)
248 : d(new Impl(*this, FileName(file), readonly)), gui_(0)
250 LYXERR(Debug::INFO, "Buffer::Buffer()");
252 d->inset.getText(0)->setMacrocontextPosition(par_iterator_begin());
258 LYXERR(Debug::INFO, "Buffer::~Buffer()");
259 // here the buffer should take care that it is
260 // saved properly, before it goes into the void.
262 // GuiView already destroyed
265 Buffer const * master = masterBuffer();
266 if (master != this && use_gui) {
267 // We are closing buf which was a child document so we
268 // must update the labels and section numbering of its master
270 updateLabels(*master);
271 master->updateMacros();
274 resetChildDocuments(false);
276 if (!d->temppath.destroyDirectory()) {
277 Alert::warning(_("Could not remove temporary directory"),
278 bformat(_("Could not remove the temporary directory %1$s"),
279 from_utf8(d->temppath.absFilename())));
282 // Remove any previewed LaTeX snippets associated with this buffer.
283 graphics::Previews::get().removeLoader(*this);
289 void Buffer::changed() const
296 frontend::WorkAreaManager & Buffer::workAreaManager() const
298 BOOST_ASSERT(d->wa_);
303 Text & Buffer::text() const
305 return const_cast<Text &>(d->inset.text_);
309 Inset & Buffer::inset() const
311 return const_cast<InsetText &>(d->inset);
315 BufferParams & Buffer::params()
321 BufferParams const & Buffer::params() const
327 ParagraphList & Buffer::paragraphs()
329 return text().paragraphs();
333 ParagraphList const & Buffer::paragraphs() const
335 return text().paragraphs();
339 LyXVC & Buffer::lyxvc()
345 LyXVC const & Buffer::lyxvc() const
351 string const Buffer::temppath() const
353 return d->temppath.absFilename();
357 TexRow const & Buffer::texrow() const
363 TocBackend & Buffer::tocBackend() const
365 return d->toc_backend;
369 EmbeddedFileList & Buffer::embeddedFiles()
371 return d->embedded_files;
375 EmbeddedFileList const & Buffer::embeddedFiles() const
377 return d->embedded_files;
381 bool Buffer::embedded() const
383 return params().embedded;
387 Undo & Buffer::undo()
393 string Buffer::latexName(bool const no_path) const
395 FileName latex_name = makeLatexName(d->filename);
396 return no_path ? latex_name.onlyFileName()
397 : latex_name.absFilename();
401 string Buffer::logName(LogType * type) const
403 string const filename = latexName(false);
405 if (filename.empty()) {
411 string const path = temppath();
413 FileName const fname(addName(temppath(),
414 onlyFilename(changeExtension(filename,
416 FileName const bname(
417 addName(path, onlyFilename(
418 changeExtension(filename,
419 formats.extension("literate") + ".out"))));
421 // If no Latex log or Build log is newer, show Build log
423 if (bname.exists() &&
424 (!fname.exists() || fname.lastModified() < bname.lastModified())) {
425 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
428 return bname.absFilename();
430 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
433 return fname.absFilename();
437 void Buffer::setReadonly(bool const flag)
439 if (d->read_only != flag) {
446 void Buffer::setFileName(string const & newfile)
448 d->filename = makeAbsPath(newfile);
449 setReadonly(d->filename.isReadOnly());
454 int Buffer::readHeader(Lexer & lex)
456 int unknown_tokens = 0;
458 int begin_header_line = -1;
460 // Initialize parameters that may be/go lacking in header:
461 params().branchlist().clear();
462 params().preamble.erase();
463 params().options.erase();
464 params().float_placement.erase();
465 params().paperwidth.erase();
466 params().paperheight.erase();
467 params().leftmargin.erase();
468 params().rightmargin.erase();
469 params().topmargin.erase();
470 params().bottommargin.erase();
471 params().headheight.erase();
472 params().headsep.erase();
473 params().footskip.erase();
474 params().listings_params.clear();
475 params().clearLayoutModules();
476 params().pdfoptions().clear();
478 for (int i = 0; i < 4; ++i) {
479 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
480 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
483 ErrorList & errorList = d->errorLists["Parse"];
487 string const token = lex.getString();
492 if (token == "\\end_header")
496 if (token == "\\begin_header") {
497 begin_header_line = line;
501 LYXERR(Debug::PARSER, "Handling document header token: `"
504 string unknown = params().readToken(lex, token, d->filename.onlyPath());
505 if (!unknown.empty()) {
506 if (unknown[0] != '\\' && token == "\\textclass") {
507 Alert::warning(_("Unknown document class"),
508 bformat(_("Using the default document class, because the "
509 "class %1$s is unknown."), from_utf8(unknown)));
512 docstring const s = bformat(_("Unknown token: "
516 errorList.push_back(ErrorItem(_("Document header error"),
521 if (begin_header_line) {
522 docstring const s = _("\\begin_header is missing");
523 errorList.push_back(ErrorItem(_("Document header error"),
527 params().makeTextClass();
529 return unknown_tokens;
534 // changed to be public and have one parameter
535 // Returns false if "\end_document" is not read (Asger)
536 bool Buffer::readDocument(Lexer & lex)
538 ErrorList & errorList = d->errorLists["Parse"];
542 string const token = lex.getString();
543 if (token != "\\begin_document") {
544 docstring const s = _("\\begin_document is missing");
545 errorList.push_back(ErrorItem(_("Document header error"),
549 // we are reading in a brand new document
550 BOOST_ASSERT(paragraphs().empty());
554 if (params().outputChanges) {
555 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
556 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
557 LaTeXFeatures::isAvailable("xcolor");
559 if (!dvipost && !xcolorsoul) {
560 Alert::warning(_("Changes not shown in LaTeX output"),
561 _("Changes will not be highlighted in LaTeX output, "
562 "because neither dvipost nor xcolor/soul are installed.\n"
563 "Please install these packages or redefine "
564 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
565 } else if (!xcolorsoul) {
566 Alert::warning(_("Changes not shown in LaTeX output"),
567 _("Changes will not be highlighted in LaTeX output "
568 "when using pdflatex, because xcolor and soul are not installed.\n"
569 "Please install both packages or redefine "
570 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
575 bool const res = text().read(*this, lex, errorList);
576 for_each(text().paragraphs().begin(),
577 text().paragraphs().end(),
578 bind(&Paragraph::setInsetOwner, _1, &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";
952 /// For each author, set 'used' to true if there is a change
953 /// by this author in the document; otherwise set it to 'false'.
954 AuthorList::Authors::const_iterator a_it = params().authors().begin();
955 AuthorList::Authors::const_iterator a_end = params().authors().end();
956 for (; a_it != a_end; ++a_it)
957 a_it->second.setUsed(false);
959 ParIterator const end = par_iterator_end();
960 ParIterator it = par_iterator_begin();
961 for ( ; it != end; ++it)
962 it->checkAuthors(params().authors());
964 // now write out the buffer parameters.
965 ofs << "\\begin_header\n";
966 params().writeFile(ofs);
967 ofs << "\\end_header\n";
970 ofs << "\n\\begin_body\n";
971 text().write(*this, ofs);
972 ofs << "\n\\end_body\n";
974 // Write marker that shows file is complete
975 ofs << "\\end_document" << endl;
977 // Shouldn't really be needed....
980 // how to check if close went ok?
981 // Following is an attempt... (BE 20001011)
983 // good() returns false if any error occured, including some
985 // bad() returns true if something bad happened in the buffer,
986 // which should include file system full errors.
991 lyxerr << "File was not closed properly." << endl;
998 bool Buffer::makeLaTeXFile(FileName const & fname,
999 string const & original_path,
1000 OutputParams const & runparams,
1001 bool output_preamble, bool output_body) const
1003 string const encoding = runparams.encoding->iconvName();
1004 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1007 try { ofs.reset(encoding); }
1008 catch (iconv_codecvt_facet_exception & e) {
1009 lyxerr << "Caught iconv exception: " << e.what() << endl;
1010 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1011 "verify that the support software for your encoding (%1$s) is "
1012 "properly installed"), from_ascii(encoding)));
1015 if (!openFileWrite(ofs, fname))
1018 //TexStream ts(ofs.rdbuf(), &texrow());
1019 ErrorList & errorList = d->errorLists["Export"];
1021 bool failed_export = false;
1024 writeLaTeXSource(ofs, original_path,
1025 runparams, output_preamble, output_body);
1027 catch (EncodingException & e) {
1028 odocstringstream ods;
1029 ods.put(e.failed_char);
1031 oss << "0x" << hex << e.failed_char << dec;
1032 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1033 " (code point %2$s)"),
1034 ods.str(), from_utf8(oss.str()));
1035 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1036 "representable in the chosen encoding.\n"
1037 "Changing the document encoding to utf8 could help."),
1038 e.par_id, e.pos, e.pos + 1));
1039 failed_export = true;
1041 catch (iconv_codecvt_facet_exception & e) {
1042 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1043 _(e.what()), -1, 0, 0));
1044 failed_export = true;
1046 catch (exception const & e) {
1047 errorList.push_back(ErrorItem(_("conversion failed"),
1048 _(e.what()), -1, 0, 0));
1049 failed_export = true;
1052 lyxerr << "Caught some really weird exception..." << endl;
1053 LyX::cref().exit(1);
1058 failed_export = true;
1059 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1063 return !failed_export;
1067 void Buffer::writeLaTeXSource(odocstream & os,
1068 string const & original_path,
1069 OutputParams const & runparams_in,
1070 bool const output_preamble, bool const output_body) const
1072 OutputParams runparams = runparams_in;
1074 // validate the buffer.
1075 LYXERR(Debug::LATEX, " Validating buffer...");
1076 LaTeXFeatures features(*this, params(), runparams);
1078 LYXERR(Debug::LATEX, " Buffer validation done.");
1080 // The starting paragraph of the coming rows is the
1081 // first paragraph of the document. (Asger)
1082 if (output_preamble && runparams.nice) {
1083 os << "%% LyX " << lyx_version << " created this file. "
1084 "For more info, see http://www.lyx.org/.\n"
1085 "%% Do not edit unless you really know what "
1087 d->texrow.newline();
1088 d->texrow.newline();
1090 LYXERR(Debug::INFO, "lyx document header finished");
1091 // There are a few differences between nice LaTeX and usual files:
1092 // usual is \batchmode and has a
1093 // special input@path to allow the including of figures
1094 // with either \input or \includegraphics (what figinsets do).
1095 // input@path is set when the actual parameter
1096 // original_path is set. This is done for usual tex-file, but not
1097 // for nice-latex-file. (Matthias 250696)
1098 // Note that input@path is only needed for something the user does
1099 // in the preamble, included .tex files or ERT, files included by
1100 // LyX work without it.
1101 if (output_preamble) {
1102 if (!runparams.nice) {
1103 // code for usual, NOT nice-latex-file
1104 os << "\\batchmode\n"; // changed
1105 // from \nonstopmode
1106 d->texrow.newline();
1108 if (!original_path.empty()) {
1110 // We don't know the encoding of inputpath
1111 docstring const inputpath = from_utf8(latex_path(original_path));
1112 os << "\\makeatletter\n"
1113 << "\\def\\input@path{{"
1114 << inputpath << "/}}\n"
1115 << "\\makeatother\n";
1116 d->texrow.newline();
1117 d->texrow.newline();
1118 d->texrow.newline();
1121 // Write the preamble
1122 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1128 os << "\\begin{document}\n";
1129 d->texrow.newline();
1130 } // output_preamble
1132 d->texrow.start(paragraphs().begin()->id(), 0);
1134 LYXERR(Debug::INFO, "preamble finished, now the body.");
1136 // fold macros if possible, still with parent buffer as the
1137 // macros will be put in the prefix anyway.
1139 updateMacroInstances();
1141 // if we are doing a real file with body, even if this is the
1142 // child of some other buffer, let's cut the link here.
1143 // This happens for example if only a child document is printed.
1144 Buffer const * save_parent = 0;
1145 if (output_preamble) {
1146 // output the macros visible for this buffer
1147 writeParentMacros(os);
1149 save_parent = d->parent_buffer;
1150 d->parent_buffer = 0;
1153 loadChildDocuments();
1156 latexParagraphs(*this, paragraphs(), os, d->texrow, runparams);
1158 // Restore the parenthood if needed
1159 if (output_preamble) {
1160 d->parent_buffer = save_parent;
1162 // restore macros with correct parent buffer (especially
1163 // important for the redefinition flag which depends on the
1168 // add this just in case after all the paragraphs
1170 d->texrow.newline();
1172 if (output_preamble) {
1173 os << "\\end{document}\n";
1174 d->texrow.newline();
1175 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1177 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1179 runparams_in.encoding = runparams.encoding;
1181 // Just to be sure. (Asger)
1182 d->texrow.newline();
1184 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1185 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1189 bool Buffer::isLatex() const
1191 return params().getTextClass().outputType() == LATEX;
1195 bool Buffer::isLiterate() const
1197 return params().getTextClass().outputType() == LITERATE;
1201 bool Buffer::isDocBook() const
1203 return params().getTextClass().outputType() == DOCBOOK;
1207 void Buffer::makeDocBookFile(FileName const & fname,
1208 OutputParams const & runparams,
1209 bool const body_only) const
1211 LYXERR(Debug::LATEX, "makeDocBookFile...");
1214 if (!openFileWrite(ofs, fname))
1217 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1221 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1225 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1226 OutputParams const & runparams,
1227 bool const only_body) const
1229 LaTeXFeatures features(*this, params(), runparams);
1234 TextClass const & tclass = params().getTextClass();
1235 string const top_element = tclass.latexname();
1238 if (runparams.flavor == OutputParams::XML)
1239 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1242 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1245 if (! tclass.class_header().empty())
1246 os << from_ascii(tclass.class_header());
1247 else if (runparams.flavor == OutputParams::XML)
1248 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1249 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1251 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1253 docstring preamble = from_utf8(params().preamble);
1254 if (runparams.flavor != OutputParams::XML ) {
1255 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1256 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1257 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1258 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1261 string const name = runparams.nice
1262 ? changeExtension(absFileName(), ".sgml") : fname;
1263 preamble += features.getIncludedFiles(name);
1264 preamble += features.getLyXSGMLEntities();
1266 if (!preamble.empty()) {
1267 os << "\n [ " << preamble << " ]";
1272 string top = top_element;
1274 if (runparams.flavor == OutputParams::XML)
1275 top += params().language->code();
1277 top += params().language->code().substr(0,2);
1280 if (!params().options.empty()) {
1282 top += params().options;
1285 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1286 << " file was created by LyX " << lyx_version
1287 << "\n See http://www.lyx.org/ for more information -->\n";
1289 params().getTextClass().counters().reset();
1291 loadChildDocuments();
1293 sgml::openTag(os, top);
1295 docbookParagraphs(paragraphs(), *this, os, runparams);
1296 sgml::closeTag(os, top_element);
1300 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1301 // Other flags: -wall -v0 -x
1302 int Buffer::runChktex()
1306 // get LaTeX-Filename
1307 FileName const path(temppath());
1308 string const name = addName(path.absFilename(), latexName());
1309 string const org_path = filePath();
1311 PathChanger p(path); // path to LaTeX file
1312 message(_("Running chktex..."));
1314 // Generate the LaTeX file if neccessary
1315 OutputParams runparams(¶ms().encoding());
1316 runparams.flavor = OutputParams::LATEX;
1317 runparams.nice = false;
1318 makeLaTeXFile(FileName(name), org_path, runparams);
1321 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1322 int const res = chktex.run(terr); // run chktex
1325 Alert::error(_("chktex failure"),
1326 _("Could not run chktex successfully."));
1327 } else if (res > 0) {
1328 ErrorList & errlist = d->errorLists["ChkTeX"];
1330 bufferErrors(terr, errlist);
1341 void Buffer::validate(LaTeXFeatures & features) const
1343 params().validate(features);
1345 loadChildDocuments();
1347 for_each(paragraphs().begin(), paragraphs().end(),
1348 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1350 if (lyxerr.debugging(Debug::LATEX)) {
1351 features.showStruct();
1356 void Buffer::getLabelList(vector<docstring> & list) const
1358 /// if this is a child document and the parent is already loaded
1359 /// Use the parent's list instead [ale990407]
1360 Buffer const * tmp = masterBuffer();
1362 lyxerr << "masterBuffer() failed!" << endl;
1366 tmp->getLabelList(list);
1370 loadChildDocuments();
1372 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1373 it.nextInset()->getLabelList(*this, list);
1377 void Buffer::updateBibfilesCache() const
1379 // if this is a child document and the parent is already loaded
1380 // update the parent's cache instead
1381 Buffer const * tmp = masterBuffer();
1384 tmp->updateBibfilesCache();
1388 d->bibfilesCache_.clear();
1389 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1390 if (it->lyxCode() == BIBTEX_CODE) {
1391 InsetBibtex const & inset =
1392 static_cast<InsetBibtex const &>(*it);
1393 EmbeddedFileList const bibfiles = inset.getFiles(*this);
1394 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1397 } else if (it->lyxCode() == INCLUDE_CODE) {
1398 InsetInclude & inset =
1399 static_cast<InsetInclude &>(*it);
1400 inset.updateBibfilesCache(*this);
1401 EmbeddedFileList const & bibfiles =
1402 inset.getBibfilesCache(*this);
1403 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1411 EmbeddedFileList const & Buffer::getBibfilesCache() const
1413 // if this is a child document and the parent is already loaded
1414 // use the parent's cache instead
1415 Buffer const * tmp = masterBuffer();
1418 return tmp->getBibfilesCache();
1420 // We update the cache when first used instead of at loading time.
1421 if (d->bibfilesCache_.empty())
1422 const_cast<Buffer *>(this)->updateBibfilesCache();
1424 return d->bibfilesCache_;
1428 bool Buffer::isDepClean(string const & name) const
1430 DepClean::const_iterator const it = d->dep_clean.find(name);
1431 if (it == d->dep_clean.end())
1437 void Buffer::markDepClean(string const & name)
1439 d->dep_clean[name] = true;
1443 bool Buffer::dispatch(string const & command, bool * result)
1445 return dispatch(lyxaction.lookupFunc(command), result);
1449 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1451 bool dispatched = true;
1453 switch (func.action) {
1454 case LFUN_BUFFER_EXPORT: {
1455 bool const tmp = doExport(to_utf8(func.argument()), false);
1468 void Buffer::changeLanguage(Language const * from, Language const * to)
1473 for_each(par_iterator_begin(),
1475 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1479 bool Buffer::isMultiLingual() const
1481 ParConstIterator end = par_iterator_end();
1482 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1483 if (it->isMultiLingual(params()))
1490 ParIterator Buffer::getParFromID(int const id) const
1492 ParConstIterator it = par_iterator_begin();
1493 ParConstIterator const end = par_iterator_end();
1496 // John says this is called with id == -1 from undo
1497 lyxerr << "getParFromID(), id: " << id << endl;
1501 for (; it != end; ++it)
1509 bool Buffer::hasParWithID(int const id) const
1511 ParConstIterator const it = getParFromID(id);
1512 return it != par_iterator_end();
1516 ParIterator Buffer::par_iterator_begin()
1518 return lyx::par_iterator_begin(inset());
1522 ParIterator Buffer::par_iterator_end()
1524 return lyx::par_iterator_end(inset());
1528 ParConstIterator Buffer::par_iterator_begin() const
1530 return lyx::par_const_iterator_begin(inset());
1534 ParConstIterator Buffer::par_iterator_end() const
1536 return lyx::par_const_iterator_end(inset());
1540 Language const * Buffer::language() const
1542 return params().language;
1546 docstring const Buffer::B_(string const & l10n) const
1548 return params().B_(l10n);
1552 bool Buffer::isClean() const
1554 return d->lyx_clean;
1558 bool Buffer::isBakClean() const
1560 return d->bak_clean;
1564 bool Buffer::isExternallyModified(CheckMethod method) const
1566 BOOST_ASSERT(d->filename.exists());
1567 // if method == timestamp, check timestamp before checksum
1568 return (method == checksum_method
1569 || d->timestamp_ != d->filename.lastModified())
1570 && d->checksum_ != d->filename.checksum();
1574 void Buffer::saveCheckSum(FileName const & file) const
1576 if (file.exists()) {
1577 d->timestamp_ = file.lastModified();
1578 d->checksum_ = file.checksum();
1580 // in the case of save to a new file.
1587 void Buffer::markClean() const
1589 if (!d->lyx_clean) {
1590 d->lyx_clean = true;
1593 // if the .lyx file has been saved, we don't need an
1595 d->bak_clean = true;
1599 void Buffer::markBakClean() const
1601 d->bak_clean = true;
1605 void Buffer::setUnnamed(bool flag)
1611 bool Buffer::isUnnamed() const
1617 // FIXME: this function should be moved to buffer_pimpl.C
1618 void Buffer::markDirty()
1621 d->lyx_clean = false;
1624 d->bak_clean = false;
1626 DepClean::iterator it = d->dep_clean.begin();
1627 DepClean::const_iterator const end = d->dep_clean.end();
1629 for (; it != end; ++it)
1634 FileName Buffer::fileName() const
1640 string Buffer::absFileName() const
1642 return d->filename.absFilename();
1646 string Buffer::filePath() const
1648 return d->filename.onlyPath().absFilename() + "/";
1652 bool Buffer::isReadonly() const
1654 return d->read_only;
1658 void Buffer::setParent(Buffer const * buffer)
1660 // Avoids recursive include.
1661 d->parent_buffer = buffer == this ? 0 : buffer;
1666 Buffer const * Buffer::parent()
1668 return d->parent_buffer;
1672 Buffer const * Buffer::masterBuffer() const
1674 if (!d->parent_buffer)
1677 return d->parent_buffer->masterBuffer();
1681 template<typename M>
1682 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
1687 typename M::iterator it = m.lower_bound(x);
1688 if (it == m.begin())
1696 MacroData const * Buffer::getBufferMacro(docstring const & name,
1697 DocIterator const & pos) const
1699 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
1701 // if paragraphs have no macro context set, pos will be empty
1705 // we haven't found anything yet
1706 DocIterator bestPos = par_iterator_begin();
1707 MacroData const * bestData = 0;
1709 // find macro definitions for name
1710 Impl::NamePositionScopeMacroMap::iterator nameIt
1711 = d->macros.find(name);
1712 if (nameIt != d->macros.end()) {
1713 // find last definition in front of pos or at pos itself
1714 Impl::PositionScopeMacroMap::const_iterator it
1715 = greatest_below(nameIt->second, pos);
1716 if (it != nameIt->second.end()) {
1718 // scope ends behind pos?
1719 if (pos < it->second.first) {
1720 // Looks good, remember this. If there
1721 // is no external macro behind this,
1722 // we found the right one already.
1723 bestPos = it->first;
1724 bestData = &it->second.second;
1728 // try previous macro if there is one
1729 if (it == nameIt->second.begin())
1736 // find macros in included files
1737 Impl::PositionScopeBufferMap::const_iterator it
1738 = greatest_below(d->position_to_children, pos);
1739 if (it != d->position_to_children.end()) {
1741 // do we know something better (i.e. later) already?
1742 if (it->first < bestPos )
1745 // scope ends behind pos?
1746 if (pos < it->second.first) {
1747 // look for macro in external file
1748 d->macro_lock = true;
1749 MacroData const * data
1750 = it->second.second->getMacro(name, false);
1751 d->macro_lock = false;
1753 bestPos = it->first;
1759 // try previous file if there is one
1760 if (it == d->position_to_children.begin())
1766 // return the best macro we have found
1771 MacroData const * Buffer::getMacro(docstring const & name,
1772 DocIterator const & pos, bool global) const
1777 // query buffer macros
1778 MacroData const * data = getBufferMacro(name, pos);
1782 // If there is a master buffer, query that
1783 if (d->parent_buffer) {
1784 d->macro_lock = true;
1785 MacroData const * macro
1786 = d->parent_buffer->getMacro(name, *this, false);
1787 d->macro_lock = false;
1793 data = MacroTable::globalMacros().get(name);
1802 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
1804 // set scope end behind the last paragraph
1805 DocIterator scope = par_iterator_begin();
1806 scope.pit() = scope.lastpit() + 1;
1808 return getMacro(name, scope, global);
1812 MacroData const * Buffer::getMacro(docstring const & name, Buffer const & child, bool global) const
1814 // look where the child buffer is included first
1815 Impl::BufferPositionMap::iterator it
1816 = d->children_positions.find(&child);
1817 if (it == d->children_positions.end())
1820 // check for macros at the inclusion position
1821 return getMacro(name, it->second, global);
1825 void Buffer::updateEnvironmentMacros(DocIterator & it,
1827 DocIterator & scope) const
1829 Paragraph & par = it.paragraph();
1831 = par.params().depth();
1832 Length const & leftIndent
1833 = par.params().leftIndent();
1835 // look for macros in each paragraph
1836 while (it.pit() <= lastpit) {
1837 Paragraph & par = it.paragraph();
1840 if ((par.params().depth() > depth
1841 || par.params().leftIndent() != leftIndent)
1842 && par.layout()->isEnvironment()) {
1843 updateBlockMacros(it, scope);
1847 // iterate over the insets of the current paragraph
1848 InsetList const & insets = par.insetList();
1849 InsetList::const_iterator iit = insets.begin();
1850 InsetList::const_iterator end = insets.end();
1851 for (; iit != end; ++iit) {
1852 it.pos() = iit->pos;
1854 // is it a nested text inset?
1855 if (iit->inset->asInsetText()) {
1856 // Inset needs its own scope?
1857 InsetText const * itext
1858 = iit->inset->asInsetText();
1859 bool newScope = itext->isMacroScope(*this);
1861 // scope which ends just behind die inset
1862 DocIterator insetScope = it;
1865 // collect macros in inset
1866 it.push_back(CursorSlice(*iit->inset));
1867 updateInsetMacros(it, newScope ? insetScope : scope);
1872 // is it an external file?
1873 if (iit->inset->lyxCode() == INCLUDE_CODE) {
1874 // get buffer of external file
1875 InsetCommand const & inset
1876 = static_cast<InsetCommand const &>(*iit->inset);
1877 InsetCommandParams const & ip = inset.params();
1878 d->macro_lock = true;
1879 Buffer * child = loadIfNeeded(*this, ip);
1880 d->macro_lock = false;
1884 // register it, but only when it is
1885 // included first in the buffer
1886 if (d->children_positions.find(child)
1887 == d->children_positions.end())
1888 d->children_positions[child] = it;
1890 // register child with its scope
1891 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
1896 if (iit->inset->lyxCode() != MATHMACRO_CODE)
1900 MathMacroTemplate & macroTemplate
1901 = static_cast<MathMacroTemplate &>(*iit->inset);
1902 MacroContext mc(*this, it);
1903 macroTemplate.updateToContext(mc);
1906 bool valid = macroTemplate.validMacro();
1907 // FIXME: Should be fixNameAndCheckIfValid() in fact,
1908 // then the BufferView's cursor will be invalid in
1909 // some cases which leads to crashes.
1914 d->macros[macroTemplate.name()][it]
1915 = Impl::ScopeMacro(scope, MacroData(*this, it));
1925 void Buffer::updateBlockMacros(DocIterator & it, DocIterator & scope) const
1927 Paragraph & par = it.paragraph();
1929 // set scope for macros in this paragraph:
1930 // * either the "old" outer scope
1931 // * or the scope ending after the environment
1932 if (par.layout()->isEnvironment()) {
1933 // find end of environment block,
1934 DocIterator envEnd = it;
1935 pit_type n = it.lastpit() + 1;
1936 depth_type depth = par.params().depth();
1937 Length const & length = par.params().leftIndent();
1938 // looping through the paragraph, basically until
1939 // the layout changes or the depth gets smaller.
1940 // (the logic of output_latex.cpp's TeXEnvironment)
1943 if (envEnd.pit() == n)
1945 } while (par.layout() == envEnd.paragraph().layout()
1946 || depth < envEnd.paragraph().params().depth()
1947 || length != envEnd.paragraph().params().leftIndent());
1949 // collect macros from environment block
1950 updateEnvironmentMacros(it, envEnd.pit() - 1, envEnd);
1952 // collect macros from paragraph
1953 updateEnvironmentMacros(it, it.pit(), scope);
1958 void Buffer::updateInsetMacros(DocIterator & it, DocIterator & scope) const
1960 // look for macros in each paragraph
1961 pit_type n = it.lastpit() + 1;
1962 while (it.pit() < n)
1963 updateBlockMacros(it, scope);
1967 void Buffer::updateMacros() const
1972 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
1974 // start with empty table
1976 d->children_positions.clear();
1977 d->position_to_children.clear();
1979 // Iterate over buffer, starting with first paragraph
1980 // The scope must be bigger than any lookup DocIterator
1981 // later. For the global lookup, lastpit+1 is used, hence
1982 // we use lastpit+2 here.
1983 DocIterator it = par_iterator_begin();
1984 DocIterator outerScope = it;
1985 outerScope.pit() = outerScope.lastpit() + 2;
1986 updateInsetMacros(it, outerScope);
1990 void Buffer::updateMacroInstances() const
1992 LYXERR(Debug::MACROS, "updateMacroInstances for " << d->filename.onlyFileName());
1993 ParIterator it = par_iterator_begin();
1994 ParIterator end = par_iterator_end();
1995 for (; it != end; it.forwardPos()) {
1996 // look for MathData cells in InsetMathNest insets
1997 Inset * inset = it.nextInset();
2001 InsetMath * minset = inset->asInsetMath();
2005 // update macro in all cells of the InsetMathNest
2006 DocIterator::idx_type n = minset->nargs();
2007 MacroContext mc = MacroContext(*this, it);
2008 for (DocIterator::idx_type i = 0; i < n; ++i) {
2009 MathData & data = minset->cell(i);
2010 data.updateMacros(0, mc);
2016 void Buffer::listMacroNames(MacroNameSet & macros) const
2021 d->macro_lock = true;
2023 // loop over macro names
2024 Impl::NamePositionScopeMacroMap::iterator nameIt
2025 = d->macros.begin();
2026 Impl::NamePositionScopeMacroMap::iterator nameEnd
2028 for (; nameIt != nameEnd; ++nameIt)
2029 macros.insert(nameIt->first);
2031 // loop over children
2032 Impl::BufferPositionMap::iterator it
2033 = d->children_positions.begin();
2034 Impl::BufferPositionMap::iterator end
2035 = d->children_positions.end();
2036 for (; it != end; ++it)
2037 it->first->listMacroNames(macros);
2040 if (d->parent_buffer)
2041 d->parent_buffer->listMacroNames(macros);
2043 d->macro_lock = false;
2047 void Buffer::writeParentMacros(odocstream & os) const
2049 if (!d->parent_buffer)
2052 // collect macro names
2054 d->parent_buffer->listMacroNames(names);
2056 // resolve and output them
2057 MacroNameSet::iterator it = names.begin();
2058 MacroNameSet::iterator end = names.end();
2059 for (; it != end; ++it) {
2061 MacroData const * data =
2062 d->parent_buffer->getMacro(*it, *this, false);
2064 data->write(os, true);
2069 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2072 //FIXME: This does not work for child documents yet.
2073 BOOST_ASSERT(code == CITE_CODE || code == REF_CODE);
2074 // Check if the label 'from' appears more than once
2075 vector<docstring> labels;
2078 if (code == CITE_CODE) {
2080 keys.fillWithBibKeys(this);
2081 BiblioInfo::const_iterator bit = keys.begin();
2082 BiblioInfo::const_iterator bend = keys.end();
2084 for (; bit != bend; ++bit)
2086 labels.push_back(bit->first);
2089 getLabelList(labels);
2090 paramName = "reference";
2093 if (count(labels.begin(), labels.end(), from) > 1)
2096 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2097 if (it->lyxCode() == code) {
2098 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2099 docstring const oldValue = inset.getParam(paramName);
2100 if (oldValue == from)
2101 inset.setParam(paramName, to);
2107 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2108 pit_type par_end, bool full_source)
2110 OutputParams runparams(¶ms().encoding());
2111 runparams.nice = true;
2112 runparams.flavor = OutputParams::LATEX;
2113 runparams.linelen = lyxrc.plaintext_linelen;
2114 // No side effect of file copying and image conversion
2115 runparams.dryrun = true;
2119 os << "% " << _("Preview source code") << "\n\n";
2120 d->texrow.newline();
2121 d->texrow.newline();
2123 writeLaTeXSource(os, filePath(), runparams, true, true);
2125 writeDocBookSource(os, absFileName(), runparams, false);
2128 runparams.par_begin = par_begin;
2129 runparams.par_end = par_end;
2130 if (par_begin + 1 == par_end)
2132 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2136 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2137 convert<docstring>(par_begin),
2138 convert<docstring>(par_end - 1))
2140 d->texrow.newline();
2141 d->texrow.newline();
2142 // output paragraphs
2144 latexParagraphs(*this, paragraphs(), os, d->texrow, runparams);
2147 docbookParagraphs(paragraphs(), *this, os, runparams);
2153 ErrorList & Buffer::errorList(string const & type) const
2155 static ErrorList emptyErrorList;
2156 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2157 if (I == d->errorLists.end())
2158 return emptyErrorList;
2164 void Buffer::structureChanged() const
2167 gui_->structureChanged();
2171 void Buffer::errors(string const & err) const
2178 void Buffer::message(docstring const & msg) const
2185 void Buffer::setBusy(bool on) const
2192 void Buffer::setReadOnly(bool on) const
2195 d->wa_->setReadOnly(on);
2199 void Buffer::updateTitles() const
2202 d->wa_->updateTitles();
2206 void Buffer::resetAutosaveTimers() const
2209 gui_->resetAutosaveTimers();
2213 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2222 class AutoSaveBuffer : public ForkedProcess {
2225 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2226 : buffer_(buffer), fname_(fname) {}
2228 virtual boost::shared_ptr<ForkedProcess> clone() const
2230 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2235 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2236 from_utf8(fname_.absFilename())));
2237 return run(DontWait);
2241 virtual int generateChild();
2243 Buffer const & buffer_;
2248 #if !defined (HAVE_FORK)
2252 int AutoSaveBuffer::generateChild()
2254 // tmp_ret will be located (usually) in /tmp
2255 // will that be a problem?
2256 pid_t const pid = fork();
2257 // If you want to debug the autosave
2258 // you should set pid to -1, and comment out the fork.
2259 if (pid == 0 || pid == -1) {
2260 // pid = -1 signifies that lyx was unable
2261 // to fork. But we will do the save
2263 bool failed = false;
2265 FileName const tmp_ret = FileName::tempName("lyxauto");
2266 if (!tmp_ret.empty()) {
2267 buffer_.writeFile(tmp_ret);
2268 // assume successful write of tmp_ret
2269 if (!tmp_ret.moveTo(fname_)) {
2271 // most likely couldn't move between
2272 // filesystems unless write of tmp_ret
2273 // failed so remove tmp file (if it
2275 tmp_ret.removeFile();
2282 // failed to write/rename tmp_ret so try writing direct
2283 if (!buffer_.writeFile(fname_)) {
2284 // It is dangerous to do this in the child,
2285 // but safe in the parent, so...
2286 if (pid == -1) // emit message signal.
2287 buffer_.message(_("Autosave failed!"));
2290 if (pid == 0) { // we are the child so...
2300 // Perfect target for a thread...
2301 void Buffer::autoSave() const
2303 if (isBakClean() || isReadonly()) {
2304 // We don't save now, but we'll try again later
2305 resetAutosaveTimers();
2309 // emit message signal.
2310 message(_("Autosaving current document..."));
2312 // create autosave filename
2313 string fname = filePath();
2315 fname += d->filename.onlyFileName();
2318 AutoSaveBuffer autosave(*this, FileName(fname));
2322 resetAutosaveTimers();
2326 void Buffer::resetChildDocuments(bool close_them) const
2328 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2329 if (it->lyxCode() != INCLUDE_CODE)
2331 InsetCommand const & inset = static_cast<InsetCommand const &>(*it);
2332 InsetCommandParams const & ip = inset.params();
2334 resetParentBuffer(this, ip, close_them);
2337 if (use_gui && masterBuffer() == this)
2338 updateLabels(*this);
2340 // clear references to children in macro tables
2341 d->children_positions.clear();
2342 d->position_to_children.clear();
2346 void Buffer::loadChildDocuments() const
2348 bool parse_error = false;
2350 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2351 if (it->lyxCode() != INCLUDE_CODE)
2353 InsetCommand const & inset = static_cast<InsetCommand const &>(*it);
2354 InsetCommandParams const & ip = inset.params();
2355 Buffer * child = loadIfNeeded(*this, ip);
2358 parse_error |= !child->errorList("Parse").empty();
2359 child->loadChildDocuments();
2362 if (use_gui && masterBuffer() == this)
2363 updateLabels(*this);
2369 string Buffer::bufferFormat() const
2379 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2380 string & result_file) const
2382 string backend_format;
2383 OutputParams runparams(¶ms().encoding());
2384 runparams.flavor = OutputParams::LATEX;
2385 runparams.linelen = lyxrc.plaintext_linelen;
2386 vector<string> backs = backends();
2387 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2388 // Get shortest path to format
2389 Graph::EdgePath path;
2390 for (vector<string>::const_iterator it = backs.begin();
2391 it != backs.end(); ++it) {
2392 Graph::EdgePath p = theConverters().getPath(*it, format);
2393 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2394 backend_format = *it;
2399 runparams.flavor = theConverters().getFlavor(path);
2401 Alert::error(_("Couldn't export file"),
2402 bformat(_("No information for exporting the format %1$s."),
2403 formats.prettyName(format)));
2407 backend_format = format;
2408 // FIXME: Don't hardcode format names here, but use a flag
2409 if (backend_format == "pdflatex")
2410 runparams.flavor = OutputParams::PDFLATEX;
2413 string filename = latexName(false);
2414 filename = addName(temppath(), filename);
2415 filename = changeExtension(filename,
2416 formats.extension(backend_format));
2419 updateMacroInstances();
2421 // Plain text backend
2422 if (backend_format == "text")
2423 writePlaintextFile(*this, FileName(filename), runparams);
2425 else if (backend_format == "lyx")
2426 writeFile(FileName(filename));
2428 else if (isDocBook()) {
2429 runparams.nice = !put_in_tempdir;
2430 makeDocBookFile(FileName(filename), runparams);
2433 else if (backend_format == format) {
2434 runparams.nice = true;
2435 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2437 } else if (!lyxrc.tex_allows_spaces
2438 && contains(filePath(), ' ')) {
2439 Alert::error(_("File name error"),
2440 _("The directory path to the document cannot contain spaces."));
2443 runparams.nice = false;
2444 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2448 string const error_type = (format == "program")
2449 ? "Build" : bufferFormat();
2450 string const ext = formats.extension(format);
2451 FileName const tmp_result_file(changeExtension(filename, ext));
2452 bool const success = theConverters().convert(this, FileName(filename),
2453 tmp_result_file, FileName(absFileName()), backend_format, format,
2454 errorList(error_type));
2455 // Emit the signal to show the error list.
2456 if (format != backend_format)
2462 result_file = tmp_result_file.absFilename();
2464 result_file = changeExtension(absFileName(), ext);
2465 // We need to copy referenced files (e. g. included graphics
2466 // if format == "dvi") to the result dir.
2467 vector<ExportedFile> const files =
2468 runparams.exportdata->externalFiles(format);
2469 string const dest = onlyPath(result_file);
2470 CopyStatus status = SUCCESS;
2471 for (vector<ExportedFile>::const_iterator it = files.begin();
2472 it != files.end() && status != CANCEL; ++it) {
2474 formats.getFormatFromFile(it->sourceName);
2475 status = copyFile(fmt, it->sourceName,
2476 makeAbsPath(it->exportName, dest),
2477 it->exportName, status == FORCE);
2479 if (status == CANCEL) {
2480 message(_("Document export cancelled."));
2481 } else if (tmp_result_file.exists()) {
2482 // Finally copy the main file
2483 status = copyFile(format, tmp_result_file,
2484 FileName(result_file), result_file,
2486 message(bformat(_("Document exported as %1$s "
2488 formats.prettyName(format),
2489 makeDisplayPath(result_file)));
2491 // This must be a dummy converter like fax (bug 1888)
2492 message(bformat(_("Document exported as %1$s"),
2493 formats.prettyName(format)));
2501 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2504 return doExport(format, put_in_tempdir, result_file);
2508 bool Buffer::preview(string const & format) const
2511 if (!doExport(format, true, result_file))
2513 return formats.view(*this, FileName(result_file), format);
2517 bool Buffer::isExportable(string const & format) const
2519 vector<string> backs = backends();
2520 for (vector<string>::const_iterator it = backs.begin();
2521 it != backs.end(); ++it)
2522 if (theConverters().isReachable(*it, format))
2528 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2530 vector<string> backs = backends();
2531 vector<Format const *> result =
2532 theConverters().getReachable(backs[0], only_viewable, true);
2533 for (vector<string>::const_iterator it = backs.begin() + 1;
2534 it != backs.end(); ++it) {
2535 vector<Format const *> r =
2536 theConverters().getReachable(*it, only_viewable, false);
2537 result.insert(result.end(), r.begin(), r.end());
2543 vector<string> Buffer::backends() const
2546 if (params().getTextClass().isTeXClassAvailable()) {
2547 v.push_back(bufferFormat());
2548 // FIXME: Don't hardcode format names here, but use a flag
2549 if (v.back() == "latex")
2550 v.push_back("pdflatex");
2552 v.push_back("text");
2558 bool Buffer::readFileHelper(FileName const & s)
2560 // File information about normal file
2562 docstring const file = makeDisplayPath(s.absFilename(), 50);
2563 docstring text = bformat(_("The specified document\n%1$s"
2564 "\ncould not be read."), file);
2565 Alert::error(_("Could not read document"), text);
2569 // Check if emergency save file exists and is newer.
2570 FileName const e(s.absFilename() + ".emergency");
2572 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2573 docstring const file = makeDisplayPath(s.absFilename(), 20);
2574 docstring const text =
2575 bformat(_("An emergency save of the document "
2577 "Recover emergency save?"), file);
2578 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2579 _("&Recover"), _("&Load Original"),
2583 // the file is not saved if we load the emergency file.
2593 // Now check if autosave file is newer.
2594 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2596 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2597 docstring const file = makeDisplayPath(s.absFilename(), 20);
2598 docstring const text =
2599 bformat(_("The backup of the document "
2600 "%1$s is newer.\n\nLoad the "
2601 "backup instead?"), file);
2602 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2603 _("&Load backup"), _("Load &original"),
2607 // the file is not saved if we load the autosave file.
2611 // Here we delete the autosave
2622 bool Buffer::loadLyXFile(FileName const & s)
2624 if (s.isReadableFile()) {
2625 if (readFileHelper(s)) {
2626 lyxvc().file_found_hook(s);
2627 if (!s.isWritable())
2632 docstring const file = makeDisplayPath(s.absFilename(), 20);
2633 // Here we probably should run
2634 if (LyXVC::file_not_found_hook(s)) {
2635 docstring const text =
2636 bformat(_("Do you want to retrieve the document"
2637 " %1$s from version control?"), file);
2638 int const ret = Alert::prompt(_("Retrieve from version control?"),
2639 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2642 // How can we know _how_ to do the checkout?
2643 // With the current VC support it has to be,
2644 // a RCS file since CVS do not have special ,v files.
2646 return loadLyXFile(s);
2654 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2656 TeXErrors::Errors::const_iterator cit = terr.begin();
2657 TeXErrors::Errors::const_iterator end = terr.end();
2659 for (; cit != end; ++cit) {
2662 int errorRow = cit->error_in_line;
2663 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2669 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2670 } while (found && id_start == id_end && pos_start == pos_end);
2672 errorList.push_back(ErrorItem(cit->error_desc,
2673 cit->error_text, id_start, pos_start, pos_end));