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 "LayoutFile.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"
56 #include "TexStream.h"
58 #include "TextClass.h"
59 #include "TocBackend.h"
61 #include "VCBackend.h"
65 #include "insets/InsetBibitem.h"
66 #include "insets/InsetBibtex.h"
67 #include "insets/InsetInclude.h"
68 #include "insets/InsetText.h"
70 #include "mathed/MacroTable.h"
71 #include "mathed/MathMacroTemplate.h"
72 #include "mathed/MathSupport.h"
74 #include "frontends/alert.h"
75 #include "frontends/Delegates.h"
76 #include "frontends/WorkAreaManager.h"
78 #include "graphics/Previews.h"
80 #include "support/convert.h"
81 #include "support/debug.h"
82 #include "support/ExceptionMessage.h"
83 #include "support/FileName.h"
84 #include "support/FileNameList.h"
85 #include "support/filetools.h"
86 #include "support/ForkedCalls.h"
87 #include "support/gettext.h"
88 #include "support/gzstream.h"
89 #include "support/lstrings.h"
90 #include "support/lyxalgo.h"
91 #include "support/os.h"
92 #include "support/Package.h"
93 #include "support/Path.h"
94 #include "support/textutils.h"
95 #include "support/types.h"
96 #include "support/FileZipListDir.h"
98 #include <boost/bind.hpp>
99 #include <boost/shared_ptr.hpp>
110 using namespace lyx::support;
114 namespace Alert = frontend::Alert;
115 namespace os = support::os;
119 int const LYX_FORMAT = 325;
121 typedef map<string, bool> DepClean;
122 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
129 Impl(Buffer & parent, FileName const & file, bool readonly);
142 mutable TexRow texrow;
143 Buffer const * parent_buffer;
145 /// need to regenerate .tex?
149 mutable bool lyx_clean;
151 /// is autosave needed?
152 mutable bool bak_clean;
154 /// is this a unnamed file (New...)?
160 /// name of the file the buffer is associated with.
163 /** Set to true only when the file is fully loaded.
164 * Used to prevent the premature generation of previews
165 * and by the citation inset.
167 bool file_fully_loaded;
170 mutable TocBackend toc_backend;
173 typedef pair<DocIterator, MacroData> ScopeMacro;
174 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
175 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
176 /// map from the macro name to the position map,
177 /// which maps the macro definition position to the scope and the MacroData.
178 NamePositionScopeMacroMap macros;
181 /// positions of child buffers in the buffer
182 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
183 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
184 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
185 /// position of children buffers in this buffer
186 BufferPositionMap children_positions;
187 /// map from children inclusion positions to their scope and their buffer
188 PositionScopeBufferMap position_to_children;
190 /// Container for all sort of Buffer dependant errors.
191 map<string, ErrorList> errorLists;
193 /// all embedded files of this buffer
194 EmbeddedFileList embedded_files;
196 /// timestamp and checksum used to test if the file has been externally
197 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
199 unsigned long checksum_;
202 frontend::WorkAreaManager * wa_;
207 /// A cache for the bibfiles (including bibfiles of loaded child
208 /// documents), needed for appropriate update of natbib labels.
209 mutable EmbeddedFileList bibfilesCache_;
211 mutable RefCache ref_cache_;
213 /// our Text that should be wrapped in an InsetText
217 /// Creates the per buffer temporary directory
218 static FileName createBufferTmpDir()
221 // We are in our own directory. Why bother to mangle name?
222 // In fact I wrote this code to circumvent a problematic behaviour
223 // (bug?) of EMX mkstemp().
224 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
225 convert<string>(count++));
227 if (!tmpfl.createDirectory(0777)) {
228 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
229 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
230 from_utf8(tmpfl.absFilename())));
236 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
237 : parent_buffer(0), lyx_clean(true), bak_clean(true), unnamed(false),
238 read_only(readonly_), filename(file), file_fully_loaded(false),
239 toc_backend(&parent), macro_lock(false),
240 embedded_files(), timestamp_(0), checksum_(0), wa_(0),
243 temppath = createBufferTmpDir();
244 lyxvc.setBuffer(&parent);
246 wa_ = new frontend::WorkAreaManager;
250 Buffer::Buffer(string const & file, bool readonly)
251 : d(new Impl(*this, FileName(file), readonly)), gui_(0)
253 LYXERR(Debug::INFO, "Buffer::Buffer()");
255 d->inset.setBuffer(*this);
256 d->inset.initParagraphs(*this);
257 d->inset.setAutoBreakRows(true);
258 d->inset.getText(0)->setMacrocontextPosition(par_iterator_begin());
264 LYXERR(Debug::INFO, "Buffer::~Buffer()");
265 // here the buffer should take care that it is
266 // saved properly, before it goes into the void.
268 // GuiView already destroyed
271 // clear references to children in macro tables
272 d->children_positions.clear();
273 d->position_to_children.clear();
275 if (!d->temppath.destroyDirectory()) {
276 Alert::warning(_("Could not remove temporary directory"),
277 bformat(_("Could not remove the temporary directory %1$s"),
278 from_utf8(d->temppath.absFilename())));
281 // Remove any previewed LaTeX snippets associated with this buffer.
282 graphics::Previews::get().removeLoader(*this);
288 void Buffer::changed() const
295 frontend::WorkAreaManager & Buffer::workAreaManager() const
297 BOOST_ASSERT(d->wa_);
302 Text & Buffer::text() const
304 return const_cast<Text &>(d->inset.text_);
308 Inset & Buffer::inset() const
310 return const_cast<InsetText &>(d->inset);
314 BufferParams & Buffer::params()
320 BufferParams const & Buffer::params() const
326 ParagraphList & Buffer::paragraphs()
328 return text().paragraphs();
332 ParagraphList const & Buffer::paragraphs() const
334 return text().paragraphs();
338 LyXVC & Buffer::lyxvc()
344 LyXVC const & Buffer::lyxvc() const
350 string const Buffer::temppath() const
352 return d->temppath.absFilename();
356 TexRow const & Buffer::texrow() const
362 TocBackend & Buffer::tocBackend() const
364 return d->toc_backend;
368 EmbeddedFileList & Buffer::embeddedFiles()
370 return d->embedded_files;
374 EmbeddedFileList const & Buffer::embeddedFiles() const
376 return d->embedded_files;
380 bool Buffer::embedded() const
382 return params().embedded;
386 Undo & Buffer::undo()
392 string Buffer::latexName(bool const no_path) const
394 FileName latex_name = makeLatexName(d->filename);
395 return no_path ? latex_name.onlyFileName()
396 : latex_name.absFilename();
400 string Buffer::logName(LogType * type) const
402 string const filename = latexName(false);
404 if (filename.empty()) {
410 string const path = temppath();
412 FileName const fname(addName(temppath(),
413 onlyFilename(changeExtension(filename,
415 FileName const bname(
416 addName(path, onlyFilename(
417 changeExtension(filename,
418 formats.extension("literate") + ".out"))));
420 // If no Latex log or Build log is newer, show Build log
422 if (bname.exists() &&
423 (!fname.exists() || fname.lastModified() < bname.lastModified())) {
424 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
427 return bname.absFilename();
429 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
432 return fname.absFilename();
436 void Buffer::setReadonly(bool const flag)
438 if (d->read_only != flag) {
445 void Buffer::setFileName(string const & newfile)
447 d->filename = makeAbsPath(newfile);
448 setReadonly(d->filename.isReadOnly());
453 int Buffer::readHeader(Lexer & lex)
455 int unknown_tokens = 0;
457 int begin_header_line = -1;
459 // Initialize parameters that may be/go lacking in header:
460 params().branchlist().clear();
461 params().preamble.erase();
462 params().options.erase();
463 params().float_placement.erase();
464 params().paperwidth.erase();
465 params().paperheight.erase();
466 params().leftmargin.erase();
467 params().rightmargin.erase();
468 params().topmargin.erase();
469 params().bottommargin.erase();
470 params().headheight.erase();
471 params().headsep.erase();
472 params().footskip.erase();
473 params().columnsep.erase();
474 params().listings_params.clear();
475 params().clearLayoutModules();
476 params().pdfoptions().clear();
478 for (int i = 0; i < 4; ++i) {
479 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
480 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
483 ErrorList & errorList = d->errorLists["Parse"];
487 string const token = lex.getString();
492 if (token == "\\end_header")
496 if (token == "\\begin_header") {
497 begin_header_line = line;
501 LYXERR(Debug::PARSER, "Handling document header token: `"
504 string unknown = params().readToken(lex, token, d->filename.onlyPath(),
506 if (!unknown.empty()) {
507 if (unknown[0] != '\\' && token == "\\textclass") {
508 Alert::warning(_("Unknown document class"),
509 bformat(_("Using the default document class, because the "
510 "class %1$s is unknown."), from_utf8(unknown)));
513 docstring const s = bformat(_("Unknown token: "
517 errorList.push_back(ErrorItem(_("Document header error"),
522 if (begin_header_line) {
523 docstring const s = _("\\begin_header is missing");
524 errorList.push_back(ErrorItem(_("Document header error"),
528 params().makeDocumentClass();
530 return unknown_tokens;
535 // changed to be public and have one parameter
536 // Returns false if "\end_document" is not read (Asger)
537 bool Buffer::readDocument(Lexer & lex)
539 ErrorList & errorList = d->errorLists["Parse"];
543 string const token = lex.getString();
544 if (token != "\\begin_document") {
545 docstring const s = _("\\begin_document is missing");
546 errorList.push_back(ErrorItem(_("Document header error"),
550 // we are reading in a brand new document
551 BOOST_ASSERT(paragraphs().empty());
555 if (params().outputChanges) {
556 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
557 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
558 LaTeXFeatures::isAvailable("xcolor");
560 if (!dvipost && !xcolorsoul) {
561 Alert::warning(_("Changes not shown in LaTeX output"),
562 _("Changes will not be highlighted in LaTeX output, "
563 "because neither dvipost nor xcolor/soul are installed.\n"
564 "Please install these packages or redefine "
565 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
566 } else if (!xcolorsoul) {
567 Alert::warning(_("Changes not shown in LaTeX output"),
568 _("Changes will not be highlighted in LaTeX output "
569 "when using pdflatex, because xcolor and soul are not installed.\n"
570 "Please install both packages or redefine "
571 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
576 bool const res = text().read(*this, lex, errorList, &(d->inset));
578 // Enable embeded files, which will set temp path and move
579 // inconsistent inzip files if needed.
581 embeddedFiles().validate(*this);
582 embeddedFiles().enable(params().embedded, *this, false);
583 } catch (ExceptionMessage const & message) {
584 Alert::error(message.title_, message.details_);
585 Alert::warning(_("Failed to read embedded files"),
586 _("Due to most likely a bug, LyX failed to locate all embedded "
587 "file. If you unzip the LyX file, you should be able to see and "
588 "open content.lyx which is your main text. You may also be able "
589 "to recover some embedded files. Please report this bug to the "
590 "lyx-devel mailing list."));
595 updateMacroInstances();
600 // needed to insert the selection
601 void Buffer::insertStringAsLines(ParagraphList & pars,
602 pit_type & pit, pos_type & pos,
603 Font const & fn, docstring const & str, bool autobreakrows)
607 // insert the string, don't insert doublespace
608 bool space_inserted = true;
609 for (docstring::const_iterator cit = str.begin();
610 cit != str.end(); ++cit) {
611 Paragraph & par = pars[pit];
613 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
614 breakParagraph(params(), pars, pit, pos,
615 par.layout().isEnvironment());
618 space_inserted = true;
622 // do not insert consecutive spaces if !free_spacing
623 } else if ((*cit == ' ' || *cit == '\t') &&
624 space_inserted && !par.isFreeSpacing()) {
626 } else if (*cit == '\t') {
627 if (!par.isFreeSpacing()) {
628 // tabs are like spaces here
629 par.insertChar(pos, ' ', font, params().trackChanges);
631 space_inserted = true;
633 const pos_type n = 8 - pos % 8;
634 for (pos_type i = 0; i < n; ++i) {
635 par.insertChar(pos, ' ', font, params().trackChanges);
638 space_inserted = true;
640 } else if (!isPrintable(*cit)) {
641 // Ignore unprintables
644 // just insert the character
645 par.insertChar(pos, *cit, font, params().trackChanges);
647 space_inserted = (*cit == ' ');
654 bool Buffer::readString(string const & s)
656 params().compressed = false;
658 // remove dummy empty par
659 paragraphs().clear();
663 FileName const name = FileName::tempName();
664 switch (readFile(lex, name, true)) {
668 // We need to call lyx2lyx, so write the input to a file
669 ofstream os(name.toFilesystemEncoding().c_str());
672 return readFile(name);
682 bool Buffer::readFile(FileName const & filename)
684 FileName fname(filename);
685 // Check if the file is compressed.
686 string format = filename.guessFormatFromContents();
687 if (format == "zip") {
688 // decompress to a temp directory
689 LYXERR(Debug::FILES, filename << " is in zip format. Unzip to " << temppath());
690 ::unzipToDir(filename.toFilesystemEncoding(), temppath());
692 FileName lyxfile(addName(temppath(), "content.lyx"));
693 // if both manifest.txt and file.lyx exist, this is am embedded file
694 if (lyxfile.exists()) {
695 // if in bundled format, save checksum of the compressed file, not content.lyx
696 saveCheckSum(filename);
697 params().embedded = true;
701 // The embedded lyx file can also be compressed, for backward compatibility
702 format = fname.guessFormatFromContents();
703 if (format == "gzip" || format == "zip" || format == "compress")
704 params().compressed = true;
706 // remove dummy empty par
707 paragraphs().clear();
710 if (readFile(lex, fname) != success)
717 bool Buffer::isFullyLoaded() const
719 return d->file_fully_loaded;
723 void Buffer::setFullyLoaded(bool value)
725 d->file_fully_loaded = value;
729 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
732 BOOST_ASSERT(!filename.empty());
735 Alert::error(_("Document could not be read"),
736 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
741 string const token = lex.getString();
744 Alert::error(_("Document could not be read"),
745 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
749 // the first token _must_ be...
750 if (token != "\\lyxformat") {
751 lyxerr << "Token: " << token << endl;
753 Alert::error(_("Document format failure"),
754 bformat(_("%1$s is not a LyX document."),
755 from_utf8(filename.absFilename())));
760 string tmp_format = lex.getString();
761 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
762 // if present remove ".," from string.
763 string::size_type dot = tmp_format.find_first_of(".,");
764 //lyxerr << " dot found at " << dot << endl;
765 if (dot != string::npos)
766 tmp_format.erase(dot, 1);
767 int const file_format = convert<int>(tmp_format);
768 //lyxerr << "format: " << file_format << endl;
770 // save timestamp and checksum of the original disk file, making sure
771 // to not overwrite them with those of the file created in the tempdir
772 // when it has to be converted to the current format.
774 // Save the timestamp and checksum of disk file. If filename is an
775 // emergency file, save the timestamp and checksum of the original lyx file
776 // because isExternallyModified will check for this file. (BUG4193)
777 string diskfile = filename.absFilename();
778 if (suffixIs(diskfile, ".emergency"))
779 diskfile = diskfile.substr(0, diskfile.size() - 10);
780 saveCheckSum(FileName(diskfile));
783 if (file_format != LYX_FORMAT) {
786 // lyx2lyx would fail
789 FileName const tmpfile = FileName::tempName();
790 if (tmpfile.empty()) {
791 Alert::error(_("Conversion failed"),
792 bformat(_("%1$s is from a different"
793 " version of LyX, but a temporary"
794 " file for converting it could"
796 from_utf8(filename.absFilename())));
799 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
800 if (lyx2lyx.empty()) {
801 Alert::error(_("Conversion script not found"),
802 bformat(_("%1$s is from a different"
803 " version of LyX, but the"
804 " conversion script lyx2lyx"
805 " could not be found."),
806 from_utf8(filename.absFilename())));
809 ostringstream command;
810 command << os::python()
811 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
812 << " -t " << convert<string>(LYX_FORMAT)
813 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
814 << ' ' << quoteName(filename.toFilesystemEncoding());
815 string const command_str = command.str();
817 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
819 cmd_ret const ret = runCommand(command_str);
820 if (ret.first != 0) {
821 Alert::error(_("Conversion script failed"),
822 bformat(_("%1$s is from a different version"
823 " of LyX, but the lyx2lyx script"
824 " failed to convert it."),
825 from_utf8(filename.absFilename())));
828 bool const ret = readFile(tmpfile);
829 // Do stuff with tmpfile name and buffer name here.
830 return ret ? success : failure;
835 if (readDocument(lex)) {
836 Alert::error(_("Document format failure"),
837 bformat(_("%1$s ended unexpectedly, which means"
838 " that it is probably corrupted."),
839 from_utf8(filename.absFilename())));
842 d->file_fully_loaded = true;
847 // Should probably be moved to somewhere else: BufferView? LyXView?
848 bool Buffer::save() const
850 // We don't need autosaves in the immediate future. (Asger)
851 resetAutosaveTimers();
853 string const encodedFilename = d->filename.toFilesystemEncoding();
856 bool madeBackup = false;
858 // make a backup if the file already exists
859 if (lyxrc.make_backup && fileName().exists()) {
860 backupName = FileName(absFileName() + '~');
861 if (!lyxrc.backupdir_path.empty()) {
862 string const mangledName =
863 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
864 backupName = FileName(addName(lyxrc.backupdir_path,
867 if (fileName().copyTo(backupName)) {
870 Alert::error(_("Backup failure"),
871 bformat(_("Cannot create backup file %1$s.\n"
872 "Please check whether the directory exists and is writeable."),
873 from_utf8(backupName.absFilename())));
874 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
878 // ask if the disk file has been externally modified (use checksum method)
879 if (fileName().exists() && isExternallyModified(checksum_method)) {
880 docstring const file = makeDisplayPath(absFileName(), 20);
881 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
882 "you want to overwrite this file?"), file);
883 int const ret = Alert::prompt(_("Overwrite modified file?"),
884 text, 1, 1, _("&Overwrite"), _("&Cancel"));
889 if (writeFile(d->filename)) {
893 // Saving failed, so backup is not backup
895 backupName.moveTo(d->filename);
901 bool Buffer::writeFile(FileName const & fname) const
903 if (d->read_only && fname == d->filename)
909 if (params().embedded)
910 // first write the .lyx file to the temporary directory
911 content = FileName(addName(temppath(), "content.lyx"));
915 docstring const str = bformat(_("Saving document %1$s..."),
916 makeDisplayPath(content.absFilename()));
919 if (params().compressed) {
920 gz::ogzstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
921 retval = ofs && write(ofs);
923 ofstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
924 retval = ofs && write(ofs);
928 message(str + _(" could not write file!"));
932 removeAutosaveFile(d->filename.absFilename());
934 if (params().embedded) {
935 message(str + _(" writing embedded files."));
936 // if embedding is enabled, write file.lyx and all the embedded files
937 // to the zip file fname.
938 if (!d->embedded_files.writeFile(fname, *this)) {
939 message(str + _(" could not write embedded files!"));
943 saveCheckSum(d->filename);
944 message(str + _(" done."));
950 bool Buffer::write(ostream & ofs) const
953 // Use the standard "C" locale for file output.
954 ofs.imbue(locale::classic());
957 // The top of the file should not be written by params().
959 // write out a comment in the top of the file
960 ofs << "#LyX " << lyx_version
961 << " created this file. For more info see http://www.lyx.org/\n"
962 << "\\lyxformat " << LYX_FORMAT << "\n"
963 << "\\begin_document\n";
965 /// For each author, set 'used' to true if there is a change
966 /// by this author in the document; otherwise set it to 'false'.
967 AuthorList::Authors::const_iterator a_it = params().authors().begin();
968 AuthorList::Authors::const_iterator a_end = params().authors().end();
969 for (; a_it != a_end; ++a_it)
970 a_it->second.setUsed(false);
972 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
973 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
974 for ( ; it != end; ++it)
975 it->checkAuthors(params().authors());
977 // now write out the buffer parameters.
978 ofs << "\\begin_header\n";
979 params().writeFile(ofs);
980 ofs << "\\end_header\n";
983 ofs << "\n\\begin_body\n";
984 text().write(*this, ofs);
985 ofs << "\n\\end_body\n";
987 // Write marker that shows file is complete
988 ofs << "\\end_document" << endl;
990 // Shouldn't really be needed....
993 // how to check if close went ok?
994 // Following is an attempt... (BE 20001011)
996 // good() returns false if any error occured, including some
998 // bad() returns true if something bad happened in the buffer,
999 // which should include file system full errors.
1004 lyxerr << "File was not closed properly." << endl;
1011 bool Buffer::makeLaTeXFile(FileName const & fname,
1012 string const & original_path,
1013 OutputParams const & runparams,
1014 bool output_preamble, bool output_body) const
1016 string const encoding = runparams.encoding->iconvName();
1017 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1020 try { ofs.reset(encoding); }
1021 catch (iconv_codecvt_facet_exception & e) {
1022 lyxerr << "Caught iconv exception: " << e.what() << endl;
1023 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1024 "verify that the support software for your encoding (%1$s) is "
1025 "properly installed"), from_ascii(encoding)));
1028 if (!openFileWrite(ofs, fname))
1031 //TexStream ts(ofs.rdbuf(), &texrow());
1032 ErrorList & errorList = d->errorLists["Export"];
1034 bool failed_export = false;
1037 writeLaTeXSource(ofs, original_path,
1038 runparams, output_preamble, output_body);
1040 catch (EncodingException & e) {
1041 odocstringstream ods;
1042 ods.put(e.failed_char);
1044 oss << "0x" << hex << e.failed_char << dec;
1045 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1046 " (code point %2$s)"),
1047 ods.str(), from_utf8(oss.str()));
1048 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1049 "representable in the chosen encoding.\n"
1050 "Changing the document encoding to utf8 could help."),
1051 e.par_id, e.pos, e.pos + 1));
1052 failed_export = true;
1054 catch (iconv_codecvt_facet_exception & e) {
1055 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1056 _(e.what()), -1, 0, 0));
1057 failed_export = true;
1059 catch (exception const & e) {
1060 errorList.push_back(ErrorItem(_("conversion failed"),
1061 _(e.what()), -1, 0, 0));
1062 failed_export = true;
1065 lyxerr << "Caught some really weird exception..." << endl;
1066 LyX::cref().exit(1);
1071 failed_export = true;
1072 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1076 return !failed_export;
1080 void Buffer::writeLaTeXSource(odocstream & os,
1081 string const & original_path,
1082 OutputParams const & runparams_in,
1083 bool const output_preamble, bool const output_body) const
1085 // The child documents, if any, shall be already loaded at this point.
1087 OutputParams runparams = runparams_in;
1089 // validate the buffer.
1090 LYXERR(Debug::LATEX, " Validating buffer...");
1091 LaTeXFeatures features(*this, params(), runparams);
1093 LYXERR(Debug::LATEX, " Buffer validation done.");
1095 // The starting paragraph of the coming rows is the
1096 // first paragraph of the document. (Asger)
1097 if (output_preamble && runparams.nice) {
1098 os << "%% LyX " << lyx_version << " created this file. "
1099 "For more info, see http://www.lyx.org/.\n"
1100 "%% Do not edit unless you really know what "
1102 d->texrow.newline();
1103 d->texrow.newline();
1105 LYXERR(Debug::INFO, "lyx document header finished");
1107 // Don't move this behind the parent_buffer=0 code below,
1108 // because then the macros will not get the right "redefinition"
1109 // flag as they don't see the parent macros which are output before.
1112 // fold macros if possible, still with parent buffer as the
1113 // macros will be put in the prefix anyway.
1114 updateMacroInstances();
1116 // There are a few differences between nice LaTeX and usual files:
1117 // usual is \batchmode and has a
1118 // special input@path to allow the including of figures
1119 // with either \input or \includegraphics (what figinsets do).
1120 // input@path is set when the actual parameter
1121 // original_path is set. This is done for usual tex-file, but not
1122 // for nice-latex-file. (Matthias 250696)
1123 // Note that input@path is only needed for something the user does
1124 // in the preamble, included .tex files or ERT, files included by
1125 // LyX work without it.
1126 if (output_preamble) {
1127 if (!runparams.nice) {
1128 // code for usual, NOT nice-latex-file
1129 os << "\\batchmode\n"; // changed
1130 // from \nonstopmode
1131 d->texrow.newline();
1133 if (!original_path.empty()) {
1135 // We don't know the encoding of inputpath
1136 docstring const inputpath = from_utf8(latex_path(original_path));
1137 os << "\\makeatletter\n"
1138 << "\\def\\input@path{{"
1139 << inputpath << "/}}\n"
1140 << "\\makeatother\n";
1141 d->texrow.newline();
1142 d->texrow.newline();
1143 d->texrow.newline();
1146 // get parent macros (if this buffer has a parent) which will be
1147 // written at the document begin further down.
1148 MacroSet parentMacros;
1149 listParentMacros(parentMacros, features);
1151 // Write the preamble
1152 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1158 os << "\\begin{document}\n";
1159 d->texrow.newline();
1161 // output the parent macros
1162 MacroSet::iterator it = parentMacros.begin();
1163 MacroSet::iterator end = parentMacros.end();
1164 for (; it != end; ++it)
1165 (*it)->write(os, true);
1166 } // output_preamble
1168 d->texrow.start(paragraphs().begin()->id(), 0);
1170 LYXERR(Debug::INFO, "preamble finished, now the body.");
1172 // if we are doing a real file with body, even if this is the
1173 // child of some other buffer, let's cut the link here.
1174 // This happens for example if only a child document is printed.
1175 Buffer const * save_parent = 0;
1176 if (output_preamble) {
1177 save_parent = d->parent_buffer;
1178 d->parent_buffer = 0;
1182 latexParagraphs(*this, text(), os, d->texrow, runparams);
1184 // Restore the parenthood if needed
1185 if (output_preamble)
1186 d->parent_buffer = save_parent;
1188 // add this just in case after all the paragraphs
1190 d->texrow.newline();
1192 if (output_preamble) {
1193 os << "\\end{document}\n";
1194 d->texrow.newline();
1195 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1197 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1199 runparams_in.encoding = runparams.encoding;
1201 // Just to be sure. (Asger)
1202 d->texrow.newline();
1204 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1205 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1209 bool Buffer::isLatex() const
1211 return params().documentClass().outputType() == LATEX;
1215 bool Buffer::isLiterate() const
1217 return params().documentClass().outputType() == LITERATE;
1221 bool Buffer::isDocBook() const
1223 return params().documentClass().outputType() == DOCBOOK;
1227 void Buffer::makeDocBookFile(FileName const & fname,
1228 OutputParams const & runparams,
1229 bool const body_only) const
1231 LYXERR(Debug::LATEX, "makeDocBookFile...");
1234 if (!openFileWrite(ofs, fname))
1237 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1241 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1245 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1246 OutputParams const & runparams,
1247 bool const only_body) const
1249 LaTeXFeatures features(*this, params(), runparams);
1254 DocumentClass const & tclass = params().documentClass();
1255 string const top_element = tclass.latexname();
1258 if (runparams.flavor == OutputParams::XML)
1259 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1262 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1265 if (! tclass.class_header().empty())
1266 os << from_ascii(tclass.class_header());
1267 else if (runparams.flavor == OutputParams::XML)
1268 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1269 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1271 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1273 docstring preamble = from_utf8(params().preamble);
1274 if (runparams.flavor != OutputParams::XML ) {
1275 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1276 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1277 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1278 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1281 string const name = runparams.nice
1282 ? changeExtension(absFileName(), ".sgml") : fname;
1283 preamble += features.getIncludedFiles(name);
1284 preamble += features.getLyXSGMLEntities();
1286 if (!preamble.empty()) {
1287 os << "\n [ " << preamble << " ]";
1292 string top = top_element;
1294 if (runparams.flavor == OutputParams::XML)
1295 top += params().language->code();
1297 top += params().language->code().substr(0,2);
1300 if (!params().options.empty()) {
1302 top += params().options;
1305 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1306 << " file was created by LyX " << lyx_version
1307 << "\n See http://www.lyx.org/ for more information -->\n";
1309 params().documentClass().counters().reset();
1313 sgml::openTag(os, top);
1315 docbookParagraphs(paragraphs(), *this, os, runparams);
1316 sgml::closeTag(os, top_element);
1320 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1321 // Other flags: -wall -v0 -x
1322 int Buffer::runChktex()
1326 // get LaTeX-Filename
1327 FileName const path(temppath());
1328 string const name = addName(path.absFilename(), latexName());
1329 string const org_path = filePath();
1331 PathChanger p(path); // path to LaTeX file
1332 message(_("Running chktex..."));
1334 // Generate the LaTeX file if neccessary
1335 OutputParams runparams(¶ms().encoding());
1336 runparams.flavor = OutputParams::LATEX;
1337 runparams.nice = false;
1338 makeLaTeXFile(FileName(name), org_path, runparams);
1341 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1342 int const res = chktex.run(terr); // run chktex
1345 Alert::error(_("chktex failure"),
1346 _("Could not run chktex successfully."));
1347 } else if (res > 0) {
1348 ErrorList & errlist = d->errorLists["ChkTeX"];
1350 bufferErrors(terr, errlist);
1361 void Buffer::validate(LaTeXFeatures & features) const
1363 params().validate(features);
1367 for_each(paragraphs().begin(), paragraphs().end(),
1368 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1370 if (lyxerr.debugging(Debug::LATEX)) {
1371 features.showStruct();
1376 void Buffer::getLabelList(vector<docstring> & list) const
1378 // If this is a child document, use the parent's list instead.
1379 if (d->parent_buffer) {
1380 d->parent_buffer->getLabelList(list);
1385 Toc & toc = d->toc_backend.toc("label");
1386 TocIterator toc_it = toc.begin();
1387 TocIterator end = toc.end();
1388 for (; toc_it != end; ++toc_it) {
1389 if (toc_it->depth() == 0)
1390 list.push_back(toc_it->str());
1395 void Buffer::updateBibfilesCache() const
1397 // If this is a child document, use the parent's cache instead.
1398 if (d->parent_buffer) {
1399 d->parent_buffer->updateBibfilesCache();
1403 d->bibfilesCache_.clear();
1404 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1405 if (it->lyxCode() == BIBTEX_CODE) {
1406 InsetBibtex const & inset =
1407 static_cast<InsetBibtex const &>(*it);
1408 EmbeddedFileList const bibfiles = inset.getBibFiles();
1409 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1412 } else if (it->lyxCode() == INCLUDE_CODE) {
1413 InsetInclude & inset =
1414 static_cast<InsetInclude &>(*it);
1415 inset.updateBibfilesCache();
1416 EmbeddedFileList const & bibfiles =
1417 inset.getBibfilesCache(*this);
1418 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1426 EmbeddedFileList const & Buffer::getBibfilesCache() const
1428 // If this is a child document, use the parent's cache instead.
1429 if (d->parent_buffer)
1430 return d->parent_buffer->getBibfilesCache();
1432 // We update the cache when first used instead of at loading time.
1433 if (d->bibfilesCache_.empty())
1434 const_cast<Buffer *>(this)->updateBibfilesCache();
1436 return d->bibfilesCache_;
1440 bool Buffer::isDepClean(string const & name) const
1442 DepClean::const_iterator const it = d->dep_clean.find(name);
1443 if (it == d->dep_clean.end())
1449 void Buffer::markDepClean(string const & name)
1451 d->dep_clean[name] = true;
1455 bool Buffer::dispatch(string const & command, bool * result)
1457 return dispatch(lyxaction.lookupFunc(command), result);
1461 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1463 bool dispatched = true;
1465 switch (func.action) {
1466 case LFUN_BUFFER_EXPORT: {
1467 bool const tmp = doExport(to_utf8(func.argument()), false);
1480 void Buffer::changeLanguage(Language const * from, Language const * to)
1485 for_each(par_iterator_begin(),
1487 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1491 bool Buffer::isMultiLingual() const
1493 ParConstIterator end = par_iterator_end();
1494 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1495 if (it->isMultiLingual(params()))
1502 DocIterator Buffer::getParFromID(int const id) const
1505 // John says this is called with id == -1 from undo
1506 lyxerr << "getParFromID(), id: " << id << endl;
1507 return doc_iterator_end(inset());
1510 for (DocIterator it = doc_iterator_begin(inset()); !it.atEnd(); it.forwardPar())
1511 if (it.paragraph().id() == id)
1514 return doc_iterator_end(inset());
1518 bool Buffer::hasParWithID(int const id) const
1520 return !getParFromID(id).atEnd();
1524 ParIterator Buffer::par_iterator_begin()
1526 return ParIterator(doc_iterator_begin(inset()));
1530 ParIterator Buffer::par_iterator_end()
1532 return ParIterator(doc_iterator_end(inset()));
1536 ParConstIterator Buffer::par_iterator_begin() const
1538 return lyx::par_const_iterator_begin(inset());
1542 ParConstIterator Buffer::par_iterator_end() const
1544 return lyx::par_const_iterator_end(inset());
1548 Language const * Buffer::language() const
1550 return params().language;
1554 docstring const Buffer::B_(string const & l10n) const
1556 return params().B_(l10n);
1560 bool Buffer::isClean() const
1562 return d->lyx_clean;
1566 bool Buffer::isBakClean() const
1568 return d->bak_clean;
1572 bool Buffer::isExternallyModified(CheckMethod method) const
1574 BOOST_ASSERT(d->filename.exists());
1575 // if method == timestamp, check timestamp before checksum
1576 return (method == checksum_method
1577 || d->timestamp_ != d->filename.lastModified())
1578 && d->checksum_ != d->filename.checksum();
1582 void Buffer::saveCheckSum(FileName const & file) const
1584 if (file.exists()) {
1585 d->timestamp_ = file.lastModified();
1586 d->checksum_ = file.checksum();
1588 // in the case of save to a new file.
1595 void Buffer::markClean() const
1597 if (!d->lyx_clean) {
1598 d->lyx_clean = true;
1601 // if the .lyx file has been saved, we don't need an
1603 d->bak_clean = true;
1607 void Buffer::markBakClean() const
1609 d->bak_clean = true;
1613 void Buffer::setUnnamed(bool flag)
1619 bool Buffer::isUnnamed() const
1625 // FIXME: this function should be moved to buffer_pimpl.C
1626 void Buffer::markDirty()
1629 d->lyx_clean = false;
1632 d->bak_clean = false;
1634 DepClean::iterator it = d->dep_clean.begin();
1635 DepClean::const_iterator const end = d->dep_clean.end();
1637 for (; it != end; ++it)
1642 FileName Buffer::fileName() const
1648 string Buffer::absFileName() const
1650 return d->filename.absFilename();
1654 string Buffer::filePath() const
1656 return d->filename.onlyPath().absFilename() + "/";
1660 bool Buffer::isReadonly() const
1662 return d->read_only;
1666 void Buffer::setParent(Buffer const * buffer)
1668 // Avoids recursive include.
1669 d->parent_buffer = buffer == this ? 0 : buffer;
1674 Buffer const * Buffer::parent()
1676 return d->parent_buffer;
1680 Buffer const * Buffer::masterBuffer() const
1682 if (!d->parent_buffer)
1685 return d->parent_buffer->masterBuffer();
1689 template<typename M>
1690 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
1695 typename M::iterator it = m.lower_bound(x);
1696 if (it == m.begin())
1704 MacroData const * Buffer::getBufferMacro(docstring const & name,
1705 DocIterator const & pos) const
1707 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
1709 // if paragraphs have no macro context set, pos will be empty
1713 // we haven't found anything yet
1714 DocIterator bestPos = par_iterator_begin();
1715 MacroData const * bestData = 0;
1717 // find macro definitions for name
1718 Impl::NamePositionScopeMacroMap::iterator nameIt
1719 = d->macros.find(name);
1720 if (nameIt != d->macros.end()) {
1721 // find last definition in front of pos or at pos itself
1722 Impl::PositionScopeMacroMap::const_iterator it
1723 = greatest_below(nameIt->second, pos);
1724 if (it != nameIt->second.end()) {
1726 // scope ends behind pos?
1727 if (pos < it->second.first) {
1728 // Looks good, remember this. If there
1729 // is no external macro behind this,
1730 // we found the right one already.
1731 bestPos = it->first;
1732 bestData = &it->second.second;
1736 // try previous macro if there is one
1737 if (it == nameIt->second.begin())
1744 // find macros in included files
1745 Impl::PositionScopeBufferMap::const_iterator it
1746 = greatest_below(d->position_to_children, pos);
1747 if (it == d->position_to_children.end())
1748 // no children before
1752 // do we know something better (i.e. later) already?
1753 if (it->first < bestPos )
1756 // scope ends behind pos?
1757 if (pos < it->second.first) {
1758 // look for macro in external file
1759 d->macro_lock = true;
1760 MacroData const * data
1761 = it->second.second->getMacro(name, false);
1762 d->macro_lock = false;
1764 bestPos = it->first;
1770 // try previous file if there is one
1771 if (it == d->position_to_children.begin())
1776 // return the best macro we have found
1781 MacroData const * Buffer::getMacro(docstring const & name,
1782 DocIterator const & pos, bool global) const
1787 // query buffer macros
1788 MacroData const * data = getBufferMacro(name, pos);
1792 // If there is a master buffer, query that
1793 if (d->parent_buffer) {
1794 d->macro_lock = true;
1795 MacroData const * macro = d->parent_buffer->getMacro(
1796 name, *this, false);
1797 d->macro_lock = false;
1803 data = MacroTable::globalMacros().get(name);
1812 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
1814 // set scope end behind the last paragraph
1815 DocIterator scope = par_iterator_begin();
1816 scope.pit() = scope.lastpit() + 1;
1818 return getMacro(name, scope, global);
1822 MacroData const * Buffer::getMacro(docstring const & name,
1823 Buffer const & child, bool global) const
1825 // look where the child buffer is included first
1826 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
1827 if (it == d->children_positions.end())
1830 // check for macros at the inclusion position
1831 return getMacro(name, it->second, global);
1835 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
1837 pit_type lastpit = it.lastpit();
1839 // look for macros in each paragraph
1840 while (it.pit() <= lastpit) {
1841 Paragraph & par = it.paragraph();
1843 // iterate over the insets of the current paragraph
1844 InsetList const & insets = par.insetList();
1845 InsetList::const_iterator iit = insets.begin();
1846 InsetList::const_iterator end = insets.end();
1847 for (; iit != end; ++iit) {
1848 it.pos() = iit->pos;
1850 // is it a nested text inset?
1851 if (iit->inset->asInsetText()) {
1852 // Inset needs its own scope?
1853 InsetText const * itext
1854 = iit->inset->asInsetText();
1855 bool newScope = itext->isMacroScope();
1857 // scope which ends just behind the inset
1858 DocIterator insetScope = it;
1861 // collect macros in inset
1862 it.push_back(CursorSlice(*iit->inset));
1863 updateMacros(it, newScope ? insetScope : scope);
1868 // is it an external file?
1869 if (iit->inset->lyxCode() == INCLUDE_CODE) {
1870 // get buffer of external file
1871 InsetCommand const & inset
1872 = static_cast<InsetCommand const &>(*iit->inset);
1873 InsetCommandParams const & ip = inset.params();
1874 d->macro_lock = true;
1875 Buffer * child = loadIfNeeded(*this, ip);
1876 d->macro_lock = false;
1880 // register its position, but only when it is
1881 // included first in the buffer
1882 if (d->children_positions.find(child)
1883 == d->children_positions.end())
1884 d->children_positions[child] = it;
1886 // register child with its scope
1887 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
1891 if (iit->inset->lyxCode() != MATHMACRO_CODE)
1895 MathMacroTemplate & macroTemplate
1896 = static_cast<MathMacroTemplate &>(*iit->inset);
1897 MacroContext mc(*this, it);
1898 macroTemplate.updateToContext(mc);
1901 bool valid = macroTemplate.validMacro();
1902 // FIXME: Should be fixNameAndCheckIfValid() in fact,
1903 // then the BufferView's cursor will be invalid in
1904 // some cases which leads to crashes.
1909 d->macros[macroTemplate.name()][it] =
1910 Impl::ScopeMacro(scope, MacroData(*this, it));
1920 void Buffer::updateMacros() const
1925 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
1927 // start with empty table
1929 d->children_positions.clear();
1930 d->position_to_children.clear();
1932 // Iterate over buffer, starting with first paragraph
1933 // The scope must be bigger than any lookup DocIterator
1934 // later. For the global lookup, lastpit+1 is used, hence
1935 // we use lastpit+2 here.
1936 DocIterator it = par_iterator_begin();
1937 DocIterator outerScope = it;
1938 outerScope.pit() = outerScope.lastpit() + 2;
1939 updateMacros(it, outerScope);
1943 void Buffer::updateMacroInstances() const
1945 LYXERR(Debug::MACROS, "updateMacroInstances for "
1946 << d->filename.onlyFileName());
1947 DocIterator it = doc_iterator_begin(inset());
1948 DocIterator end = doc_iterator_end(inset());
1949 for (; it != end; it.forwardPos()) {
1950 // look for MathData cells in InsetMathNest insets
1951 Inset * inset = it.nextInset();
1955 InsetMath * minset = inset->asInsetMath();
1959 // update macro in all cells of the InsetMathNest
1960 DocIterator::idx_type n = minset->nargs();
1961 MacroContext mc = MacroContext(*this, it);
1962 for (DocIterator::idx_type i = 0; i < n; ++i) {
1963 MathData & data = minset->cell(i);
1964 data.updateMacros(0, mc);
1970 void Buffer::listMacroNames(MacroNameSet & macros) const
1975 d->macro_lock = true;
1977 // loop over macro names
1978 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
1979 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
1980 for (; nameIt != nameEnd; ++nameIt)
1981 macros.insert(nameIt->first);
1983 // loop over children
1984 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
1985 Impl::BufferPositionMap::iterator end = d->children_positions.end();
1986 for (; it != end; ++it)
1987 it->first->listMacroNames(macros);
1990 if (d->parent_buffer)
1991 d->parent_buffer->listMacroNames(macros);
1993 d->macro_lock = false;
1997 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
1999 if (!d->parent_buffer)
2003 d->parent_buffer->listMacroNames(names);
2006 MacroNameSet::iterator it = names.begin();
2007 MacroNameSet::iterator end = names.end();
2008 for (; it != end; ++it) {
2010 MacroData const * data =
2011 d->parent_buffer->getMacro(*it, *this, false);
2013 macros.insert(data);
2015 // we cannot access the original MathMacroTemplate anymore
2016 // here to calls validate method. So we do its work here manually.
2017 // FIXME: somehow make the template accessible here.
2018 if (data->optionals() > 0)
2019 features.require("xargs");
2025 Buffer::References & Buffer::references(docstring const & label)
2027 if (d->parent_buffer)
2028 return const_cast<Buffer *>(masterBuffer())->references(label);
2030 RefCache::iterator it = d->ref_cache_.find(label);
2031 if (it != d->ref_cache_.end())
2032 return it->second.second;
2034 static InsetLabel const * dummy_il = 0;
2035 static References const dummy_refs;
2036 it = d->ref_cache_.insert(
2037 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2038 return it->second.second;
2042 Buffer::References const & Buffer::references(docstring const & label) const
2044 return const_cast<Buffer *>(this)->references(label);
2048 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2050 masterBuffer()->d->ref_cache_[label].first = il;
2054 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2056 return masterBuffer()->d->ref_cache_[label].first;
2060 void Buffer::clearReferenceCache() const
2062 if (!d->parent_buffer)
2063 d->ref_cache_.clear();
2067 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2070 //FIXME: This does not work for child documents yet.
2071 BOOST_ASSERT(code == CITE_CODE);
2072 // Check if the label 'from' appears more than once
2073 vector<docstring> labels;
2076 keys.fillWithBibKeys(this);
2077 BiblioInfo::const_iterator bit = keys.begin();
2078 BiblioInfo::const_iterator bend = keys.end();
2080 for (; bit != bend; ++bit)
2082 labels.push_back(bit->first);
2085 if (count(labels.begin(), labels.end(), from) > 1)
2088 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2089 if (it->lyxCode() == code) {
2090 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2091 docstring const oldValue = inset.getParam(paramName);
2092 if (oldValue == from)
2093 inset.setParam(paramName, to);
2099 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2100 pit_type par_end, bool full_source)
2102 OutputParams runparams(¶ms().encoding());
2103 runparams.nice = true;
2104 runparams.flavor = OutputParams::LATEX;
2105 runparams.linelen = lyxrc.plaintext_linelen;
2106 // No side effect of file copying and image conversion
2107 runparams.dryrun = true;
2111 os << "% " << _("Preview source code") << "\n\n";
2112 d->texrow.newline();
2113 d->texrow.newline();
2115 writeLaTeXSource(os, filePath(), runparams, true, true);
2117 writeDocBookSource(os, absFileName(), runparams, false);
2119 runparams.par_begin = par_begin;
2120 runparams.par_end = par_end;
2121 if (par_begin + 1 == par_end) {
2123 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2127 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2128 convert<docstring>(par_begin),
2129 convert<docstring>(par_end - 1))
2132 d->texrow.newline();
2133 d->texrow.newline();
2134 // output paragraphs
2136 latexParagraphs(*this, text(), os, d->texrow, runparams);
2139 docbookParagraphs(paragraphs(), *this, os, runparams);
2144 ErrorList & Buffer::errorList(string const & type) const
2146 static ErrorList emptyErrorList;
2147 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2148 if (I == d->errorLists.end())
2149 return emptyErrorList;
2155 void Buffer::structureChanged() const
2158 gui_->structureChanged();
2162 void Buffer::errors(string const & err) const
2169 void Buffer::message(docstring const & msg) const
2176 void Buffer::setBusy(bool on) const
2183 void Buffer::setReadOnly(bool on) const
2186 d->wa_->setReadOnly(on);
2190 void Buffer::updateTitles() const
2193 d->wa_->updateTitles();
2197 void Buffer::resetAutosaveTimers() const
2200 gui_->resetAutosaveTimers();
2204 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2213 class AutoSaveBuffer : public ForkedProcess {
2216 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2217 : buffer_(buffer), fname_(fname) {}
2219 virtual boost::shared_ptr<ForkedProcess> clone() const
2221 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2226 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2227 from_utf8(fname_.absFilename())));
2228 return run(DontWait);
2232 virtual int generateChild();
2234 Buffer const & buffer_;
2239 int AutoSaveBuffer::generateChild()
2241 // tmp_ret will be located (usually) in /tmp
2242 // will that be a problem?
2243 // Note that this calls ForkedCalls::fork(), so it's
2244 // ok cross-platform.
2245 pid_t const pid = fork();
2246 // If you want to debug the autosave
2247 // you should set pid to -1, and comment out the fork.
2248 if (pid != 0 && pid != -1)
2251 // pid = -1 signifies that lyx was unable
2252 // to fork. But we will do the save
2254 bool failed = false;
2255 FileName const tmp_ret = FileName::tempName("lyxauto");
2256 if (!tmp_ret.empty()) {
2257 buffer_.writeFile(tmp_ret);
2258 // assume successful write of tmp_ret
2259 if (!tmp_ret.moveTo(fname_))
2265 // failed to write/rename tmp_ret so try writing direct
2266 if (!buffer_.writeFile(fname_)) {
2267 // It is dangerous to do this in the child,
2268 // but safe in the parent, so...
2269 if (pid == -1) // emit message signal.
2270 buffer_.message(_("Autosave failed!"));
2274 if (pid == 0) // we are the child so...
2283 // Perfect target for a thread...
2284 void Buffer::autoSave() const
2286 if (isBakClean() || isReadonly()) {
2287 // We don't save now, but we'll try again later
2288 resetAutosaveTimers();
2292 // emit message signal.
2293 message(_("Autosaving current document..."));
2295 // create autosave filename
2296 string fname = filePath();
2298 fname += d->filename.onlyFileName();
2301 AutoSaveBuffer autosave(*this, FileName(fname));
2305 resetAutosaveTimers();
2309 string Buffer::bufferFormat() const
2319 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2320 string & result_file) const
2322 string backend_format;
2323 OutputParams runparams(¶ms().encoding());
2324 runparams.flavor = OutputParams::LATEX;
2325 runparams.linelen = lyxrc.plaintext_linelen;
2326 vector<string> backs = backends();
2327 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2328 // Get shortest path to format
2329 Graph::EdgePath path;
2330 for (vector<string>::const_iterator it = backs.begin();
2331 it != backs.end(); ++it) {
2332 Graph::EdgePath p = theConverters().getPath(*it, format);
2333 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2334 backend_format = *it;
2339 runparams.flavor = theConverters().getFlavor(path);
2341 Alert::error(_("Couldn't export file"),
2342 bformat(_("No information for exporting the format %1$s."),
2343 formats.prettyName(format)));
2347 backend_format = format;
2348 // FIXME: Don't hardcode format names here, but use a flag
2349 if (backend_format == "pdflatex")
2350 runparams.flavor = OutputParams::PDFLATEX;
2353 string filename = latexName(false);
2354 filename = addName(temppath(), filename);
2355 filename = changeExtension(filename,
2356 formats.extension(backend_format));
2359 updateMacroInstances();
2361 // Plain text backend
2362 if (backend_format == "text")
2363 writePlaintextFile(*this, FileName(filename), runparams);
2365 else if (backend_format == "lyx")
2366 writeFile(FileName(filename));
2368 else if (isDocBook()) {
2369 runparams.nice = !put_in_tempdir;
2370 makeDocBookFile(FileName(filename), runparams);
2373 else if (backend_format == format) {
2374 runparams.nice = true;
2375 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2377 } else if (!lyxrc.tex_allows_spaces
2378 && contains(filePath(), ' ')) {
2379 Alert::error(_("File name error"),
2380 _("The directory path to the document cannot contain spaces."));
2383 runparams.nice = false;
2384 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2388 string const error_type = (format == "program")
2389 ? "Build" : bufferFormat();
2390 string const ext = formats.extension(format);
2391 FileName const tmp_result_file(changeExtension(filename, ext));
2392 bool const success = theConverters().convert(this, FileName(filename),
2393 tmp_result_file, FileName(absFileName()), backend_format, format,
2394 errorList(error_type));
2395 // Emit the signal to show the error list.
2396 if (format != backend_format)
2401 if (put_in_tempdir) {
2402 result_file = tmp_result_file.absFilename();
2406 result_file = changeExtension(absFileName(), ext);
2407 // We need to copy referenced files (e. g. included graphics
2408 // if format == "dvi") to the result dir.
2409 vector<ExportedFile> const files =
2410 runparams.exportdata->externalFiles(format);
2411 string const dest = onlyPath(result_file);
2412 CopyStatus status = SUCCESS;
2413 for (vector<ExportedFile>::const_iterator it = files.begin();
2414 it != files.end() && status != CANCEL; ++it) {
2415 string const fmt = formats.getFormatFromFile(it->sourceName);
2416 status = copyFile(fmt, it->sourceName,
2417 makeAbsPath(it->exportName, dest),
2418 it->exportName, status == FORCE);
2420 if (status == CANCEL) {
2421 message(_("Document export cancelled."));
2422 } else if (tmp_result_file.exists()) {
2423 // Finally copy the main file
2424 status = copyFile(format, tmp_result_file,
2425 FileName(result_file), result_file,
2427 message(bformat(_("Document exported as %1$s "
2429 formats.prettyName(format),
2430 makeDisplayPath(result_file)));
2432 // This must be a dummy converter like fax (bug 1888)
2433 message(bformat(_("Document exported as %1$s"),
2434 formats.prettyName(format)));
2441 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2444 return doExport(format, put_in_tempdir, result_file);
2448 bool Buffer::preview(string const & format) const
2451 if (!doExport(format, true, result_file))
2453 return formats.view(*this, FileName(result_file), format);
2457 bool Buffer::isExportable(string const & format) const
2459 vector<string> backs = backends();
2460 for (vector<string>::const_iterator it = backs.begin();
2461 it != backs.end(); ++it)
2462 if (theConverters().isReachable(*it, format))
2468 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2470 vector<string> backs = backends();
2471 vector<Format const *> result =
2472 theConverters().getReachable(backs[0], only_viewable, true);
2473 for (vector<string>::const_iterator it = backs.begin() + 1;
2474 it != backs.end(); ++it) {
2475 vector<Format const *> r =
2476 theConverters().getReachable(*it, only_viewable, false);
2477 result.insert(result.end(), r.begin(), r.end());
2483 vector<string> Buffer::backends() const
2486 if (params().baseClass()->isTeXClassAvailable()) {
2487 v.push_back(bufferFormat());
2488 // FIXME: Don't hardcode format names here, but use a flag
2489 if (v.back() == "latex")
2490 v.push_back("pdflatex");
2492 v.push_back("text");
2498 bool Buffer::readFileHelper(FileName const & s)
2500 // File information about normal file
2502 docstring const file = makeDisplayPath(s.absFilename(), 50);
2503 docstring text = bformat(_("The specified document\n%1$s"
2504 "\ncould not be read."), file);
2505 Alert::error(_("Could not read document"), text);
2509 // Check if emergency save file exists and is newer.
2510 FileName const e(s.absFilename() + ".emergency");
2512 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2513 docstring const file = makeDisplayPath(s.absFilename(), 20);
2514 docstring const text =
2515 bformat(_("An emergency save of the document "
2517 "Recover emergency save?"), file);
2518 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2519 _("&Recover"), _("&Load Original"),
2523 // the file is not saved if we load the emergency file.
2533 // Now check if autosave file is newer.
2534 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2536 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2537 docstring const file = makeDisplayPath(s.absFilename(), 20);
2538 docstring const text =
2539 bformat(_("The backup of the document "
2540 "%1$s is newer.\n\nLoad the "
2541 "backup instead?"), file);
2542 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2543 _("&Load backup"), _("Load &original"),
2547 // the file is not saved if we load the autosave file.
2551 // Here we delete the autosave
2562 bool Buffer::loadLyXFile(FileName const & s)
2564 if (s.isReadableFile()) {
2565 if (readFileHelper(s)) {
2566 lyxvc().file_found_hook(s);
2567 if (!s.isWritable())
2572 docstring const file = makeDisplayPath(s.absFilename(), 20);
2573 // Here we probably should run
2574 if (LyXVC::file_not_found_hook(s)) {
2575 docstring const text =
2576 bformat(_("Do you want to retrieve the document"
2577 " %1$s from version control?"), file);
2578 int const ret = Alert::prompt(_("Retrieve from version control?"),
2579 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2582 // How can we know _how_ to do the checkout?
2583 // With the current VC support it has to be,
2584 // a RCS file since CVS do not have special ,v files.
2586 return loadLyXFile(s);
2594 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2596 TeXErrors::Errors::const_iterator cit = terr.begin();
2597 TeXErrors::Errors::const_iterator end = terr.end();
2599 for (; cit != end; ++cit) {
2602 int errorRow = cit->error_in_line;
2603 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2609 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2610 } while (found && id_start == id_end && pos_start == pos_end);
2612 errorList.push_back(ErrorItem(cit->error_desc,
2613 cit->error_text, id_start, pos_start, pos_end));