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;
171 mutable TocBackend toc_backend;
174 typedef pair<DocIterator, MacroData> ScopeMacro;
175 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
176 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
177 NamePositionScopeMacroMap macros;
180 /// positions of child buffers in the buffer
181 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
182 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
183 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
184 BufferPositionMap children_positions;
185 PositionScopeBufferMap position_to_children;
187 /// Container for all sort of Buffer dependant errors.
188 map<string, ErrorList> errorLists;
190 /// all embedded files of this buffer
191 EmbeddedFileList embedded_files;
193 /// timestamp and checksum used to test if the file has been externally
194 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
196 unsigned long checksum_;
199 frontend::WorkAreaManager * wa_;
204 /// A cache for the bibfiles (including bibfiles of loaded child
205 /// documents), needed for appropriate update of natbib labels.
206 mutable EmbeddedFileList bibfilesCache_;
208 mutable RefCache ref_cache_;
210 /// our Text that should be wrapped in an InsetText
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 toc_backend(&parent), macro_lock(false),
237 embedded_files(), timestamp_(0), checksum_(0), wa_(0),
240 temppath = createBufferTmpDir();
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.setBuffer(*this);
253 d->inset.initParagraphs(*this);
254 d->inset.setAutoBreakRows(true);
255 d->inset.getText(0)->setMacrocontextPosition(par_iterator_begin());
261 LYXERR(Debug::INFO, "Buffer::~Buffer()");
262 // here the buffer should take care that it is
263 // saved properly, before it goes into the void.
265 // GuiView already destroyed
268 Buffer const * master = masterBuffer();
269 if (master != this && use_gui) {
270 // We are closing buf which was a child document so we
271 // must update the labels and section numbering of its master
273 updateLabels(*master);
274 master->updateMacros();
277 resetChildDocuments(false);
279 if (!d->temppath.destroyDirectory()) {
280 Alert::warning(_("Could not remove temporary directory"),
281 bformat(_("Could not remove the temporary directory %1$s"),
282 from_utf8(d->temppath.absFilename())));
285 // Remove any previewed LaTeX snippets associated with this buffer.
286 graphics::Previews::get().removeLoader(*this);
292 void Buffer::changed() const
299 frontend::WorkAreaManager & Buffer::workAreaManager() const
301 BOOST_ASSERT(d->wa_);
306 Text & Buffer::text() const
308 return const_cast<Text &>(d->inset.text_);
312 Inset & Buffer::inset() const
314 return const_cast<InsetText &>(d->inset);
318 BufferParams & Buffer::params()
324 BufferParams const & Buffer::params() const
330 ParagraphList & Buffer::paragraphs()
332 return text().paragraphs();
336 ParagraphList const & Buffer::paragraphs() const
338 return text().paragraphs();
342 LyXVC & Buffer::lyxvc()
348 LyXVC const & Buffer::lyxvc() const
354 string const Buffer::temppath() const
356 return d->temppath.absFilename();
360 TexRow const & Buffer::texrow() const
366 TocBackend & Buffer::tocBackend() const
368 return d->toc_backend;
372 EmbeddedFileList & Buffer::embeddedFiles()
374 return d->embedded_files;
378 EmbeddedFileList const & Buffer::embeddedFiles() const
380 return d->embedded_files;
384 bool Buffer::embedded() const
386 return params().embedded;
390 Undo & Buffer::undo()
396 string Buffer::latexName(bool const no_path) const
398 FileName latex_name = makeLatexName(d->filename);
399 return no_path ? latex_name.onlyFileName()
400 : latex_name.absFilename();
404 string Buffer::logName(LogType * type) const
406 string const filename = latexName(false);
408 if (filename.empty()) {
414 string const path = temppath();
416 FileName const fname(addName(temppath(),
417 onlyFilename(changeExtension(filename,
419 FileName const bname(
420 addName(path, onlyFilename(
421 changeExtension(filename,
422 formats.extension("literate") + ".out"))));
424 // If no Latex log or Build log is newer, show Build log
426 if (bname.exists() &&
427 (!fname.exists() || fname.lastModified() < bname.lastModified())) {
428 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
431 return bname.absFilename();
433 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
436 return fname.absFilename();
440 void Buffer::setReadonly(bool const flag)
442 if (d->read_only != flag) {
449 void Buffer::setFileName(string const & newfile)
451 d->filename = makeAbsPath(newfile);
452 setReadonly(d->filename.isReadOnly());
457 int Buffer::readHeader(Lexer & lex)
459 int unknown_tokens = 0;
461 int begin_header_line = -1;
463 // Initialize parameters that may be/go lacking in header:
464 params().branchlist().clear();
465 params().preamble.erase();
466 params().options.erase();
467 params().float_placement.erase();
468 params().paperwidth.erase();
469 params().paperheight.erase();
470 params().leftmargin.erase();
471 params().rightmargin.erase();
472 params().topmargin.erase();
473 params().bottommargin.erase();
474 params().headheight.erase();
475 params().headsep.erase();
476 params().footskip.erase();
477 params().columnsep.erase();
478 params().listings_params.clear();
479 params().clearLayoutModules();
480 params().pdfoptions().clear();
482 for (int i = 0; i < 4; ++i) {
483 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
484 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
487 ErrorList & errorList = d->errorLists["Parse"];
491 string const token = lex.getString();
496 if (token == "\\end_header")
500 if (token == "\\begin_header") {
501 begin_header_line = line;
505 LYXERR(Debug::PARSER, "Handling document header token: `"
508 string unknown = params().readToken(lex, token, d->filename.onlyPath());
509 if (!unknown.empty()) {
510 if (unknown[0] != '\\' && token == "\\textclass") {
511 Alert::warning(_("Unknown document class"),
512 bformat(_("Using the default document class, because the "
513 "class %1$s is unknown."), from_utf8(unknown)));
516 docstring const s = bformat(_("Unknown token: "
520 errorList.push_back(ErrorItem(_("Document header error"),
525 if (begin_header_line) {
526 docstring const s = _("\\begin_header is missing");
527 errorList.push_back(ErrorItem(_("Document header error"),
531 params().makeDocumentClass();
533 return unknown_tokens;
538 // changed to be public and have one parameter
539 // Returns false if "\end_document" is not read (Asger)
540 bool Buffer::readDocument(Lexer & lex)
542 ErrorList & errorList = d->errorLists["Parse"];
546 string const token = lex.getString();
547 if (token != "\\begin_document") {
548 docstring const s = _("\\begin_document is missing");
549 errorList.push_back(ErrorItem(_("Document header error"),
553 // we are reading in a brand new document
554 BOOST_ASSERT(paragraphs().empty());
558 if (params().outputChanges) {
559 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
560 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
561 LaTeXFeatures::isAvailable("xcolor");
563 if (!dvipost && !xcolorsoul) {
564 Alert::warning(_("Changes not shown in LaTeX output"),
565 _("Changes will not be highlighted in LaTeX output, "
566 "because neither dvipost nor xcolor/soul are installed.\n"
567 "Please install these packages or redefine "
568 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
569 } else if (!xcolorsoul) {
570 Alert::warning(_("Changes not shown in LaTeX output"),
571 _("Changes will not be highlighted in LaTeX output "
572 "when using pdflatex, because xcolor and soul are not installed.\n"
573 "Please install both packages or redefine "
574 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
579 bool const res = text().read(*this, lex, errorList, &(d->inset));
582 updateMacroInstances();
587 // needed to insert the selection
588 void Buffer::insertStringAsLines(ParagraphList & pars,
589 pit_type & pit, pos_type & pos,
590 Font const & fn, docstring const & str, bool autobreakrows)
594 // insert the string, don't insert doublespace
595 bool space_inserted = true;
596 for (docstring::const_iterator cit = str.begin();
597 cit != str.end(); ++cit) {
598 Paragraph & par = pars[pit];
600 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
601 breakParagraph(params(), pars, pit, pos,
602 par.layout()->isEnvironment());
605 space_inserted = true;
609 // do not insert consecutive spaces if !free_spacing
610 } else if ((*cit == ' ' || *cit == '\t') &&
611 space_inserted && !par.isFreeSpacing()) {
613 } else if (*cit == '\t') {
614 if (!par.isFreeSpacing()) {
615 // tabs are like spaces here
616 par.insertChar(pos, ' ', font, params().trackChanges);
618 space_inserted = true;
620 const pos_type n = 8 - pos % 8;
621 for (pos_type i = 0; i < n; ++i) {
622 par.insertChar(pos, ' ', font, params().trackChanges);
625 space_inserted = true;
627 } else if (!isPrintable(*cit)) {
628 // Ignore unprintables
631 // just insert the character
632 par.insertChar(pos, *cit, font, params().trackChanges);
634 space_inserted = (*cit == ' ');
641 bool Buffer::readString(string const & s)
643 params().compressed = false;
645 // remove dummy empty par
646 paragraphs().clear();
650 FileName const name = FileName::tempName();
651 switch (readFile(lex, name, true)) {
655 // We need to call lyx2lyx, so write the input to a file
656 ofstream os(name.toFilesystemEncoding().c_str());
659 return readFile(name);
669 bool Buffer::readFile(FileName const & filename)
671 FileName fname(filename);
672 // Check if the file is compressed.
673 string format = filename.guessFormatFromContents();
674 if (format == "zip") {
675 // decompress to a temp directory
676 LYXERR(Debug::FILES, filename << " is in zip format. Unzip to " << temppath());
677 ::unzipToDir(filename.toFilesystemEncoding(), temppath());
679 FileName lyxfile(addName(temppath(), "content.lyx"));
680 // if both manifest.txt and file.lyx exist, this is am embedded file
681 if (lyxfile.exists()) {
682 // if in bundled format, save checksum of the compressed file, not content.lyx
683 saveCheckSum(filename);
684 params().embedded = true;
688 // The embedded lyx file can also be compressed, for backward compatibility
689 format = fname.guessFormatFromContents();
690 if (format == "gzip" || format == "zip" || format == "compress")
691 params().compressed = true;
693 // remove dummy empty par
694 paragraphs().clear();
697 if (readFile(lex, fname) != success)
704 bool Buffer::isFullyLoaded() const
706 return d->file_fully_loaded;
710 void Buffer::setFullyLoaded(bool value)
712 d->file_fully_loaded = value;
716 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
719 BOOST_ASSERT(!filename.empty());
722 Alert::error(_("Document could not be read"),
723 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
728 string const token = lex.getString();
731 Alert::error(_("Document could not be read"),
732 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
736 // the first token _must_ be...
737 if (token != "\\lyxformat") {
738 lyxerr << "Token: " << token << endl;
740 Alert::error(_("Document format failure"),
741 bformat(_("%1$s is not a LyX document."),
742 from_utf8(filename.absFilename())));
747 string tmp_format = lex.getString();
748 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
749 // if present remove ".," from string.
750 string::size_type dot = tmp_format.find_first_of(".,");
751 //lyxerr << " dot found at " << dot << endl;
752 if (dot != string::npos)
753 tmp_format.erase(dot, 1);
754 int const file_format = convert<int>(tmp_format);
755 //lyxerr << "format: " << file_format << endl;
757 // save timestamp and checksum of the original disk file, making sure
758 // to not overwrite them with those of the file created in the tempdir
759 // when it has to be converted to the current format.
761 // Save the timestamp and checksum of disk file. If filename is an
762 // emergency file, save the timestamp and checksum of the original lyx file
763 // because isExternallyModified will check for this file. (BUG4193)
764 string diskfile = filename.absFilename();
765 if (suffixIs(diskfile, ".emergency"))
766 diskfile = diskfile.substr(0, diskfile.size() - 10);
767 saveCheckSum(FileName(diskfile));
770 if (file_format != LYX_FORMAT) {
773 // lyx2lyx would fail
776 FileName const tmpfile = FileName::tempName();
777 if (tmpfile.empty()) {
778 Alert::error(_("Conversion failed"),
779 bformat(_("%1$s is from a different"
780 " version of LyX, but a temporary"
781 " file for converting it could"
783 from_utf8(filename.absFilename())));
786 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
787 if (lyx2lyx.empty()) {
788 Alert::error(_("Conversion script not found"),
789 bformat(_("%1$s is from a different"
790 " version of LyX, but the"
791 " conversion script lyx2lyx"
792 " could not be found."),
793 from_utf8(filename.absFilename())));
796 ostringstream command;
797 command << os::python()
798 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
799 << " -t " << convert<string>(LYX_FORMAT)
800 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
801 << ' ' << quoteName(filename.toFilesystemEncoding());
802 string const command_str = command.str();
804 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
806 cmd_ret const ret = runCommand(command_str);
807 if (ret.first != 0) {
808 Alert::error(_("Conversion script failed"),
809 bformat(_("%1$s is from a different version"
810 " of LyX, but the lyx2lyx script"
811 " failed to convert it."),
812 from_utf8(filename.absFilename())));
815 bool const ret = readFile(tmpfile);
816 // Do stuff with tmpfile name and buffer name here.
817 return ret ? success : failure;
822 if (readDocument(lex)) {
823 Alert::error(_("Document format failure"),
824 bformat(_("%1$s ended unexpectedly, which means"
825 " that it is probably corrupted."),
826 from_utf8(filename.absFilename())));
829 d->file_fully_loaded = true;
834 // Should probably be moved to somewhere else: BufferView? LyXView?
835 bool Buffer::save() const
837 // We don't need autosaves in the immediate future. (Asger)
838 resetAutosaveTimers();
840 string const encodedFilename = d->filename.toFilesystemEncoding();
843 bool madeBackup = false;
845 // make a backup if the file already exists
846 if (lyxrc.make_backup && fileName().exists()) {
847 backupName = FileName(absFileName() + '~');
848 if (!lyxrc.backupdir_path.empty()) {
849 string const mangledName =
850 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
851 backupName = FileName(addName(lyxrc.backupdir_path,
854 if (fileName().copyTo(backupName)) {
857 Alert::error(_("Backup failure"),
858 bformat(_("Cannot create backup file %1$s.\n"
859 "Please check whether the directory exists and is writeable."),
860 from_utf8(backupName.absFilename())));
861 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
865 // ask if the disk file has been externally modified (use checksum method)
866 if (fileName().exists() && isExternallyModified(checksum_method)) {
867 docstring const file = makeDisplayPath(absFileName(), 20);
868 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
869 "you want to overwrite this file?"), file);
870 int const ret = Alert::prompt(_("Overwrite modified file?"),
871 text, 1, 1, _("&Overwrite"), _("&Cancel"));
876 if (writeFile(d->filename)) {
880 // Saving failed, so backup is not backup
882 backupName.moveTo(d->filename);
888 bool Buffer::writeFile(FileName const & fname) const
890 if (d->read_only && fname == d->filename)
896 if (params().embedded)
897 // first write the .lyx file to the temporary directory
898 content = FileName(addName(temppath(), "content.lyx"));
902 docstring const str = bformat(_("Saving document %1$s..."),
903 makeDisplayPath(content.absFilename()));
906 if (params().compressed) {
907 gz::ogzstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
908 retval = ofs && write(ofs);
910 ofstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
911 retval = ofs && write(ofs);
915 message(str + _(" could not write file!."));
919 removeAutosaveFile(d->filename.absFilename());
921 if (params().embedded) {
922 message(str + _(" writing embedded files!."));
923 // if embedding is enabled, write file.lyx and all the embedded files
924 // to the zip file fname.
925 if (!d->embedded_files.writeFile(fname, *this)) {
926 message(str + _(" could not write embedded files!."));
930 saveCheckSum(d->filename);
931 message(str + _(" done."));
937 bool Buffer::write(ostream & ofs) const
940 // Use the standard "C" locale for file output.
941 ofs.imbue(locale::classic());
944 // The top of the file should not be written by params().
946 // write out a comment in the top of the file
947 ofs << "#LyX " << lyx_version
948 << " created this file. For more info see http://www.lyx.org/\n"
949 << "\\lyxformat " << LYX_FORMAT << "\n"
950 << "\\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 = const_cast<Buffer *>(this)->par_iterator_end();
960 ParIterator it = const_cast<Buffer *>(this)->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 // load children, if not already done.
1137 // This includes an updateMacro() call.
1138 // Don't move this behind the parent_buffer=0 code below,
1139 // because then the macros will not get the right "redefinition"
1140 // flag as they don't see the parent macros which are output before.
1141 loadChildDocuments();
1143 // fold macros if possible, still with parent buffer as the
1144 // macros will be put in the prefix anyway.
1145 updateMacroInstances();
1147 // if we are doing a real file with body, even if this is the
1148 // child of some other buffer, let's cut the link here.
1149 // This happens for example if only a child document is printed.
1150 Buffer const * save_parent = 0;
1151 if (output_preamble) {
1152 // output the macros visible for this buffer
1153 writeParentMacros(os);
1155 save_parent = d->parent_buffer;
1156 d->parent_buffer = 0;
1160 latexParagraphs(*this, text(), os, d->texrow, runparams);
1162 // Restore the parenthood if needed
1163 if (output_preamble) {
1164 d->parent_buffer = save_parent;
1166 // restore macros with correct parent buffer (especially
1167 // important for the redefinition flag which depends on the
1172 // add this just in case after all the paragraphs
1174 d->texrow.newline();
1176 if (output_preamble) {
1177 os << "\\end{document}\n";
1178 d->texrow.newline();
1179 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1181 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1183 runparams_in.encoding = runparams.encoding;
1185 // Just to be sure. (Asger)
1186 d->texrow.newline();
1188 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1189 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1193 bool Buffer::isLatex() const
1195 return params().documentClass().outputType() == LATEX;
1199 bool Buffer::isLiterate() const
1201 return params().documentClass().outputType() == LITERATE;
1205 bool Buffer::isDocBook() const
1207 return params().documentClass().outputType() == DOCBOOK;
1211 void Buffer::makeDocBookFile(FileName const & fname,
1212 OutputParams const & runparams,
1213 bool const body_only) const
1215 LYXERR(Debug::LATEX, "makeDocBookFile...");
1218 if (!openFileWrite(ofs, fname))
1221 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1225 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1229 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1230 OutputParams const & runparams,
1231 bool const only_body) const
1233 LaTeXFeatures features(*this, params(), runparams);
1238 DocumentClass const & tclass = params().documentClass();
1239 string const top_element = tclass.latexname();
1242 if (runparams.flavor == OutputParams::XML)
1243 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1246 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1249 if (! tclass.class_header().empty())
1250 os << from_ascii(tclass.class_header());
1251 else if (runparams.flavor == OutputParams::XML)
1252 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1253 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1255 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1257 docstring preamble = from_utf8(params().preamble);
1258 if (runparams.flavor != OutputParams::XML ) {
1259 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1260 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1261 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1262 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1265 string const name = runparams.nice
1266 ? changeExtension(absFileName(), ".sgml") : fname;
1267 preamble += features.getIncludedFiles(name);
1268 preamble += features.getLyXSGMLEntities();
1270 if (!preamble.empty()) {
1271 os << "\n [ " << preamble << " ]";
1276 string top = top_element;
1278 if (runparams.flavor == OutputParams::XML)
1279 top += params().language->code();
1281 top += params().language->code().substr(0,2);
1284 if (!params().options.empty()) {
1286 top += params().options;
1289 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1290 << " file was created by LyX " << lyx_version
1291 << "\n See http://www.lyx.org/ for more information -->\n";
1293 params().documentClass().counters().reset();
1295 loadChildDocuments();
1297 sgml::openTag(os, top);
1299 docbookParagraphs(paragraphs(), *this, os, runparams);
1300 sgml::closeTag(os, top_element);
1304 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1305 // Other flags: -wall -v0 -x
1306 int Buffer::runChktex()
1310 // get LaTeX-Filename
1311 FileName const path(temppath());
1312 string const name = addName(path.absFilename(), latexName());
1313 string const org_path = filePath();
1315 PathChanger p(path); // path to LaTeX file
1316 message(_("Running chktex..."));
1318 // Generate the LaTeX file if neccessary
1319 OutputParams runparams(¶ms().encoding());
1320 runparams.flavor = OutputParams::LATEX;
1321 runparams.nice = false;
1322 makeLaTeXFile(FileName(name), org_path, runparams);
1325 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1326 int const res = chktex.run(terr); // run chktex
1329 Alert::error(_("chktex failure"),
1330 _("Could not run chktex successfully."));
1331 } else if (res > 0) {
1332 ErrorList & errlist = d->errorLists["ChkTeX"];
1334 bufferErrors(terr, errlist);
1345 void Buffer::validate(LaTeXFeatures & features) const
1347 params().validate(features);
1349 loadChildDocuments();
1351 for_each(paragraphs().begin(), paragraphs().end(),
1352 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1354 if (lyxerr.debugging(Debug::LATEX)) {
1355 features.showStruct();
1360 void Buffer::getLabelList(vector<docstring> & list) const
1362 /// if this is a child document and the parent is already loaded
1363 /// Use the parent's list instead [ale990407]
1364 Buffer const * tmp = masterBuffer();
1366 lyxerr << "masterBuffer() failed!" << endl;
1370 tmp->getLabelList(list);
1374 loadChildDocuments();
1376 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1377 it.nextInset()->getLabelList(list);
1381 void Buffer::updateBibfilesCache() const
1383 // if this is a child document and the parent is already loaded
1384 // update the parent's cache instead
1385 Buffer const * tmp = masterBuffer();
1388 tmp->updateBibfilesCache();
1392 d->bibfilesCache_.clear();
1393 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1394 if (it->lyxCode() == BIBTEX_CODE) {
1395 InsetBibtex const & inset =
1396 static_cast<InsetBibtex const &>(*it);
1397 EmbeddedFileList const bibfiles = inset.embeddedFiles();
1398 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1401 } else if (it->lyxCode() == INCLUDE_CODE) {
1402 InsetInclude & inset =
1403 static_cast<InsetInclude &>(*it);
1404 inset.updateBibfilesCache();
1405 EmbeddedFileList const & bibfiles =
1406 inset.getBibfilesCache(*this);
1407 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1415 EmbeddedFileList const & Buffer::getBibfilesCache() const
1417 // if this is a child document and the parent is already loaded
1418 // use the parent's cache instead
1419 Buffer const * tmp = masterBuffer();
1422 return tmp->getBibfilesCache();
1424 // We update the cache when first used instead of at loading time.
1425 if (d->bibfilesCache_.empty())
1426 const_cast<Buffer *>(this)->updateBibfilesCache();
1428 return d->bibfilesCache_;
1432 bool Buffer::isDepClean(string const & name) const
1434 DepClean::const_iterator const it = d->dep_clean.find(name);
1435 if (it == d->dep_clean.end())
1441 void Buffer::markDepClean(string const & name)
1443 d->dep_clean[name] = true;
1447 bool Buffer::dispatch(string const & command, bool * result)
1449 return dispatch(lyxaction.lookupFunc(command), result);
1453 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1455 bool dispatched = true;
1457 switch (func.action) {
1458 case LFUN_BUFFER_EXPORT: {
1459 bool const tmp = doExport(to_utf8(func.argument()), false);
1472 void Buffer::changeLanguage(Language const * from, Language const * to)
1477 for_each(par_iterator_begin(),
1479 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1483 bool Buffer::isMultiLingual() const
1485 ParConstIterator end = par_iterator_end();
1486 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1487 if (it->isMultiLingual(params()))
1494 DocIterator Buffer::getParFromID(int const id) const
1497 // John says this is called with id == -1 from undo
1498 lyxerr << "getParFromID(), id: " << id << endl;
1499 return doc_iterator_end(inset());
1502 for (DocIterator it = doc_iterator_begin(inset()); !it.atEnd(); it.forwardPar())
1503 if (it.paragraph().id() == id)
1506 return doc_iterator_end(inset());
1510 bool Buffer::hasParWithID(int const id) const
1512 return !getParFromID(id).atEnd();
1516 ParIterator Buffer::par_iterator_begin()
1518 return ParIterator(doc_iterator_begin(inset()));
1522 ParIterator Buffer::par_iterator_end()
1524 return ParIterator(doc_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())
1740 // no children before
1744 // do we know something better (i.e. later) already?
1745 if (it->first < bestPos )
1748 // scope ends behind pos?
1749 if (pos < it->second.first) {
1750 // look for macro in external file
1751 d->macro_lock = true;
1752 MacroData const * data
1753 = it->second.second->getMacro(name, false);
1754 d->macro_lock = false;
1756 bestPos = it->first;
1762 // try previous file if there is one
1763 if (it == d->position_to_children.begin())
1768 // return the best macro we have found
1773 MacroData const * Buffer::getMacro(docstring const & name,
1774 DocIterator const & pos, bool global) const
1779 // query buffer macros
1780 MacroData const * data = getBufferMacro(name, pos);
1784 // If there is a master buffer, query that
1785 if (d->parent_buffer) {
1786 d->macro_lock = true;
1787 MacroData const * macro
1788 = d->parent_buffer->getMacro(name, *this, false);
1789 d->macro_lock = false;
1795 data = MacroTable::globalMacros().get(name);
1804 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
1806 // set scope end behind the last paragraph
1807 DocIterator scope = par_iterator_begin();
1808 scope.pit() = scope.lastpit() + 1;
1810 return getMacro(name, scope, global);
1814 MacroData const * Buffer::getMacro(docstring const & name, Buffer const & child, bool global) const
1816 // look where the child buffer is included first
1817 Impl::BufferPositionMap::iterator it
1818 = d->children_positions.find(&child);
1819 if (it == d->children_positions.end())
1822 // check for macros at the inclusion position
1823 return getMacro(name, it->second, global);
1827 void Buffer::updateEnvironmentMacros(DocIterator & it,
1829 DocIterator & scope) const
1831 Paragraph & par = it.paragraph();
1833 = par.params().depth();
1834 Length const & leftIndent
1835 = par.params().leftIndent();
1837 // look for macros in each paragraph
1838 while (it.pit() <= lastpit) {
1839 Paragraph & par = it.paragraph();
1842 if ((par.params().depth() > depth
1843 || par.params().leftIndent() != leftIndent)
1844 && par.layout()->isEnvironment()) {
1845 updateBlockMacros(it, scope);
1849 // iterate over the insets of the current paragraph
1850 InsetList const & insets = par.insetList();
1851 InsetList::const_iterator iit = insets.begin();
1852 InsetList::const_iterator end = insets.end();
1853 for (; iit != end; ++iit) {
1854 it.pos() = iit->pos;
1856 // is it a nested text inset?
1857 if (iit->inset->asInsetText()) {
1858 // Inset needs its own scope?
1859 InsetText const * itext
1860 = iit->inset->asInsetText();
1861 bool newScope = itext->isMacroScope();
1863 // scope which ends just behind the inset
1864 DocIterator insetScope = it;
1867 // collect macros in inset
1868 it.push_back(CursorSlice(*iit->inset));
1869 updateInsetMacros(it, newScope ? insetScope : scope);
1874 // is it an external file?
1875 if (iit->inset->lyxCode() == INCLUDE_CODE) {
1876 // get buffer of external file
1877 InsetCommand const & inset
1878 = static_cast<InsetCommand const &>(*iit->inset);
1879 InsetCommandParams const & ip = inset.params();
1880 d->macro_lock = true;
1881 Buffer * child = loadIfNeeded(*this, ip);
1882 d->macro_lock = false;
1886 // register its position, but only when it is
1887 // included first in the buffer
1888 if (d->children_positions.find(child)
1889 == d->children_positions.end())
1890 d->children_positions[child] = it;
1892 // register child with its scope
1893 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
1898 if (iit->inset->lyxCode() != MATHMACRO_CODE)
1902 MathMacroTemplate & macroTemplate
1903 = static_cast<MathMacroTemplate &>(*iit->inset);
1904 MacroContext mc(*this, it);
1905 macroTemplate.updateToContext(mc);
1908 bool valid = macroTemplate.validMacro();
1909 // FIXME: Should be fixNameAndCheckIfValid() in fact,
1910 // then the BufferView's cursor will be invalid in
1911 // some cases which leads to crashes.
1916 d->macros[macroTemplate.name()][it]
1917 = Impl::ScopeMacro(scope, MacroData(*this, it));
1927 void Buffer::updateBlockMacros(DocIterator & it, DocIterator & scope) const
1929 Paragraph & par = it.paragraph();
1931 // set scope for macros in this paragraph:
1932 // * either the "old" outer scope
1933 // * or the scope ending after the environment
1934 if (par.layout()->isEnvironment()) {
1935 // find end of environment block,
1936 DocIterator envEnd = it;
1937 pit_type n = it.lastpit() + 1;
1938 depth_type depth = par.params().depth();
1939 Length const & length = par.params().leftIndent();
1940 // looping through the paragraph, basically until
1941 // the layout changes or the depth gets smaller.
1942 // (the logic of output_latex.cpp's TeXEnvironment)
1945 if (envEnd.pit() == n)
1947 } while (par.layout() == envEnd.paragraph().layout()
1948 || depth < envEnd.paragraph().params().depth()
1949 || length != envEnd.paragraph().params().leftIndent());
1951 // collect macros from environment block
1952 updateEnvironmentMacros(it, envEnd.pit() - 1, envEnd);
1954 // collect macros from paragraph
1955 updateEnvironmentMacros(it, it.pit(), scope);
1960 void Buffer::updateInsetMacros(DocIterator & it, DocIterator & scope) const
1962 // look for macros in each paragraph
1963 pit_type n = it.lastpit() + 1;
1964 while (it.pit() < n)
1965 updateBlockMacros(it, scope);
1969 void Buffer::updateMacros() const
1974 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
1976 // start with empty table
1978 d->children_positions.clear();
1979 d->position_to_children.clear();
1981 // Iterate over buffer, starting with first paragraph
1982 // The scope must be bigger than any lookup DocIterator
1983 // later. For the global lookup, lastpit+1 is used, hence
1984 // we use lastpit+2 here.
1985 DocIterator it = par_iterator_begin();
1986 DocIterator outerScope = it;
1987 outerScope.pit() = outerScope.lastpit() + 2;
1988 updateInsetMacros(it, outerScope);
1992 void Buffer::updateMacroInstances() const
1994 LYXERR(Debug::MACROS, "updateMacroInstances for "
1995 << d->filename.onlyFileName());
1996 DocIterator it = doc_iterator_begin(inset());
1997 DocIterator end = doc_iterator_end(inset());
1998 for (; it != end; it.forwardPos()) {
1999 // look for MathData cells in InsetMathNest insets
2000 Inset * inset = it.nextInset();
2004 InsetMath * minset = inset->asInsetMath();
2008 // update macro in all cells of the InsetMathNest
2009 DocIterator::idx_type n = minset->nargs();
2010 MacroContext mc = MacroContext(*this, it);
2011 for (DocIterator::idx_type i = 0; i < n; ++i) {
2012 MathData & data = minset->cell(i);
2013 data.updateMacros(0, mc);
2019 void Buffer::listMacroNames(MacroNameSet & macros) const
2024 d->macro_lock = true;
2026 // loop over macro names
2027 Impl::NamePositionScopeMacroMap::iterator nameIt
2028 = d->macros.begin();
2029 Impl::NamePositionScopeMacroMap::iterator nameEnd
2031 for (; nameIt != nameEnd; ++nameIt)
2032 macros.insert(nameIt->first);
2034 // loop over children
2035 Impl::BufferPositionMap::iterator it
2036 = d->children_positions.begin();
2037 Impl::BufferPositionMap::iterator end
2038 = d->children_positions.end();
2039 for (; it != end; ++it)
2040 it->first->listMacroNames(macros);
2043 if (d->parent_buffer)
2044 d->parent_buffer->listMacroNames(macros);
2046 d->macro_lock = false;
2050 void Buffer::writeParentMacros(odocstream & os) const
2052 if (!d->parent_buffer)
2055 // collect macro names
2057 d->parent_buffer->listMacroNames(names);
2059 // resolve and output them
2060 MacroNameSet::iterator it = names.begin();
2061 MacroNameSet::iterator end = names.end();
2062 for (; it != end; ++it) {
2064 MacroData const * data =
2065 d->parent_buffer->getMacro(*it, *this, false);
2067 data->write(os, true);
2072 Buffer::References & Buffer::references(docstring const & label)
2074 if (d->parent_buffer)
2075 return const_cast<Buffer *>(masterBuffer())->references(label);
2077 RefCache::iterator it = d->ref_cache_.find(label);
2078 if (it != d->ref_cache_.end())
2079 return it->second.second;
2081 static InsetLabel const * dummy_il = 0;
2082 static References const dummy_refs;
2083 it = d->ref_cache_.insert(make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2084 return it->second.second;
2088 Buffer::References const & Buffer::references(docstring const & label) const
2090 return const_cast<Buffer *>(this)->references(label);
2094 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2096 masterBuffer()->d->ref_cache_[label].first = il;
2100 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2102 return masterBuffer()->d->ref_cache_[label].first;
2106 void Buffer::clearReferenceCache() const
2108 if (!d->parent_buffer)
2109 d->ref_cache_.clear();
2113 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2116 //FIXME: This does not work for child documents yet.
2117 BOOST_ASSERT(code == CITE_CODE || code == REF_CODE);
2118 // Check if the label 'from' appears more than once
2119 vector<docstring> labels;
2122 if (code == CITE_CODE) {
2124 keys.fillWithBibKeys(this);
2125 BiblioInfo::const_iterator bit = keys.begin();
2126 BiblioInfo::const_iterator bend = keys.end();
2128 for (; bit != bend; ++bit)
2130 labels.push_back(bit->first);
2133 getLabelList(labels);
2134 paramName = "reference";
2137 if (count(labels.begin(), labels.end(), from) > 1)
2140 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2141 if (it->lyxCode() == code) {
2142 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2143 docstring const oldValue = inset.getParam(paramName);
2144 if (oldValue == from)
2145 inset.setParam(paramName, to);
2151 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2152 pit_type par_end, bool full_source)
2154 OutputParams runparams(¶ms().encoding());
2155 runparams.nice = true;
2156 runparams.flavor = OutputParams::LATEX;
2157 runparams.linelen = lyxrc.plaintext_linelen;
2158 // No side effect of file copying and image conversion
2159 runparams.dryrun = true;
2163 os << "% " << _("Preview source code") << "\n\n";
2164 d->texrow.newline();
2165 d->texrow.newline();
2167 writeLaTeXSource(os, filePath(), runparams, true, true);
2169 writeDocBookSource(os, absFileName(), runparams, false);
2172 runparams.par_begin = par_begin;
2173 runparams.par_end = par_end;
2174 if (par_begin + 1 == par_end)
2176 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2180 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2181 convert<docstring>(par_begin),
2182 convert<docstring>(par_end - 1))
2184 d->texrow.newline();
2185 d->texrow.newline();
2186 // output paragraphs
2188 latexParagraphs(*this, text(), os, d->texrow, runparams);
2191 docbookParagraphs(paragraphs(), *this, os, runparams);
2197 ErrorList & Buffer::errorList(string const & type) const
2199 static ErrorList emptyErrorList;
2200 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2201 if (I == d->errorLists.end())
2202 return emptyErrorList;
2208 void Buffer::structureChanged() const
2211 gui_->structureChanged();
2215 void Buffer::errors(string const & err) const
2222 void Buffer::message(docstring const & msg) const
2229 void Buffer::setBusy(bool on) const
2236 void Buffer::setReadOnly(bool on) const
2239 d->wa_->setReadOnly(on);
2243 void Buffer::updateTitles() const
2246 d->wa_->updateTitles();
2250 void Buffer::resetAutosaveTimers() const
2253 gui_->resetAutosaveTimers();
2257 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2266 class AutoSaveBuffer : public ForkedProcess {
2269 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2270 : buffer_(buffer), fname_(fname) {}
2272 virtual boost::shared_ptr<ForkedProcess> clone() const
2274 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2279 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2280 from_utf8(fname_.absFilename())));
2281 return run(DontWait);
2285 virtual int generateChild();
2287 Buffer const & buffer_;
2292 int AutoSaveBuffer::generateChild()
2294 // tmp_ret will be located (usually) in /tmp
2295 // will that be a problem?
2296 // Note that this calls ForkedCalls::fork(), so it's
2297 // ok cross-platform.
2298 pid_t const pid = fork();
2299 // If you want to debug the autosave
2300 // you should set pid to -1, and comment out the fork.
2301 if (pid != 0 && pid != -1)
2304 // pid = -1 signifies that lyx was unable
2305 // to fork. But we will do the save
2307 bool failed = false;
2308 FileName const tmp_ret = FileName::tempName("lyxauto");
2309 if (!tmp_ret.empty()) {
2310 buffer_.writeFile(tmp_ret);
2311 // assume successful write of tmp_ret
2312 if (!tmp_ret.moveTo(fname_))
2318 // failed to write/rename tmp_ret so try writing direct
2319 if (!buffer_.writeFile(fname_)) {
2320 // It is dangerous to do this in the child,
2321 // but safe in the parent, so...
2322 if (pid == -1) // emit message signal.
2323 buffer_.message(_("Autosave failed!"));
2327 if (pid == 0) // we are the child so...
2336 // Perfect target for a thread...
2337 void Buffer::autoSave() const
2339 if (isBakClean() || isReadonly()) {
2340 // We don't save now, but we'll try again later
2341 resetAutosaveTimers();
2345 // emit message signal.
2346 message(_("Autosaving current document..."));
2348 // create autosave filename
2349 string fname = filePath();
2351 fname += d->filename.onlyFileName();
2354 AutoSaveBuffer autosave(*this, FileName(fname));
2358 resetAutosaveTimers();
2362 void Buffer::resetChildDocuments(bool close_them) const
2367 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2368 if (it->lyxCode() != INCLUDE_CODE)
2370 InsetCommand const & inset = static_cast<InsetCommand const &>(*it);
2371 InsetCommandParams const & ip = inset.params();
2373 resetParentBuffer(this, ip, close_them);
2376 // clear references to children in macro tables
2377 d->children_positions.clear();
2378 d->position_to_children.clear();
2382 void Buffer::loadChildDocuments() const
2384 bool parse_error = false;
2386 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2387 if (it->lyxCode() != INCLUDE_CODE)
2389 InsetCommand const & inset = static_cast<InsetCommand const &>(*it);
2390 InsetCommandParams const & ip = inset.params();
2391 Buffer * child = loadIfNeeded(*this, ip);
2394 parse_error |= !child->errorList("Parse").empty();
2395 child->loadChildDocuments();
2402 string Buffer::bufferFormat() const
2412 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2413 string & result_file) const
2415 string backend_format;
2416 OutputParams runparams(¶ms().encoding());
2417 runparams.flavor = OutputParams::LATEX;
2418 runparams.linelen = lyxrc.plaintext_linelen;
2419 vector<string> backs = backends();
2420 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2421 // Get shortest path to format
2422 Graph::EdgePath path;
2423 for (vector<string>::const_iterator it = backs.begin();
2424 it != backs.end(); ++it) {
2425 Graph::EdgePath p = theConverters().getPath(*it, format);
2426 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2427 backend_format = *it;
2432 runparams.flavor = theConverters().getFlavor(path);
2434 Alert::error(_("Couldn't export file"),
2435 bformat(_("No information for exporting the format %1$s."),
2436 formats.prettyName(format)));
2440 backend_format = format;
2441 // FIXME: Don't hardcode format names here, but use a flag
2442 if (backend_format == "pdflatex")
2443 runparams.flavor = OutputParams::PDFLATEX;
2446 string filename = latexName(false);
2447 filename = addName(temppath(), filename);
2448 filename = changeExtension(filename,
2449 formats.extension(backend_format));
2452 updateMacroInstances();
2454 // Plain text backend
2455 if (backend_format == "text")
2456 writePlaintextFile(*this, FileName(filename), runparams);
2458 else if (backend_format == "lyx")
2459 writeFile(FileName(filename));
2461 else if (isDocBook()) {
2462 runparams.nice = !put_in_tempdir;
2463 makeDocBookFile(FileName(filename), runparams);
2466 else if (backend_format == format) {
2467 runparams.nice = true;
2468 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2470 } else if (!lyxrc.tex_allows_spaces
2471 && contains(filePath(), ' ')) {
2472 Alert::error(_("File name error"),
2473 _("The directory path to the document cannot contain spaces."));
2476 runparams.nice = false;
2477 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2481 string const error_type = (format == "program")
2482 ? "Build" : bufferFormat();
2483 string const ext = formats.extension(format);
2484 FileName const tmp_result_file(changeExtension(filename, ext));
2485 bool const success = theConverters().convert(this, FileName(filename),
2486 tmp_result_file, FileName(absFileName()), backend_format, format,
2487 errorList(error_type));
2488 // Emit the signal to show the error list.
2489 if (format != backend_format)
2494 if (put_in_tempdir) {
2495 result_file = tmp_result_file.absFilename();
2499 result_file = changeExtension(absFileName(), ext);
2500 // We need to copy referenced files (e. g. included graphics
2501 // if format == "dvi") to the result dir.
2502 vector<ExportedFile> const files =
2503 runparams.exportdata->externalFiles(format);
2504 string const dest = onlyPath(result_file);
2505 CopyStatus status = SUCCESS;
2506 for (vector<ExportedFile>::const_iterator it = files.begin();
2507 it != files.end() && status != CANCEL; ++it) {
2508 string const fmt = formats.getFormatFromFile(it->sourceName);
2509 status = copyFile(fmt, it->sourceName,
2510 makeAbsPath(it->exportName, dest),
2511 it->exportName, status == FORCE);
2513 if (status == CANCEL) {
2514 message(_("Document export cancelled."));
2515 } else if (tmp_result_file.exists()) {
2516 // Finally copy the main file
2517 status = copyFile(format, tmp_result_file,
2518 FileName(result_file), result_file,
2520 message(bformat(_("Document exported as %1$s "
2522 formats.prettyName(format),
2523 makeDisplayPath(result_file)));
2525 // This must be a dummy converter like fax (bug 1888)
2526 message(bformat(_("Document exported as %1$s"),
2527 formats.prettyName(format)));
2534 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2537 return doExport(format, put_in_tempdir, result_file);
2541 bool Buffer::preview(string const & format) const
2544 if (!doExport(format, true, result_file))
2546 return formats.view(*this, FileName(result_file), format);
2550 bool Buffer::isExportable(string const & format) const
2552 vector<string> backs = backends();
2553 for (vector<string>::const_iterator it = backs.begin();
2554 it != backs.end(); ++it)
2555 if (theConverters().isReachable(*it, format))
2561 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2563 vector<string> backs = backends();
2564 vector<Format const *> result =
2565 theConverters().getReachable(backs[0], only_viewable, true);
2566 for (vector<string>::const_iterator it = backs.begin() + 1;
2567 it != backs.end(); ++it) {
2568 vector<Format const *> r =
2569 theConverters().getReachable(*it, only_viewable, false);
2570 result.insert(result.end(), r.begin(), r.end());
2576 vector<string> Buffer::backends() const
2579 if (params().baseClass()->isTeXClassAvailable()) {
2580 v.push_back(bufferFormat());
2581 // FIXME: Don't hardcode format names here, but use a flag
2582 if (v.back() == "latex")
2583 v.push_back("pdflatex");
2585 v.push_back("text");
2591 bool Buffer::readFileHelper(FileName const & s)
2593 // File information about normal file
2595 docstring const file = makeDisplayPath(s.absFilename(), 50);
2596 docstring text = bformat(_("The specified document\n%1$s"
2597 "\ncould not be read."), file);
2598 Alert::error(_("Could not read document"), text);
2602 // Check if emergency save file exists and is newer.
2603 FileName const e(s.absFilename() + ".emergency");
2605 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2606 docstring const file = makeDisplayPath(s.absFilename(), 20);
2607 docstring const text =
2608 bformat(_("An emergency save of the document "
2610 "Recover emergency save?"), file);
2611 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2612 _("&Recover"), _("&Load Original"),
2616 // the file is not saved if we load the emergency file.
2626 // Now check if autosave file is newer.
2627 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2629 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2630 docstring const file = makeDisplayPath(s.absFilename(), 20);
2631 docstring const text =
2632 bformat(_("The backup of the document "
2633 "%1$s is newer.\n\nLoad the "
2634 "backup instead?"), file);
2635 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2636 _("&Load backup"), _("Load &original"),
2640 // the file is not saved if we load the autosave file.
2644 // Here we delete the autosave
2655 bool Buffer::loadLyXFile(FileName const & s)
2657 if (s.isReadableFile()) {
2658 if (readFileHelper(s)) {
2659 lyxvc().file_found_hook(s);
2660 if (!s.isWritable())
2665 docstring const file = makeDisplayPath(s.absFilename(), 20);
2666 // Here we probably should run
2667 if (LyXVC::file_not_found_hook(s)) {
2668 docstring const text =
2669 bformat(_("Do you want to retrieve the document"
2670 " %1$s from version control?"), file);
2671 int const ret = Alert::prompt(_("Retrieve from version control?"),
2672 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2675 // How can we know _how_ to do the checkout?
2676 // With the current VC support it has to be,
2677 // a RCS file since CVS do not have special ,v files.
2679 return loadLyXFile(s);
2687 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2689 TeXErrors::Errors::const_iterator cit = terr.begin();
2690 TeXErrors::Errors::const_iterator end = terr.end();
2692 for (; cit != end; ++cit) {
2695 int errorRow = cit->error_in_line;
2696 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2702 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2703 } while (found && id_start == id_end && pos_start == pos_end);
2705 errorList.push_back(ErrorItem(cit->error_desc,
2706 cit->error_text, id_start, pos_start, pos_end));