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/FileName.h"
83 #include "support/FileNameList.h"
84 #include "support/filetools.h"
85 #include "support/ForkedCalls.h"
86 #include "support/gettext.h"
87 #include "support/gzstream.h"
88 #include "support/lstrings.h"
89 #include "support/lyxalgo.h"
90 #include "support/os.h"
91 #include "support/Package.h"
92 #include "support/Path.h"
93 #include "support/textutils.h"
94 #include "support/types.h"
95 #include "support/FileZipListDir.h"
97 #include <boost/bind.hpp>
98 #include <boost/shared_ptr.hpp>
107 using namespace lyx::support;
111 namespace Alert = frontend::Alert;
112 namespace os = support::os;
116 int const LYX_FORMAT = 314; // Uwe Stöhr: scrlttr2 for serial letters
121 typedef map<string, bool> DepClean;
126 Impl(Buffer & parent, FileName const & file, bool readonly);
139 mutable TexRow texrow;
140 Buffer const * parent_buffer;
142 /// need to regenerate .tex?
146 mutable bool lyx_clean;
148 /// is autosave needed?
149 mutable bool bak_clean;
151 /// is this a unnamed file (New...)?
157 /// name of the file the buffer is associated with.
160 /** Set to true only when the file is fully loaded.
161 * Used to prevent the premature generation of previews
162 * and by the citation inset.
164 bool file_fully_loaded;
166 /// our Text that should be wrapped in an InsetText
170 mutable TocBackend toc_backend;
173 typedef pair<DocIterator, MacroData> ScopeMacro;
174 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
175 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
176 NamePositionScopeMacroMap macros;
179 /// positions of child buffers in the buffer
180 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
181 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
182 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
183 BufferPositionMap children_positions;
184 PositionScopeBufferMap position_to_children;
186 /// Container for all sort of Buffer dependant errors.
187 map<string, ErrorList> errorLists;
189 /// all embedded files of this buffer
190 EmbeddedFileList embedded_files;
192 /// timestamp and checksum used to test if the file has been externally
193 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
195 unsigned long checksum_;
198 frontend::WorkAreaManager * wa_;
203 /// A cache for the bibfiles (including bibfiles of loaded child
204 /// documents), needed for appropriate update of natbib labels.
205 mutable EmbeddedFileList bibfilesCache_;
208 /// Creates the per buffer temporary directory
209 static FileName createBufferTmpDir()
212 // We are in our own directory. Why bother to mangle name?
213 // In fact I wrote this code to circumvent a problematic behaviour
214 // (bug?) of EMX mkstemp().
215 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
216 convert<string>(count++));
218 if (!tmpfl.createDirectory(0777)) {
219 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
220 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
221 from_utf8(tmpfl.absFilename())));
227 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
228 : parent_buffer(0), lyx_clean(true), bak_clean(true), unnamed(false),
229 read_only(readonly_), filename(file), file_fully_loaded(false),
230 inset(params), toc_backend(&parent), macro_lock(false),
231 embedded_files(), timestamp_(0), checksum_(0), wa_(0),
234 temppath = createBufferTmpDir();
235 inset.setAutoBreakRows(true);
236 lyxvc.setBuffer(&parent);
238 wa_ = new frontend::WorkAreaManager;
242 Buffer::Buffer(string const & file, bool readonly)
243 : d(new Impl(*this, FileName(file), readonly)), gui_(0)
245 LYXERR(Debug::INFO, "Buffer::Buffer()");
247 d->inset.getText(0)->setMacrocontextPosition(par_iterator_begin());
253 LYXERR(Debug::INFO, "Buffer::~Buffer()");
254 // here the buffer should take care that it is
255 // saved properly, before it goes into the void.
257 // GuiView already destroyed
260 Buffer const * master = masterBuffer();
261 if (master != this && use_gui) {
262 // We are closing buf which was a child document so we
263 // must update the labels and section numbering of its master
265 updateLabels(*master);
266 master->updateMacros();
269 resetChildDocuments(false);
271 if (!d->temppath.destroyDirectory()) {
272 Alert::warning(_("Could not remove temporary directory"),
273 bformat(_("Could not remove the temporary directory %1$s"),
274 from_utf8(d->temppath.absFilename())));
277 // Remove any previewed LaTeX snippets associated with this buffer.
278 graphics::Previews::get().removeLoader(*this);
284 void Buffer::changed() const
291 frontend::WorkAreaManager & Buffer::workAreaManager() const
293 BOOST_ASSERT(d->wa_);
298 Text & Buffer::text() const
300 return const_cast<Text &>(d->inset.text_);
304 Inset & Buffer::inset() const
306 return const_cast<InsetText &>(d->inset);
310 BufferParams & Buffer::params()
316 BufferParams const & Buffer::params() const
322 ParagraphList & Buffer::paragraphs()
324 return text().paragraphs();
328 ParagraphList const & Buffer::paragraphs() const
330 return text().paragraphs();
334 LyXVC & Buffer::lyxvc()
340 LyXVC const & Buffer::lyxvc() const
346 string const Buffer::temppath() const
348 return d->temppath.absFilename();
352 TexRow const & Buffer::texrow() const
358 TocBackend & Buffer::tocBackend() const
360 return d->toc_backend;
364 EmbeddedFileList & Buffer::embeddedFiles()
366 return d->embedded_files;
370 EmbeddedFileList const & Buffer::embeddedFiles() const
372 return d->embedded_files;
376 bool Buffer::embedded() const
378 return params().embedded;
382 Undo & Buffer::undo()
388 string Buffer::latexName(bool const no_path) const
390 FileName latex_name = makeLatexName(d->filename);
391 return no_path ? latex_name.onlyFileName()
392 : latex_name.absFilename();
396 string Buffer::logName(LogType * type) const
398 string const filename = latexName(false);
400 if (filename.empty()) {
406 string const path = temppath();
408 FileName const fname(addName(temppath(),
409 onlyFilename(changeExtension(filename,
411 FileName const bname(
412 addName(path, onlyFilename(
413 changeExtension(filename,
414 formats.extension("literate") + ".out"))));
416 // If no Latex log or Build log is newer, show Build log
418 if (bname.exists() &&
419 (!fname.exists() || fname.lastModified() < bname.lastModified())) {
420 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
423 return bname.absFilename();
425 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
428 return fname.absFilename();
432 void Buffer::setReadonly(bool const flag)
434 if (d->read_only != flag) {
441 void Buffer::setFileName(string const & newfile)
443 d->filename = makeAbsPath(newfile);
444 setReadonly(d->filename.isReadOnly());
449 int Buffer::readHeader(Lexer & lex)
451 int unknown_tokens = 0;
453 int begin_header_line = -1;
455 // Initialize parameters that may be/go lacking in header:
456 params().branchlist().clear();
457 params().preamble.erase();
458 params().options.erase();
459 params().float_placement.erase();
460 params().paperwidth.erase();
461 params().paperheight.erase();
462 params().leftmargin.erase();
463 params().rightmargin.erase();
464 params().topmargin.erase();
465 params().bottommargin.erase();
466 params().headheight.erase();
467 params().headsep.erase();
468 params().footskip.erase();
469 params().listings_params.clear();
470 params().clearLayoutModules();
471 params().pdfoptions().clear();
473 for (int i = 0; i < 4; ++i) {
474 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
475 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
478 ErrorList & errorList = d->errorLists["Parse"];
482 string const token = lex.getString();
487 if (token == "\\end_header")
491 if (token == "\\begin_header") {
492 begin_header_line = line;
496 LYXERR(Debug::PARSER, "Handling document header token: `"
499 string unknown = params().readToken(lex, token, d->filename.onlyPath());
500 if (!unknown.empty()) {
501 if (unknown[0] != '\\' && token == "\\textclass") {
502 Alert::warning(_("Unknown document class"),
503 bformat(_("Using the default document class, because the "
504 "class %1$s is unknown."), from_utf8(unknown)));
507 docstring const s = bformat(_("Unknown token: "
511 errorList.push_back(ErrorItem(_("Document header error"),
516 if (begin_header_line) {
517 docstring const s = _("\\begin_header is missing");
518 errorList.push_back(ErrorItem(_("Document header error"),
522 params().makeTextClass();
524 return unknown_tokens;
529 // changed to be public and have one parameter
530 // Returns false if "\end_document" is not read (Asger)
531 bool Buffer::readDocument(Lexer & lex)
533 ErrorList & errorList = d->errorLists["Parse"];
537 string const token = lex.getString();
538 if (token != "\\begin_document") {
539 docstring const s = _("\\begin_document is missing");
540 errorList.push_back(ErrorItem(_("Document header error"),
544 // we are reading in a brand new document
545 BOOST_ASSERT(paragraphs().empty());
549 if (params().outputChanges) {
550 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
551 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
552 LaTeXFeatures::isAvailable("xcolor");
554 if (!dvipost && !xcolorsoul) {
555 Alert::warning(_("Changes not shown in LaTeX output"),
556 _("Changes will not be highlighted in LaTeX output, "
557 "because neither dvipost nor xcolor/soul are installed.\n"
558 "Please install these packages or redefine "
559 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
560 } else if (!xcolorsoul) {
561 Alert::warning(_("Changes not shown in LaTeX output"),
562 _("Changes will not be highlighted in LaTeX output "
563 "when using pdflatex, because xcolor and soul are not installed.\n"
564 "Please install both packages or redefine "
565 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
570 bool const res = text().read(*this, lex, errorList);
571 for_each(text().paragraphs().begin(),
572 text().paragraphs().end(),
573 bind(&Paragraph::setInsetOwner, _1, &inset()));
576 updateMacroInstances();
581 // needed to insert the selection
582 void Buffer::insertStringAsLines(ParagraphList & pars,
583 pit_type & pit, pos_type & pos,
584 Font const & fn, docstring const & str, bool autobreakrows)
588 // insert the string, don't insert doublespace
589 bool space_inserted = true;
590 for (docstring::const_iterator cit = str.begin();
591 cit != str.end(); ++cit) {
592 Paragraph & par = pars[pit];
594 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
595 breakParagraph(params(), pars, pit, pos,
596 par.layout()->isEnvironment());
599 space_inserted = true;
603 // do not insert consecutive spaces if !free_spacing
604 } else if ((*cit == ' ' || *cit == '\t') &&
605 space_inserted && !par.isFreeSpacing()) {
607 } else if (*cit == '\t') {
608 if (!par.isFreeSpacing()) {
609 // tabs are like spaces here
610 par.insertChar(pos, ' ', font, params().trackChanges);
612 space_inserted = true;
614 const pos_type n = 8 - pos % 8;
615 for (pos_type i = 0; i < n; ++i) {
616 par.insertChar(pos, ' ', font, params().trackChanges);
619 space_inserted = true;
621 } else if (!isPrintable(*cit)) {
622 // Ignore unprintables
625 // just insert the character
626 par.insertChar(pos, *cit, font, params().trackChanges);
628 space_inserted = (*cit == ' ');
635 bool Buffer::readString(string const & s)
637 params().compressed = false;
639 // remove dummy empty par
640 paragraphs().clear();
644 FileName const name = FileName::tempName();
645 switch (readFile(lex, name, true)) {
649 // We need to call lyx2lyx, so write the input to a file
650 ofstream os(name.toFilesystemEncoding().c_str());
653 return readFile(name);
663 bool Buffer::readFile(FileName const & filename)
665 FileName fname(filename);
666 // Check if the file is compressed.
667 string format = filename.guessFormatFromContents();
668 if (format == "zip") {
669 // decompress to a temp directory
670 LYXERR(Debug::FILES, filename << " is in zip format. Unzip to " << temppath());
671 ::unzipToDir(filename.toFilesystemEncoding(), temppath());
673 FileName lyxfile(addName(temppath(), "content.lyx"));
674 // if both manifest.txt and file.lyx exist, this is am embedded file
675 if (lyxfile.exists()) {
676 // if in bundled format, save checksum of the compressed file, not content.lyx
677 saveCheckSum(filename);
678 params().embedded = true;
682 // The embedded lyx file can also be compressed, for backward compatibility
683 format = fname.guessFormatFromContents();
684 if (format == "gzip" || format == "zip" || format == "compress")
685 params().compressed = true;
687 // remove dummy empty par
688 paragraphs().clear();
691 if (readFile(lex, fname) != success)
698 bool Buffer::isFullyLoaded() const
700 return d->file_fully_loaded;
704 void Buffer::setFullyLoaded(bool value)
706 d->file_fully_loaded = value;
710 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
713 BOOST_ASSERT(!filename.empty());
716 Alert::error(_("Document could not be read"),
717 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
722 string const token = lex.getString();
725 Alert::error(_("Document could not be read"),
726 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
730 // the first token _must_ be...
731 if (token != "\\lyxformat") {
732 lyxerr << "Token: " << token << endl;
734 Alert::error(_("Document format failure"),
735 bformat(_("%1$s is not a LyX document."),
736 from_utf8(filename.absFilename())));
741 string tmp_format = lex.getString();
742 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
743 // if present remove ".," from string.
744 string::size_type dot = tmp_format.find_first_of(".,");
745 //lyxerr << " dot found at " << dot << endl;
746 if (dot != string::npos)
747 tmp_format.erase(dot, 1);
748 int const file_format = convert<int>(tmp_format);
749 //lyxerr << "format: " << file_format << endl;
751 // save timestamp and checksum of the original disk file, making sure
752 // to not overwrite them with those of the file created in the tempdir
753 // when it has to be converted to the current format.
755 // Save the timestamp and checksum of disk file. If filename is an
756 // emergency file, save the timestamp and checksum of the original lyx file
757 // because isExternallyModified will check for this file. (BUG4193)
758 string diskfile = filename.absFilename();
759 if (suffixIs(diskfile, ".emergency"))
760 diskfile = diskfile.substr(0, diskfile.size() - 10);
761 saveCheckSum(FileName(diskfile));
764 if (file_format != LYX_FORMAT) {
767 // lyx2lyx would fail
770 FileName const tmpfile = FileName::tempName();
771 if (tmpfile.empty()) {
772 Alert::error(_("Conversion failed"),
773 bformat(_("%1$s is from a different"
774 " version of LyX, but a temporary"
775 " file for converting it could"
777 from_utf8(filename.absFilename())));
780 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
781 if (lyx2lyx.empty()) {
782 Alert::error(_("Conversion script not found"),
783 bformat(_("%1$s is from a different"
784 " version of LyX, but the"
785 " conversion script lyx2lyx"
786 " could not be found."),
787 from_utf8(filename.absFilename())));
790 ostringstream command;
791 command << os::python()
792 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
793 << " -t " << convert<string>(LYX_FORMAT)
794 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
795 << ' ' << quoteName(filename.toFilesystemEncoding());
796 string const command_str = command.str();
798 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
800 cmd_ret const ret = runCommand(command_str);
801 if (ret.first != 0) {
802 Alert::error(_("Conversion script failed"),
803 bformat(_("%1$s is from a different version"
804 " of LyX, but the lyx2lyx script"
805 " failed to convert it."),
806 from_utf8(filename.absFilename())));
809 bool const ret = readFile(tmpfile);
810 // Do stuff with tmpfile name and buffer name here.
811 return ret ? success : failure;
816 if (readDocument(lex)) {
817 Alert::error(_("Document format failure"),
818 bformat(_("%1$s ended unexpectedly, which means"
819 " that it is probably corrupted."),
820 from_utf8(filename.absFilename())));
823 d->file_fully_loaded = true;
828 // Should probably be moved to somewhere else: BufferView? LyXView?
829 bool Buffer::save() const
831 // We don't need autosaves in the immediate future. (Asger)
832 resetAutosaveTimers();
834 string const encodedFilename = d->filename.toFilesystemEncoding();
837 bool madeBackup = false;
839 // make a backup if the file already exists
840 if (lyxrc.make_backup && fileName().exists()) {
841 backupName = FileName(absFileName() + '~');
842 if (!lyxrc.backupdir_path.empty()) {
843 string const mangledName =
844 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
845 backupName = FileName(addName(lyxrc.backupdir_path,
848 if (fileName().copyTo(backupName)) {
851 Alert::error(_("Backup failure"),
852 bformat(_("Cannot create backup file %1$s.\n"
853 "Please check whether the directory exists and is writeable."),
854 from_utf8(backupName.absFilename())));
855 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
859 // ask if the disk file has been externally modified (use checksum method)
860 if (fileName().exists() && isExternallyModified(checksum_method)) {
861 docstring const file = makeDisplayPath(absFileName(), 20);
862 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
863 "you want to overwrite this file?"), file);
864 int const ret = Alert::prompt(_("Overwrite modified file?"),
865 text, 1, 1, _("&Overwrite"), _("&Cancel"));
870 if (writeFile(d->filename)) {
874 // Saving failed, so backup is not backup
876 backupName.moveTo(d->filename);
882 bool Buffer::writeFile(FileName const & fname) const
884 if (d->read_only && fname == d->filename)
890 if (params().embedded)
891 // first write the .lyx file to the temporary directory
892 content = FileName(addName(temppath(), "content.lyx"));
896 docstring const str = bformat(_("Saving document %1$s..."),
897 makeDisplayPath(content.absFilename()));
900 if (params().compressed) {
901 gz::ogzstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
902 retval = ofs && write(ofs);
904 ofstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
905 retval = ofs && write(ofs);
909 message(str + _(" could not write file!."));
913 removeAutosaveFile(d->filename.absFilename());
915 if (params().embedded) {
916 message(str + _(" writing embedded files!."));
917 // if embedding is enabled, write file.lyx and all the embedded files
918 // to the zip file fname.
919 if (!d->embedded_files.writeFile(fname, *this)) {
920 message(str + _(" could not write embedded files!."));
924 saveCheckSum(d->filename);
925 message(str + _(" done."));
931 bool Buffer::write(ostream & ofs) const
934 // Use the standard "C" locale for file output.
935 ofs.imbue(locale::classic());
938 // The top of the file should not be written by params().
940 // write out a comment in the top of the file
941 ofs << "#LyX " << lyx_version
942 << " created this file. For more info see http://www.lyx.org/\n"
943 << "\\lyxformat " << LYX_FORMAT << "\n"
944 << "\\begin_document\n";
946 /// For each author, set 'used' to true if there is a change
947 /// by this author in the document; otherwise set it to 'false'.
948 AuthorList::Authors::const_iterator a_it = params().authors().begin();
949 AuthorList::Authors::const_iterator a_end = params().authors().end();
950 for (; a_it != a_end; ++a_it)
951 a_it->second.setUsed(false);
953 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
954 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
955 for ( ; it != end; ++it)
956 it->checkAuthors(params().authors());
958 // now write out the buffer parameters.
959 ofs << "\\begin_header\n";
960 params().writeFile(ofs);
961 ofs << "\\end_header\n";
964 ofs << "\n\\begin_body\n";
965 text().write(*this, ofs);
966 ofs << "\n\\end_body\n";
968 // Write marker that shows file is complete
969 ofs << "\\end_document" << endl;
971 // Shouldn't really be needed....
974 // how to check if close went ok?
975 // Following is an attempt... (BE 20001011)
977 // good() returns false if any error occured, including some
979 // bad() returns true if something bad happened in the buffer,
980 // which should include file system full errors.
985 lyxerr << "File was not closed properly." << endl;
992 bool Buffer::makeLaTeXFile(FileName const & fname,
993 string const & original_path,
994 OutputParams const & runparams,
995 bool output_preamble, bool output_body) const
997 string const encoding = runparams.encoding->iconvName();
998 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1001 try { ofs.reset(encoding); }
1002 catch (iconv_codecvt_facet_exception & e) {
1003 lyxerr << "Caught iconv exception: " << e.what() << endl;
1004 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1005 "verify that the support software for your encoding (%1$s) is "
1006 "properly installed"), from_ascii(encoding)));
1009 if (!openFileWrite(ofs, fname))
1012 //TexStream ts(ofs.rdbuf(), &texrow());
1013 ErrorList & errorList = d->errorLists["Export"];
1015 bool failed_export = false;
1018 writeLaTeXSource(ofs, original_path,
1019 runparams, output_preamble, output_body);
1021 catch (EncodingException & e) {
1022 odocstringstream ods;
1023 ods.put(e.failed_char);
1025 oss << "0x" << hex << e.failed_char << dec;
1026 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1027 " (code point %2$s)"),
1028 ods.str(), from_utf8(oss.str()));
1029 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1030 "representable in the chosen encoding.\n"
1031 "Changing the document encoding to utf8 could help."),
1032 e.par_id, e.pos, e.pos + 1));
1033 failed_export = true;
1035 catch (iconv_codecvt_facet_exception & e) {
1036 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1037 _(e.what()), -1, 0, 0));
1038 failed_export = true;
1040 catch (exception const & e) {
1041 errorList.push_back(ErrorItem(_("conversion failed"),
1042 _(e.what()), -1, 0, 0));
1043 failed_export = true;
1046 lyxerr << "Caught some really weird exception..." << endl;
1047 LyX::cref().exit(1);
1052 failed_export = true;
1053 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1057 return !failed_export;
1061 void Buffer::writeLaTeXSource(odocstream & os,
1062 string const & original_path,
1063 OutputParams const & runparams_in,
1064 bool const output_preamble, bool const output_body) const
1066 OutputParams runparams = runparams_in;
1068 // validate the buffer.
1069 LYXERR(Debug::LATEX, " Validating buffer...");
1070 LaTeXFeatures features(*this, params(), runparams);
1072 LYXERR(Debug::LATEX, " Buffer validation done.");
1074 // The starting paragraph of the coming rows is the
1075 // first paragraph of the document. (Asger)
1076 if (output_preamble && runparams.nice) {
1077 os << "%% LyX " << lyx_version << " created this file. "
1078 "For more info, see http://www.lyx.org/.\n"
1079 "%% Do not edit unless you really know what "
1081 d->texrow.newline();
1082 d->texrow.newline();
1084 LYXERR(Debug::INFO, "lyx document header finished");
1085 // There are a few differences between nice LaTeX and usual files:
1086 // usual is \batchmode and has a
1087 // special input@path to allow the including of figures
1088 // with either \input or \includegraphics (what figinsets do).
1089 // input@path is set when the actual parameter
1090 // original_path is set. This is done for usual tex-file, but not
1091 // for nice-latex-file. (Matthias 250696)
1092 // Note that input@path is only needed for something the user does
1093 // in the preamble, included .tex files or ERT, files included by
1094 // LyX work without it.
1095 if (output_preamble) {
1096 if (!runparams.nice) {
1097 // code for usual, NOT nice-latex-file
1098 os << "\\batchmode\n"; // changed
1099 // from \nonstopmode
1100 d->texrow.newline();
1102 if (!original_path.empty()) {
1104 // We don't know the encoding of inputpath
1105 docstring const inputpath = from_utf8(latex_path(original_path));
1106 os << "\\makeatletter\n"
1107 << "\\def\\input@path{{"
1108 << inputpath << "/}}\n"
1109 << "\\makeatother\n";
1110 d->texrow.newline();
1111 d->texrow.newline();
1112 d->texrow.newline();
1115 // Write the preamble
1116 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1122 os << "\\begin{document}\n";
1123 d->texrow.newline();
1124 } // output_preamble
1126 d->texrow.start(paragraphs().begin()->id(), 0);
1128 LYXERR(Debug::INFO, "preamble finished, now the body.");
1130 // load children, if not already done.
1131 // This includes an updateMacro() call.
1132 // Don't move this behind the parent_buffer=0 code below,
1133 // because then the macros will not get the right "redefinition"
1134 // flag as they don't see the parent macros which are output before.
1135 loadChildDocuments();
1137 // fold macros if possible, still with parent buffer as the
1138 // 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;
1154 latexParagraphs(*this, text(), os, d->texrow, runparams);
1156 // Restore the parenthood if needed
1157 if (output_preamble) {
1158 d->parent_buffer = save_parent;
1160 // restore macros with correct parent buffer (especially
1161 // important for the redefinition flag which depends on the
1166 // add this just in case after all the paragraphs
1168 d->texrow.newline();
1170 if (output_preamble) {
1171 os << "\\end{document}\n";
1172 d->texrow.newline();
1173 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1175 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1177 runparams_in.encoding = runparams.encoding;
1179 // Just to be sure. (Asger)
1180 d->texrow.newline();
1182 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1183 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1187 bool Buffer::isLatex() const
1189 return params().getTextClass().outputType() == LATEX;
1193 bool Buffer::isLiterate() const
1195 return params().getTextClass().outputType() == LITERATE;
1199 bool Buffer::isDocBook() const
1201 return params().getTextClass().outputType() == DOCBOOK;
1205 void Buffer::makeDocBookFile(FileName const & fname,
1206 OutputParams const & runparams,
1207 bool const body_only) const
1209 LYXERR(Debug::LATEX, "makeDocBookFile...");
1212 if (!openFileWrite(ofs, fname))
1215 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1219 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1223 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1224 OutputParams const & runparams,
1225 bool const only_body) const
1227 LaTeXFeatures features(*this, params(), runparams);
1232 TextClass const & tclass = params().getTextClass();
1233 string const top_element = tclass.latexname();
1236 if (runparams.flavor == OutputParams::XML)
1237 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1240 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1243 if (! tclass.class_header().empty())
1244 os << from_ascii(tclass.class_header());
1245 else if (runparams.flavor == OutputParams::XML)
1246 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1247 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1249 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1251 docstring preamble = from_utf8(params().preamble);
1252 if (runparams.flavor != OutputParams::XML ) {
1253 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1254 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1255 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1256 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1259 string const name = runparams.nice
1260 ? changeExtension(absFileName(), ".sgml") : fname;
1261 preamble += features.getIncludedFiles(name);
1262 preamble += features.getLyXSGMLEntities();
1264 if (!preamble.empty()) {
1265 os << "\n [ " << preamble << " ]";
1270 string top = top_element;
1272 if (runparams.flavor == OutputParams::XML)
1273 top += params().language->code();
1275 top += params().language->code().substr(0,2);
1278 if (!params().options.empty()) {
1280 top += params().options;
1283 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1284 << " file was created by LyX " << lyx_version
1285 << "\n See http://www.lyx.org/ for more information -->\n";
1287 params().getTextClass().counters().reset();
1289 loadChildDocuments();
1291 sgml::openTag(os, top);
1293 docbookParagraphs(paragraphs(), *this, os, runparams);
1294 sgml::closeTag(os, top_element);
1298 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1299 // Other flags: -wall -v0 -x
1300 int Buffer::runChktex()
1304 // get LaTeX-Filename
1305 FileName const path(temppath());
1306 string const name = addName(path.absFilename(), latexName());
1307 string const org_path = filePath();
1309 PathChanger p(path); // path to LaTeX file
1310 message(_("Running chktex..."));
1312 // Generate the LaTeX file if neccessary
1313 OutputParams runparams(¶ms().encoding());
1314 runparams.flavor = OutputParams::LATEX;
1315 runparams.nice = false;
1316 makeLaTeXFile(FileName(name), org_path, runparams);
1319 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1320 int const res = chktex.run(terr); // run chktex
1323 Alert::error(_("chktex failure"),
1324 _("Could not run chktex successfully."));
1325 } else if (res > 0) {
1326 ErrorList & errlist = d->errorLists["ChkTeX"];
1328 bufferErrors(terr, errlist);
1339 void Buffer::validate(LaTeXFeatures & features) const
1341 params().validate(features);
1343 loadChildDocuments();
1345 for_each(paragraphs().begin(), paragraphs().end(),
1346 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1348 if (lyxerr.debugging(Debug::LATEX)) {
1349 features.showStruct();
1354 void Buffer::getLabelList(vector<docstring> & list) const
1356 /// if this is a child document and the parent is already loaded
1357 /// Use the parent's list instead [ale990407]
1358 Buffer const * tmp = masterBuffer();
1360 lyxerr << "masterBuffer() failed!" << endl;
1364 tmp->getLabelList(list);
1368 loadChildDocuments();
1370 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1371 it.nextInset()->getLabelList(*this, list);
1375 void Buffer::updateBibfilesCache() const
1377 // if this is a child document and the parent is already loaded
1378 // update the parent's cache instead
1379 Buffer const * tmp = masterBuffer();
1382 tmp->updateBibfilesCache();
1386 d->bibfilesCache_.clear();
1387 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1388 if (it->lyxCode() == BIBTEX_CODE) {
1389 InsetBibtex const & inset =
1390 static_cast<InsetBibtex const &>(*it);
1391 EmbeddedFileList const bibfiles = inset.getFiles(*this);
1392 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1395 } else if (it->lyxCode() == INCLUDE_CODE) {
1396 InsetInclude & inset =
1397 static_cast<InsetInclude &>(*it);
1398 inset.updateBibfilesCache(*this);
1399 EmbeddedFileList const & bibfiles =
1400 inset.getBibfilesCache(*this);
1401 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1409 EmbeddedFileList const & Buffer::getBibfilesCache() const
1411 // if this is a child document and the parent is already loaded
1412 // use the parent's cache instead
1413 Buffer const * tmp = masterBuffer();
1416 return tmp->getBibfilesCache();
1418 // We update the cache when first used instead of at loading time.
1419 if (d->bibfilesCache_.empty())
1420 const_cast<Buffer *>(this)->updateBibfilesCache();
1422 return d->bibfilesCache_;
1426 bool Buffer::isDepClean(string const & name) const
1428 DepClean::const_iterator const it = d->dep_clean.find(name);
1429 if (it == d->dep_clean.end())
1435 void Buffer::markDepClean(string const & name)
1437 d->dep_clean[name] = true;
1441 bool Buffer::dispatch(string const & command, bool * result)
1443 return dispatch(lyxaction.lookupFunc(command), result);
1447 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1449 bool dispatched = true;
1451 switch (func.action) {
1452 case LFUN_BUFFER_EXPORT: {
1453 bool const tmp = doExport(to_utf8(func.argument()), false);
1466 void Buffer::changeLanguage(Language const * from, Language const * to)
1471 for_each(par_iterator_begin(),
1473 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1477 bool Buffer::isMultiLingual() const
1479 ParConstIterator end = par_iterator_end();
1480 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1481 if (it->isMultiLingual(params()))
1488 ParConstIterator Buffer::getParFromID(int const id) const
1490 ParConstIterator it = par_iterator_begin();
1491 ParConstIterator const end = par_iterator_end();
1494 // John says this is called with id == -1 from undo
1495 lyxerr << "getParFromID(), id: " << id << endl;
1499 for (; it != end; ++it)
1507 ParIterator Buffer::getParFromID(int const id)
1509 ParIterator it = par_iterator_begin();
1510 ParIterator const end = par_iterator_end();
1513 // John says this is called with id == -1 from undo
1514 lyxerr << "getParFromID(), id: " << id << endl;
1518 for (; it != end; ++it)
1526 bool Buffer::hasParWithID(int const id) const
1528 ParConstIterator const it = getParFromID(id);
1529 return it != par_iterator_end();
1533 ParIterator Buffer::par_iterator_begin()
1535 return lyx::par_iterator_begin(inset());
1539 ParIterator Buffer::par_iterator_end()
1541 return lyx::par_iterator_end(inset());
1545 ParConstIterator Buffer::par_iterator_begin() const
1547 return lyx::par_const_iterator_begin(inset());
1551 ParConstIterator Buffer::par_iterator_end() const
1553 return lyx::par_const_iterator_end(inset());
1557 Language const * Buffer::language() const
1559 return params().language;
1563 docstring const Buffer::B_(string const & l10n) const
1565 return params().B_(l10n);
1569 bool Buffer::isClean() const
1571 return d->lyx_clean;
1575 bool Buffer::isBakClean() const
1577 return d->bak_clean;
1581 bool Buffer::isExternallyModified(CheckMethod method) const
1583 BOOST_ASSERT(d->filename.exists());
1584 // if method == timestamp, check timestamp before checksum
1585 return (method == checksum_method
1586 || d->timestamp_ != d->filename.lastModified())
1587 && d->checksum_ != d->filename.checksum();
1591 void Buffer::saveCheckSum(FileName const & file) const
1593 if (file.exists()) {
1594 d->timestamp_ = file.lastModified();
1595 d->checksum_ = file.checksum();
1597 // in the case of save to a new file.
1604 void Buffer::markClean() const
1606 if (!d->lyx_clean) {
1607 d->lyx_clean = true;
1610 // if the .lyx file has been saved, we don't need an
1612 d->bak_clean = true;
1616 void Buffer::markBakClean() const
1618 d->bak_clean = true;
1622 void Buffer::setUnnamed(bool flag)
1628 bool Buffer::isUnnamed() const
1634 // FIXME: this function should be moved to buffer_pimpl.C
1635 void Buffer::markDirty()
1638 d->lyx_clean = false;
1641 d->bak_clean = false;
1643 DepClean::iterator it = d->dep_clean.begin();
1644 DepClean::const_iterator const end = d->dep_clean.end();
1646 for (; it != end; ++it)
1651 FileName Buffer::fileName() const
1657 string Buffer::absFileName() const
1659 return d->filename.absFilename();
1663 string Buffer::filePath() const
1665 return d->filename.onlyPath().absFilename() + "/";
1669 bool Buffer::isReadonly() const
1671 return d->read_only;
1675 void Buffer::setParent(Buffer const * buffer)
1677 // Avoids recursive include.
1678 d->parent_buffer = buffer == this ? 0 : buffer;
1683 Buffer const * Buffer::parent()
1685 return d->parent_buffer;
1689 Buffer const * Buffer::masterBuffer() const
1691 if (!d->parent_buffer)
1694 return d->parent_buffer->masterBuffer();
1698 template<typename M>
1699 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
1704 typename M::iterator it = m.lower_bound(x);
1705 if (it == m.begin())
1713 MacroData const * Buffer::getBufferMacro(docstring const & name,
1714 DocIterator const & pos) const
1716 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
1718 // if paragraphs have no macro context set, pos will be empty
1722 // we haven't found anything yet
1723 DocIterator bestPos = par_iterator_begin();
1724 MacroData const * bestData = 0;
1726 // find macro definitions for name
1727 Impl::NamePositionScopeMacroMap::iterator nameIt
1728 = d->macros.find(name);
1729 if (nameIt != d->macros.end()) {
1730 // find last definition in front of pos or at pos itself
1731 Impl::PositionScopeMacroMap::const_iterator it
1732 = greatest_below(nameIt->second, pos);
1733 if (it != nameIt->second.end()) {
1735 // scope ends behind pos?
1736 if (pos < it->second.first) {
1737 // Looks good, remember this. If there
1738 // is no external macro behind this,
1739 // we found the right one already.
1740 bestPos = it->first;
1741 bestData = &it->second.second;
1745 // try previous macro if there is one
1746 if (it == nameIt->second.begin())
1753 // find macros in included files
1754 Impl::PositionScopeBufferMap::const_iterator it
1755 = greatest_below(d->position_to_children, pos);
1756 if (it == d->position_to_children.end())
1757 // no children before
1761 // do we know something better (i.e. later) already?
1762 if (it->first < bestPos )
1765 // scope ends behind pos?
1766 if (pos < it->second.first) {
1767 // look for macro in external file
1768 d->macro_lock = true;
1769 MacroData const * data
1770 = it->second.second->getMacro(name, false);
1771 d->macro_lock = false;
1773 bestPos = it->first;
1779 // try previous file if there is one
1780 if (it == d->position_to_children.begin())
1785 // return the best macro we have found
1790 MacroData const * Buffer::getMacro(docstring const & name,
1791 DocIterator const & pos, bool global) const
1796 // query buffer macros
1797 MacroData const * data = getBufferMacro(name, pos);
1801 // If there is a master buffer, query that
1802 if (d->parent_buffer) {
1803 d->macro_lock = true;
1804 MacroData const * macro
1805 = d->parent_buffer->getMacro(name, *this, false);
1806 d->macro_lock = false;
1812 data = MacroTable::globalMacros().get(name);
1821 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
1823 // set scope end behind the last paragraph
1824 DocIterator scope = par_iterator_begin();
1825 scope.pit() = scope.lastpit() + 1;
1827 return getMacro(name, scope, global);
1831 MacroData const * Buffer::getMacro(docstring const & name, Buffer const & child, bool global) const
1833 // look where the child buffer is included first
1834 Impl::BufferPositionMap::iterator it
1835 = d->children_positions.find(&child);
1836 if (it == d->children_positions.end())
1839 // check for macros at the inclusion position
1840 return getMacro(name, it->second, global);
1844 void Buffer::updateEnvironmentMacros(DocIterator & it,
1846 DocIterator & scope) const
1848 Paragraph & par = it.paragraph();
1850 = par.params().depth();
1851 Length const & leftIndent
1852 = par.params().leftIndent();
1854 // look for macros in each paragraph
1855 while (it.pit() <= lastpit) {
1856 Paragraph & par = it.paragraph();
1859 if ((par.params().depth() > depth
1860 || par.params().leftIndent() != leftIndent)
1861 && par.layout()->isEnvironment()) {
1862 updateBlockMacros(it, scope);
1866 // iterate over the insets of the current paragraph
1867 InsetList const & insets = par.insetList();
1868 InsetList::const_iterator iit = insets.begin();
1869 InsetList::const_iterator end = insets.end();
1870 for (; iit != end; ++iit) {
1871 it.pos() = iit->pos;
1873 // is it a nested text inset?
1874 if (iit->inset->asInsetText()) {
1875 // Inset needs its own scope?
1876 InsetText const * itext
1877 = iit->inset->asInsetText();
1878 bool newScope = itext->isMacroScope(*this);
1880 // scope which ends just behind die inset
1881 DocIterator insetScope = it;
1884 // collect macros in inset
1885 it.push_back(CursorSlice(*iit->inset));
1886 updateInsetMacros(it, newScope ? insetScope : scope);
1891 // is it an external file?
1892 if (iit->inset->lyxCode() == INCLUDE_CODE) {
1893 // get buffer of external file
1894 InsetCommand const & inset
1895 = static_cast<InsetCommand const &>(*iit->inset);
1896 InsetCommandParams const & ip = inset.params();
1897 d->macro_lock = true;
1898 Buffer * child = loadIfNeeded(*this, ip);
1899 d->macro_lock = false;
1903 // register its position, but only when it is
1904 // included first in the buffer
1905 if (d->children_positions.find(child)
1906 == d->children_positions.end())
1907 d->children_positions[child] = it;
1909 // register child with its scope
1910 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
1915 if (iit->inset->lyxCode() != MATHMACRO_CODE)
1919 MathMacroTemplate & macroTemplate
1920 = static_cast<MathMacroTemplate &>(*iit->inset);
1921 MacroContext mc(*this, it);
1922 macroTemplate.updateToContext(mc);
1925 bool valid = macroTemplate.validMacro();
1926 // FIXME: Should be fixNameAndCheckIfValid() in fact,
1927 // then the BufferView's cursor will be invalid in
1928 // some cases which leads to crashes.
1933 d->macros[macroTemplate.name()][it]
1934 = Impl::ScopeMacro(scope, MacroData(*this, it));
1944 void Buffer::updateBlockMacros(DocIterator & it, DocIterator & scope) const
1946 Paragraph & par = it.paragraph();
1948 // set scope for macros in this paragraph:
1949 // * either the "old" outer scope
1950 // * or the scope ending after the environment
1951 if (par.layout()->isEnvironment()) {
1952 // find end of environment block,
1953 DocIterator envEnd = it;
1954 pit_type n = it.lastpit() + 1;
1955 depth_type depth = par.params().depth();
1956 Length const & length = par.params().leftIndent();
1957 // looping through the paragraph, basically until
1958 // the layout changes or the depth gets smaller.
1959 // (the logic of output_latex.cpp's TeXEnvironment)
1962 if (envEnd.pit() == n)
1964 } while (par.layout() == envEnd.paragraph().layout()
1965 || depth < envEnd.paragraph().params().depth()
1966 || length != envEnd.paragraph().params().leftIndent());
1968 // collect macros from environment block
1969 updateEnvironmentMacros(it, envEnd.pit() - 1, envEnd);
1971 // collect macros from paragraph
1972 updateEnvironmentMacros(it, it.pit(), scope);
1977 void Buffer::updateInsetMacros(DocIterator & it, DocIterator & scope) const
1979 // look for macros in each paragraph
1980 pit_type n = it.lastpit() + 1;
1981 while (it.pit() < n)
1982 updateBlockMacros(it, scope);
1986 void Buffer::updateMacros() const
1991 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
1993 // start with empty table
1995 d->children_positions.clear();
1996 d->position_to_children.clear();
1998 // Iterate over buffer, starting with first paragraph
1999 // The scope must be bigger than any lookup DocIterator
2000 // later. For the global lookup, lastpit+1 is used, hence
2001 // we use lastpit+2 here.
2002 DocIterator it = par_iterator_begin();
2003 DocIterator outerScope = it;
2004 outerScope.pit() = outerScope.lastpit() + 2;
2005 updateInsetMacros(it, outerScope);
2009 void Buffer::updateMacroInstances() const
2011 LYXERR(Debug::MACROS, "updateMacroInstances for "
2012 << d->filename.onlyFileName());
2013 ParConstIterator it = par_iterator_begin();
2014 ParConstIterator end = par_iterator_end();
2015 for (; it != end; it.forwardPos()) {
2016 // look for MathData cells in InsetMathNest insets
2017 Inset * inset = it.nextInset();
2021 InsetMath * minset = inset->asInsetMath();
2025 // update macro in all cells of the InsetMathNest
2026 DocIterator::idx_type n = minset->nargs();
2027 MacroContext mc = MacroContext(*this, it);
2028 for (DocIterator::idx_type i = 0; i < n; ++i) {
2029 MathData & data = minset->cell(i);
2030 data.updateMacros(0, mc);
2036 void Buffer::listMacroNames(MacroNameSet & macros) const
2041 d->macro_lock = true;
2043 // loop over macro names
2044 Impl::NamePositionScopeMacroMap::iterator nameIt
2045 = d->macros.begin();
2046 Impl::NamePositionScopeMacroMap::iterator nameEnd
2048 for (; nameIt != nameEnd; ++nameIt)
2049 macros.insert(nameIt->first);
2051 // loop over children
2052 Impl::BufferPositionMap::iterator it
2053 = d->children_positions.begin();
2054 Impl::BufferPositionMap::iterator end
2055 = d->children_positions.end();
2056 for (; it != end; ++it)
2057 it->first->listMacroNames(macros);
2060 if (d->parent_buffer)
2061 d->parent_buffer->listMacroNames(macros);
2063 d->macro_lock = false;
2067 void Buffer::writeParentMacros(odocstream & os) const
2069 if (!d->parent_buffer)
2072 // collect macro names
2074 d->parent_buffer->listMacroNames(names);
2076 // resolve and output them
2077 MacroNameSet::iterator it = names.begin();
2078 MacroNameSet::iterator end = names.end();
2079 for (; it != end; ++it) {
2081 MacroData const * data =
2082 d->parent_buffer->getMacro(*it, *this, false);
2084 data->write(os, true);
2089 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2092 //FIXME: This does not work for child documents yet.
2093 BOOST_ASSERT(code == CITE_CODE || code == REF_CODE);
2094 // Check if the label 'from' appears more than once
2095 vector<docstring> labels;
2098 if (code == CITE_CODE) {
2100 keys.fillWithBibKeys(this);
2101 BiblioInfo::const_iterator bit = keys.begin();
2102 BiblioInfo::const_iterator bend = keys.end();
2104 for (; bit != bend; ++bit)
2106 labels.push_back(bit->first);
2109 getLabelList(labels);
2110 paramName = "reference";
2113 if (count(labels.begin(), labels.end(), from) > 1)
2116 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2117 if (it->lyxCode() == code) {
2118 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2119 docstring const oldValue = inset.getParam(paramName);
2120 if (oldValue == from)
2121 inset.setParam(paramName, to);
2127 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2128 pit_type par_end, bool full_source)
2130 OutputParams runparams(¶ms().encoding());
2131 runparams.nice = true;
2132 runparams.flavor = OutputParams::LATEX;
2133 runparams.linelen = lyxrc.plaintext_linelen;
2134 // No side effect of file copying and image conversion
2135 runparams.dryrun = true;
2139 os << "% " << _("Preview source code") << "\n\n";
2140 d->texrow.newline();
2141 d->texrow.newline();
2143 writeLaTeXSource(os, filePath(), runparams, true, true);
2145 writeDocBookSource(os, absFileName(), runparams, false);
2148 runparams.par_begin = par_begin;
2149 runparams.par_end = par_end;
2150 if (par_begin + 1 == par_end)
2152 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2156 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2157 convert<docstring>(par_begin),
2158 convert<docstring>(par_end - 1))
2160 d->texrow.newline();
2161 d->texrow.newline();
2162 // output paragraphs
2164 latexParagraphs(*this, text(), os, d->texrow, runparams);
2167 docbookParagraphs(paragraphs(), *this, os, runparams);
2173 ErrorList & Buffer::errorList(string const & type) const
2175 static ErrorList emptyErrorList;
2176 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2177 if (I == d->errorLists.end())
2178 return emptyErrorList;
2184 void Buffer::structureChanged() const
2187 gui_->structureChanged();
2191 void Buffer::errors(string const & err) const
2198 void Buffer::message(docstring const & msg) const
2205 void Buffer::setBusy(bool on) const
2212 void Buffer::setReadOnly(bool on) const
2215 d->wa_->setReadOnly(on);
2219 void Buffer::updateTitles() const
2222 d->wa_->updateTitles();
2226 void Buffer::resetAutosaveTimers() const
2229 gui_->resetAutosaveTimers();
2233 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2242 class AutoSaveBuffer : public ForkedProcess {
2245 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2246 : buffer_(buffer), fname_(fname) {}
2248 virtual boost::shared_ptr<ForkedProcess> clone() const
2250 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2255 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2256 from_utf8(fname_.absFilename())));
2257 return run(DontWait);
2261 virtual int generateChild();
2263 Buffer const & buffer_;
2268 int AutoSaveBuffer::generateChild()
2270 // tmp_ret will be located (usually) in /tmp
2271 // will that be a problem?
2272 // Note that this calls ForkedCalls::fork(), so it's
2273 // ok cross-platform.
2274 pid_t const pid = fork();
2275 // If you want to debug the autosave
2276 // you should set pid to -1, and comment out the fork.
2277 if (pid != 0 && pid != -1)
2280 // pid = -1 signifies that lyx was unable
2281 // to fork. But we will do the save
2283 bool failed = false;
2284 FileName const tmp_ret = FileName::tempName("lyxauto");
2285 if (!tmp_ret.empty()) {
2286 buffer_.writeFile(tmp_ret);
2287 // assume successful write of tmp_ret
2288 if (!tmp_ret.moveTo(fname_))
2294 // failed to write/rename tmp_ret so try writing direct
2295 if (!buffer_.writeFile(fname_)) {
2296 // It is dangerous to do this in the child,
2297 // but safe in the parent, so...
2298 if (pid == -1) // emit message signal.
2299 buffer_.message(_("Autosave failed!"));
2303 if (pid == 0) // we are the child so...
2312 // Perfect target for a thread...
2313 void Buffer::autoSave() const
2315 if (isBakClean() || isReadonly()) {
2316 // We don't save now, but we'll try again later
2317 resetAutosaveTimers();
2321 // emit message signal.
2322 message(_("Autosaving current document..."));
2324 // create autosave filename
2325 string fname = filePath();
2327 fname += d->filename.onlyFileName();
2330 AutoSaveBuffer autosave(*this, FileName(fname));
2334 resetAutosaveTimers();
2338 void Buffer::resetChildDocuments(bool close_them) const
2340 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2341 if (it->lyxCode() != INCLUDE_CODE)
2343 InsetCommand const & inset = static_cast<InsetCommand const &>(*it);
2344 InsetCommandParams const & ip = inset.params();
2346 resetParentBuffer(this, ip, close_them);
2349 if (use_gui && masterBuffer() == this)
2350 updateLabels(*this);
2352 // clear references to children in macro tables
2353 d->children_positions.clear();
2354 d->position_to_children.clear();
2358 void Buffer::loadChildDocuments() const
2360 bool parse_error = false;
2362 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2363 if (it->lyxCode() != INCLUDE_CODE)
2365 InsetCommand const & inset = static_cast<InsetCommand const &>(*it);
2366 InsetCommandParams const & ip = inset.params();
2367 Buffer * child = loadIfNeeded(*this, ip);
2370 parse_error |= !child->errorList("Parse").empty();
2371 child->loadChildDocuments();
2374 if (use_gui && masterBuffer() == this)
2375 updateLabels(*this);
2381 string Buffer::bufferFormat() const
2391 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2392 string & result_file) const
2394 string backend_format;
2395 OutputParams runparams(¶ms().encoding());
2396 runparams.flavor = OutputParams::LATEX;
2397 runparams.linelen = lyxrc.plaintext_linelen;
2398 vector<string> backs = backends();
2399 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2400 // Get shortest path to format
2401 Graph::EdgePath path;
2402 for (vector<string>::const_iterator it = backs.begin();
2403 it != backs.end(); ++it) {
2404 Graph::EdgePath p = theConverters().getPath(*it, format);
2405 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2406 backend_format = *it;
2411 runparams.flavor = theConverters().getFlavor(path);
2413 Alert::error(_("Couldn't export file"),
2414 bformat(_("No information for exporting the format %1$s."),
2415 formats.prettyName(format)));
2419 backend_format = format;
2420 // FIXME: Don't hardcode format names here, but use a flag
2421 if (backend_format == "pdflatex")
2422 runparams.flavor = OutputParams::PDFLATEX;
2425 string filename = latexName(false);
2426 filename = addName(temppath(), filename);
2427 filename = changeExtension(filename,
2428 formats.extension(backend_format));
2431 updateMacroInstances();
2433 // Plain text backend
2434 if (backend_format == "text")
2435 writePlaintextFile(*this, FileName(filename), runparams);
2437 else if (backend_format == "lyx")
2438 writeFile(FileName(filename));
2440 else if (isDocBook()) {
2441 runparams.nice = !put_in_tempdir;
2442 makeDocBookFile(FileName(filename), runparams);
2445 else if (backend_format == format) {
2446 runparams.nice = true;
2447 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2449 } else if (!lyxrc.tex_allows_spaces
2450 && contains(filePath(), ' ')) {
2451 Alert::error(_("File name error"),
2452 _("The directory path to the document cannot contain spaces."));
2455 runparams.nice = false;
2456 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2460 string const error_type = (format == "program")
2461 ? "Build" : bufferFormat();
2462 string const ext = formats.extension(format);
2463 FileName const tmp_result_file(changeExtension(filename, ext));
2464 bool const success = theConverters().convert(this, FileName(filename),
2465 tmp_result_file, FileName(absFileName()), backend_format, format,
2466 errorList(error_type));
2467 // Emit the signal to show the error list.
2468 if (format != backend_format)
2473 if (put_in_tempdir) {
2474 result_file = tmp_result_file.absFilename();
2478 result_file = changeExtension(absFileName(), ext);
2479 // We need to copy referenced files (e. g. included graphics
2480 // if format == "dvi") to the result dir.
2481 vector<ExportedFile> const files =
2482 runparams.exportdata->externalFiles(format);
2483 string const dest = onlyPath(result_file);
2484 CopyStatus status = SUCCESS;
2485 for (vector<ExportedFile>::const_iterator it = files.begin();
2486 it != files.end() && status != CANCEL; ++it) {
2487 string const fmt = formats.getFormatFromFile(it->sourceName);
2488 status = copyFile(fmt, it->sourceName,
2489 makeAbsPath(it->exportName, dest),
2490 it->exportName, status == FORCE);
2492 if (status == CANCEL) {
2493 message(_("Document export cancelled."));
2494 } else if (tmp_result_file.exists()) {
2495 // Finally copy the main file
2496 status = copyFile(format, tmp_result_file,
2497 FileName(result_file), result_file,
2499 message(bformat(_("Document exported as %1$s "
2501 formats.prettyName(format),
2502 makeDisplayPath(result_file)));
2504 // This must be a dummy converter like fax (bug 1888)
2505 message(bformat(_("Document exported as %1$s"),
2506 formats.prettyName(format)));
2513 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2516 return doExport(format, put_in_tempdir, result_file);
2520 bool Buffer::preview(string const & format) const
2523 if (!doExport(format, true, result_file))
2525 return formats.view(*this, FileName(result_file), format);
2529 bool Buffer::isExportable(string const & format) const
2531 vector<string> backs = backends();
2532 for (vector<string>::const_iterator it = backs.begin();
2533 it != backs.end(); ++it)
2534 if (theConverters().isReachable(*it, format))
2540 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2542 vector<string> backs = backends();
2543 vector<Format const *> result =
2544 theConverters().getReachable(backs[0], only_viewable, true);
2545 for (vector<string>::const_iterator it = backs.begin() + 1;
2546 it != backs.end(); ++it) {
2547 vector<Format const *> r =
2548 theConverters().getReachable(*it, only_viewable, false);
2549 result.insert(result.end(), r.begin(), r.end());
2555 vector<string> Buffer::backends() const
2558 if (params().getTextClass().isTeXClassAvailable()) {
2559 v.push_back(bufferFormat());
2560 // FIXME: Don't hardcode format names here, but use a flag
2561 if (v.back() == "latex")
2562 v.push_back("pdflatex");
2564 v.push_back("text");
2570 bool Buffer::readFileHelper(FileName const & s)
2572 // File information about normal file
2574 docstring const file = makeDisplayPath(s.absFilename(), 50);
2575 docstring text = bformat(_("The specified document\n%1$s"
2576 "\ncould not be read."), file);
2577 Alert::error(_("Could not read document"), text);
2581 // Check if emergency save file exists and is newer.
2582 FileName const e(s.absFilename() + ".emergency");
2584 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2585 docstring const file = makeDisplayPath(s.absFilename(), 20);
2586 docstring const text =
2587 bformat(_("An emergency save of the document "
2589 "Recover emergency save?"), file);
2590 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2591 _("&Recover"), _("&Load Original"),
2595 // the file is not saved if we load the emergency file.
2605 // Now check if autosave file is newer.
2606 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2608 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2609 docstring const file = makeDisplayPath(s.absFilename(), 20);
2610 docstring const text =
2611 bformat(_("The backup of the document "
2612 "%1$s is newer.\n\nLoad the "
2613 "backup instead?"), file);
2614 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2615 _("&Load backup"), _("Load &original"),
2619 // the file is not saved if we load the autosave file.
2623 // Here we delete the autosave
2634 bool Buffer::loadLyXFile(FileName const & s)
2636 if (s.isReadableFile()) {
2637 if (readFileHelper(s)) {
2638 lyxvc().file_found_hook(s);
2639 if (!s.isWritable())
2644 docstring const file = makeDisplayPath(s.absFilename(), 20);
2645 // Here we probably should run
2646 if (LyXVC::file_not_found_hook(s)) {
2647 docstring const text =
2648 bformat(_("Do you want to retrieve the document"
2649 " %1$s from version control?"), file);
2650 int const ret = Alert::prompt(_("Retrieve from version control?"),
2651 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2654 // How can we know _how_ to do the checkout?
2655 // With the current VC support it has to be,
2656 // a RCS file since CVS do not have special ,v files.
2658 return loadLyXFile(s);
2666 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2668 TeXErrors::Errors::const_iterator cit = terr.begin();
2669 TeXErrors::Errors::const_iterator end = terr.end();
2671 for (; cit != end; ++cit) {
2674 int errorRow = cit->error_in_line;
2675 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2681 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2682 } while (found && id_start == id_end && pos_start == pos_end);
2684 errorList.push_back(ErrorItem(cit->error_desc,
2685 cit->error_text, id_start, pos_start, pos_end));