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 = 323;
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");
1106 // There are a few differences between nice LaTeX and usual files:
1107 // usual is \batchmode and has a
1108 // special input@path to allow the including of figures
1109 // with either \input or \includegraphics (what figinsets do).
1110 // input@path is set when the actual parameter
1111 // original_path is set. This is done for usual tex-file, but not
1112 // for nice-latex-file. (Matthias 250696)
1113 // Note that input@path is only needed for something the user does
1114 // in the preamble, included .tex files or ERT, files included by
1115 // LyX work without it.
1116 if (output_preamble) {
1117 if (!runparams.nice) {
1118 // code for usual, NOT nice-latex-file
1119 os << "\\batchmode\n"; // changed
1120 // from \nonstopmode
1121 d->texrow.newline();
1123 if (!original_path.empty()) {
1125 // We don't know the encoding of inputpath
1126 docstring const inputpath = from_utf8(latex_path(original_path));
1127 os << "\\makeatletter\n"
1128 << "\\def\\input@path{{"
1129 << inputpath << "/}}\n"
1130 << "\\makeatother\n";
1131 d->texrow.newline();
1132 d->texrow.newline();
1133 d->texrow.newline();
1136 // Write the preamble
1137 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1143 os << "\\begin{document}\n";
1144 d->texrow.newline();
1145 } // output_preamble
1147 d->texrow.start(paragraphs().begin()->id(), 0);
1149 LYXERR(Debug::INFO, "preamble finished, now the body.");
1151 // Don't move this behind the parent_buffer=0 code below,
1152 // because then the macros will not get the right "redefinition"
1153 // flag as they don't see the parent macros which are output before.
1156 // fold macros if possible, still with parent buffer as the
1157 // macros will be put in the prefix anyway.
1158 updateMacroInstances();
1160 // if we are doing a real file with body, even if this is the
1161 // child of some other buffer, let's cut the link here.
1162 // This happens for example if only a child document is printed.
1163 Buffer const * save_parent = 0;
1164 if (output_preamble) {
1165 // output the macros visible for this buffer
1166 writeParentMacros(os);
1168 save_parent = d->parent_buffer;
1169 d->parent_buffer = 0;
1173 latexParagraphs(*this, text(), os, d->texrow, runparams);
1175 // Restore the parenthood if needed
1176 if (output_preamble) {
1177 d->parent_buffer = save_parent;
1179 // restore macros with correct parent buffer (especially
1180 // important for the redefinition flag which depends on the
1185 // add this just in case after all the paragraphs
1187 d->texrow.newline();
1189 if (output_preamble) {
1190 os << "\\end{document}\n";
1191 d->texrow.newline();
1192 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1194 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1196 runparams_in.encoding = runparams.encoding;
1198 // Just to be sure. (Asger)
1199 d->texrow.newline();
1201 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1202 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1206 bool Buffer::isLatex() const
1208 return params().documentClass().outputType() == LATEX;
1212 bool Buffer::isLiterate() const
1214 return params().documentClass().outputType() == LITERATE;
1218 bool Buffer::isDocBook() const
1220 return params().documentClass().outputType() == DOCBOOK;
1224 void Buffer::makeDocBookFile(FileName const & fname,
1225 OutputParams const & runparams,
1226 bool const body_only) const
1228 LYXERR(Debug::LATEX, "makeDocBookFile...");
1231 if (!openFileWrite(ofs, fname))
1234 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1238 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1242 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1243 OutputParams const & runparams,
1244 bool const only_body) const
1246 LaTeXFeatures features(*this, params(), runparams);
1251 DocumentClass const & tclass = params().documentClass();
1252 string const top_element = tclass.latexname();
1255 if (runparams.flavor == OutputParams::XML)
1256 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1259 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1262 if (! tclass.class_header().empty())
1263 os << from_ascii(tclass.class_header());
1264 else if (runparams.flavor == OutputParams::XML)
1265 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1266 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1268 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1270 docstring preamble = from_utf8(params().preamble);
1271 if (runparams.flavor != OutputParams::XML ) {
1272 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1273 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1274 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1275 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1278 string const name = runparams.nice
1279 ? changeExtension(absFileName(), ".sgml") : fname;
1280 preamble += features.getIncludedFiles(name);
1281 preamble += features.getLyXSGMLEntities();
1283 if (!preamble.empty()) {
1284 os << "\n [ " << preamble << " ]";
1289 string top = top_element;
1291 if (runparams.flavor == OutputParams::XML)
1292 top += params().language->code();
1294 top += params().language->code().substr(0,2);
1297 if (!params().options.empty()) {
1299 top += params().options;
1302 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1303 << " file was created by LyX " << lyx_version
1304 << "\n See http://www.lyx.org/ for more information -->\n";
1306 params().documentClass().counters().reset();
1310 sgml::openTag(os, top);
1312 docbookParagraphs(paragraphs(), *this, os, runparams);
1313 sgml::closeTag(os, top_element);
1317 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1318 // Other flags: -wall -v0 -x
1319 int Buffer::runChktex()
1323 // get LaTeX-Filename
1324 FileName const path(temppath());
1325 string const name = addName(path.absFilename(), latexName());
1326 string const org_path = filePath();
1328 PathChanger p(path); // path to LaTeX file
1329 message(_("Running chktex..."));
1331 // Generate the LaTeX file if neccessary
1332 OutputParams runparams(¶ms().encoding());
1333 runparams.flavor = OutputParams::LATEX;
1334 runparams.nice = false;
1335 makeLaTeXFile(FileName(name), org_path, runparams);
1338 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1339 int const res = chktex.run(terr); // run chktex
1342 Alert::error(_("chktex failure"),
1343 _("Could not run chktex successfully."));
1344 } else if (res > 0) {
1345 ErrorList & errlist = d->errorLists["ChkTeX"];
1347 bufferErrors(terr, errlist);
1358 void Buffer::validate(LaTeXFeatures & features) const
1360 params().validate(features);
1364 for_each(paragraphs().begin(), paragraphs().end(),
1365 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1367 if (lyxerr.debugging(Debug::LATEX)) {
1368 features.showStruct();
1373 void Buffer::getLabelList(vector<docstring> & list) const
1375 // If this is a child document, use the parent's list instead.
1376 if (d->parent_buffer) {
1377 d->parent_buffer->getLabelList(list);
1382 Toc & toc = d->toc_backend.toc("label");
1383 TocIterator toc_it = toc.begin();
1384 TocIterator end = toc.end();
1385 for (; toc_it != end; ++toc_it) {
1386 if (toc_it->depth() == 0)
1387 list.push_back(toc_it->str());
1392 void Buffer::updateBibfilesCache() const
1394 // If this is a child document, use the parent's cache instead.
1395 if (d->parent_buffer) {
1396 d->parent_buffer->updateBibfilesCache();
1400 d->bibfilesCache_.clear();
1401 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1402 if (it->lyxCode() == BIBTEX_CODE) {
1403 InsetBibtex const & inset =
1404 static_cast<InsetBibtex const &>(*it);
1405 EmbeddedFileList const bibfiles = inset.embeddedFiles();
1406 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1409 } else if (it->lyxCode() == INCLUDE_CODE) {
1410 InsetInclude & inset =
1411 static_cast<InsetInclude &>(*it);
1412 inset.updateBibfilesCache();
1413 EmbeddedFileList const & bibfiles =
1414 inset.getBibfilesCache(*this);
1415 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1423 EmbeddedFileList const & Buffer::getBibfilesCache() const
1425 // If this is a child document, use the parent's cache instead.
1426 if (d->parent_buffer)
1427 return d->parent_buffer->getBibfilesCache();
1429 // We update the cache when first used instead of at loading time.
1430 if (d->bibfilesCache_.empty())
1431 const_cast<Buffer *>(this)->updateBibfilesCache();
1433 return d->bibfilesCache_;
1437 bool Buffer::isDepClean(string const & name) const
1439 DepClean::const_iterator const it = d->dep_clean.find(name);
1440 if (it == d->dep_clean.end())
1446 void Buffer::markDepClean(string const & name)
1448 d->dep_clean[name] = true;
1452 bool Buffer::dispatch(string const & command, bool * result)
1454 return dispatch(lyxaction.lookupFunc(command), result);
1458 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1460 bool dispatched = true;
1462 switch (func.action) {
1463 case LFUN_BUFFER_EXPORT: {
1464 bool const tmp = doExport(to_utf8(func.argument()), false);
1477 void Buffer::changeLanguage(Language const * from, Language const * to)
1482 for_each(par_iterator_begin(),
1484 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1488 bool Buffer::isMultiLingual() const
1490 ParConstIterator end = par_iterator_end();
1491 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1492 if (it->isMultiLingual(params()))
1499 DocIterator Buffer::getParFromID(int const id) const
1502 // John says this is called with id == -1 from undo
1503 lyxerr << "getParFromID(), id: " << id << endl;
1504 return doc_iterator_end(inset());
1507 for (DocIterator it = doc_iterator_begin(inset()); !it.atEnd(); it.forwardPar())
1508 if (it.paragraph().id() == id)
1511 return doc_iterator_end(inset());
1515 bool Buffer::hasParWithID(int const id) const
1517 return !getParFromID(id).atEnd();
1521 ParIterator Buffer::par_iterator_begin()
1523 return ParIterator(doc_iterator_begin(inset()));
1527 ParIterator Buffer::par_iterator_end()
1529 return ParIterator(doc_iterator_end(inset()));
1533 ParConstIterator Buffer::par_iterator_begin() const
1535 return lyx::par_const_iterator_begin(inset());
1539 ParConstIterator Buffer::par_iterator_end() const
1541 return lyx::par_const_iterator_end(inset());
1545 Language const * Buffer::language() const
1547 return params().language;
1551 docstring const Buffer::B_(string const & l10n) const
1553 return params().B_(l10n);
1557 bool Buffer::isClean() const
1559 return d->lyx_clean;
1563 bool Buffer::isBakClean() const
1565 return d->bak_clean;
1569 bool Buffer::isExternallyModified(CheckMethod method) const
1571 BOOST_ASSERT(d->filename.exists());
1572 // if method == timestamp, check timestamp before checksum
1573 return (method == checksum_method
1574 || d->timestamp_ != d->filename.lastModified())
1575 && d->checksum_ != d->filename.checksum();
1579 void Buffer::saveCheckSum(FileName const & file) const
1581 if (file.exists()) {
1582 d->timestamp_ = file.lastModified();
1583 d->checksum_ = file.checksum();
1585 // in the case of save to a new file.
1592 void Buffer::markClean() const
1594 if (!d->lyx_clean) {
1595 d->lyx_clean = true;
1598 // if the .lyx file has been saved, we don't need an
1600 d->bak_clean = true;
1604 void Buffer::markBakClean() const
1606 d->bak_clean = true;
1610 void Buffer::setUnnamed(bool flag)
1616 bool Buffer::isUnnamed() const
1622 // FIXME: this function should be moved to buffer_pimpl.C
1623 void Buffer::markDirty()
1626 d->lyx_clean = false;
1629 d->bak_clean = false;
1631 DepClean::iterator it = d->dep_clean.begin();
1632 DepClean::const_iterator const end = d->dep_clean.end();
1634 for (; it != end; ++it)
1639 FileName Buffer::fileName() const
1645 string Buffer::absFileName() const
1647 return d->filename.absFilename();
1651 string Buffer::filePath() const
1653 return d->filename.onlyPath().absFilename() + "/";
1657 bool Buffer::isReadonly() const
1659 return d->read_only;
1663 void Buffer::setParent(Buffer const * buffer)
1665 // Avoids recursive include.
1666 d->parent_buffer = buffer == this ? 0 : buffer;
1671 Buffer const * Buffer::parent()
1673 return d->parent_buffer;
1677 Buffer const * Buffer::masterBuffer() const
1679 if (!d->parent_buffer)
1682 return d->parent_buffer->masterBuffer();
1686 template<typename M>
1687 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
1692 typename M::iterator it = m.lower_bound(x);
1693 if (it == m.begin())
1701 MacroData const * Buffer::getBufferMacro(docstring const & name,
1702 DocIterator const & pos) const
1704 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
1706 // if paragraphs have no macro context set, pos will be empty
1710 // we haven't found anything yet
1711 DocIterator bestPos = par_iterator_begin();
1712 MacroData const * bestData = 0;
1714 // find macro definitions for name
1715 Impl::NamePositionScopeMacroMap::iterator nameIt
1716 = d->macros.find(name);
1717 if (nameIt != d->macros.end()) {
1718 // find last definition in front of pos or at pos itself
1719 Impl::PositionScopeMacroMap::const_iterator it
1720 = greatest_below(nameIt->second, pos);
1721 if (it != nameIt->second.end()) {
1723 // scope ends behind pos?
1724 if (pos < it->second.first) {
1725 // Looks good, remember this. If there
1726 // is no external macro behind this,
1727 // we found the right one already.
1728 bestPos = it->first;
1729 bestData = &it->second.second;
1733 // try previous macro if there is one
1734 if (it == nameIt->second.begin())
1741 // find macros in included files
1742 Impl::PositionScopeBufferMap::const_iterator it
1743 = greatest_below(d->position_to_children, pos);
1744 if (it == d->position_to_children.end())
1745 // no children before
1749 // do we know something better (i.e. later) already?
1750 if (it->first < bestPos )
1753 // scope ends behind pos?
1754 if (pos < it->second.first) {
1755 // look for macro in external file
1756 d->macro_lock = true;
1757 MacroData const * data
1758 = it->second.second->getMacro(name, false);
1759 d->macro_lock = false;
1761 bestPos = it->first;
1767 // try previous file if there is one
1768 if (it == d->position_to_children.begin())
1773 // return the best macro we have found
1778 MacroData const * Buffer::getMacro(docstring const & name,
1779 DocIterator const & pos, bool global) const
1784 // query buffer macros
1785 MacroData const * data = getBufferMacro(name, pos);
1789 // If there is a master buffer, query that
1790 if (d->parent_buffer) {
1791 d->macro_lock = true;
1792 MacroData const * macro = d->parent_buffer->getMacro(
1793 name, *this, false);
1794 d->macro_lock = false;
1800 data = MacroTable::globalMacros().get(name);
1809 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
1811 // set scope end behind the last paragraph
1812 DocIterator scope = par_iterator_begin();
1813 scope.pit() = scope.lastpit() + 1;
1815 return getMacro(name, scope, global);
1819 MacroData const * Buffer::getMacro(docstring const & name,
1820 Buffer const & child, bool global) const
1822 // look where the child buffer is included first
1823 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
1824 if (it == d->children_positions.end())
1827 // check for macros at the inclusion position
1828 return getMacro(name, it->second, global);
1832 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
1834 pit_type lastpit = it.lastpit();
1836 // look for macros in each paragraph
1837 while (it.pit() <= lastpit) {
1838 Paragraph & par = it.paragraph();
1840 // iterate over the insets of the current paragraph
1841 InsetList const & insets = par.insetList();
1842 InsetList::const_iterator iit = insets.begin();
1843 InsetList::const_iterator end = insets.end();
1844 for (; iit != end; ++iit) {
1845 it.pos() = iit->pos;
1847 // is it a nested text inset?
1848 if (iit->inset->asInsetText()) {
1849 // Inset needs its own scope?
1850 InsetText const * itext
1851 = iit->inset->asInsetText();
1852 bool newScope = itext->isMacroScope();
1854 // scope which ends just behind the inset
1855 DocIterator insetScope = it;
1858 // collect macros in inset
1859 it.push_back(CursorSlice(*iit->inset));
1860 updateMacros(it, newScope ? insetScope : scope);
1865 // is it an external file?
1866 if (iit->inset->lyxCode() == INCLUDE_CODE) {
1867 // get buffer of external file
1868 InsetCommand const & inset
1869 = static_cast<InsetCommand const &>(*iit->inset);
1870 InsetCommandParams const & ip = inset.params();
1871 d->macro_lock = true;
1872 Buffer * child = loadIfNeeded(*this, ip);
1873 d->macro_lock = false;
1877 // register its position, but only when it is
1878 // included first in the buffer
1879 if (d->children_positions.find(child)
1880 == d->children_positions.end())
1881 d->children_positions[child] = it;
1883 // register child with its scope
1884 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
1888 if (iit->inset->lyxCode() != MATHMACRO_CODE)
1892 MathMacroTemplate & macroTemplate
1893 = static_cast<MathMacroTemplate &>(*iit->inset);
1894 MacroContext mc(*this, it);
1895 macroTemplate.updateToContext(mc);
1898 bool valid = macroTemplate.validMacro();
1899 // FIXME: Should be fixNameAndCheckIfValid() in fact,
1900 // then the BufferView's cursor will be invalid in
1901 // some cases which leads to crashes.
1906 d->macros[macroTemplate.name()][it] =
1907 Impl::ScopeMacro(scope, MacroData(*this, it));
1917 void Buffer::updateMacros() const
1922 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
1924 // start with empty table
1926 d->children_positions.clear();
1927 d->position_to_children.clear();
1929 // Iterate over buffer, starting with first paragraph
1930 // The scope must be bigger than any lookup DocIterator
1931 // later. For the global lookup, lastpit+1 is used, hence
1932 // we use lastpit+2 here.
1933 DocIterator it = par_iterator_begin();
1934 DocIterator outerScope = it;
1935 outerScope.pit() = outerScope.lastpit() + 2;
1936 updateMacros(it, outerScope);
1940 void Buffer::updateMacroInstances() const
1942 LYXERR(Debug::MACROS, "updateMacroInstances for "
1943 << d->filename.onlyFileName());
1944 DocIterator it = doc_iterator_begin(inset());
1945 DocIterator end = doc_iterator_end(inset());
1946 for (; it != end; it.forwardPos()) {
1947 // look for MathData cells in InsetMathNest insets
1948 Inset * inset = it.nextInset();
1952 InsetMath * minset = inset->asInsetMath();
1956 // update macro in all cells of the InsetMathNest
1957 DocIterator::idx_type n = minset->nargs();
1958 MacroContext mc = MacroContext(*this, it);
1959 for (DocIterator::idx_type i = 0; i < n; ++i) {
1960 MathData & data = minset->cell(i);
1961 data.updateMacros(0, mc);
1967 void Buffer::listMacroNames(MacroNameSet & macros) const
1972 d->macro_lock = true;
1974 // loop over macro names
1975 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
1976 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
1977 for (; nameIt != nameEnd; ++nameIt)
1978 macros.insert(nameIt->first);
1980 // loop over children
1981 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
1982 Impl::BufferPositionMap::iterator end = d->children_positions.end();
1983 for (; it != end; ++it)
1984 it->first->listMacroNames(macros);
1987 if (d->parent_buffer)
1988 d->parent_buffer->listMacroNames(macros);
1990 d->macro_lock = false;
1994 void Buffer::writeParentMacros(odocstream & os) const
1996 if (!d->parent_buffer)
1999 // collect macro names
2001 d->parent_buffer->listMacroNames(names);
2003 // resolve and output them
2004 MacroNameSet::iterator it = names.begin();
2005 MacroNameSet::iterator end = names.end();
2006 for (; it != end; ++it) {
2008 MacroData const * data =
2009 d->parent_buffer->getMacro(*it, *this, false);
2011 data->write(os, true);
2016 Buffer::References & Buffer::references(docstring const & label)
2018 if (d->parent_buffer)
2019 return const_cast<Buffer *>(masterBuffer())->references(label);
2021 RefCache::iterator it = d->ref_cache_.find(label);
2022 if (it != d->ref_cache_.end())
2023 return it->second.second;
2025 static InsetLabel const * dummy_il = 0;
2026 static References const dummy_refs;
2027 it = d->ref_cache_.insert(
2028 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2029 return it->second.second;
2033 Buffer::References const & Buffer::references(docstring const & label) const
2035 return const_cast<Buffer *>(this)->references(label);
2039 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2041 masterBuffer()->d->ref_cache_[label].first = il;
2045 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2047 return masterBuffer()->d->ref_cache_[label].first;
2051 void Buffer::clearReferenceCache() const
2053 if (!d->parent_buffer)
2054 d->ref_cache_.clear();
2058 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2061 //FIXME: This does not work for child documents yet.
2062 BOOST_ASSERT(code == CITE_CODE);
2063 // Check if the label 'from' appears more than once
2064 vector<docstring> labels;
2067 keys.fillWithBibKeys(this);
2068 BiblioInfo::const_iterator bit = keys.begin();
2069 BiblioInfo::const_iterator bend = keys.end();
2071 for (; bit != bend; ++bit)
2073 labels.push_back(bit->first);
2076 if (count(labels.begin(), labels.end(), from) > 1)
2079 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2080 if (it->lyxCode() == code) {
2081 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2082 docstring const oldValue = inset.getParam(paramName);
2083 if (oldValue == from)
2084 inset.setParam(paramName, to);
2090 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2091 pit_type par_end, bool full_source)
2093 OutputParams runparams(¶ms().encoding());
2094 runparams.nice = true;
2095 runparams.flavor = OutputParams::LATEX;
2096 runparams.linelen = lyxrc.plaintext_linelen;
2097 // No side effect of file copying and image conversion
2098 runparams.dryrun = true;
2102 os << "% " << _("Preview source code") << "\n\n";
2103 d->texrow.newline();
2104 d->texrow.newline();
2106 writeLaTeXSource(os, filePath(), runparams, true, true);
2108 writeDocBookSource(os, absFileName(), runparams, false);
2110 runparams.par_begin = par_begin;
2111 runparams.par_end = par_end;
2112 if (par_begin + 1 == par_end) {
2114 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2118 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2119 convert<docstring>(par_begin),
2120 convert<docstring>(par_end - 1))
2123 d->texrow.newline();
2124 d->texrow.newline();
2125 // output paragraphs
2127 latexParagraphs(*this, text(), os, d->texrow, runparams);
2130 docbookParagraphs(paragraphs(), *this, os, runparams);
2135 ErrorList & Buffer::errorList(string const & type) const
2137 static ErrorList emptyErrorList;
2138 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2139 if (I == d->errorLists.end())
2140 return emptyErrorList;
2146 void Buffer::structureChanged() const
2149 gui_->structureChanged();
2153 void Buffer::errors(string const & err) const
2160 void Buffer::message(docstring const & msg) const
2167 void Buffer::setBusy(bool on) const
2174 void Buffer::setReadOnly(bool on) const
2177 d->wa_->setReadOnly(on);
2181 void Buffer::updateTitles() const
2184 d->wa_->updateTitles();
2188 void Buffer::resetAutosaveTimers() const
2191 gui_->resetAutosaveTimers();
2195 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2204 class AutoSaveBuffer : public ForkedProcess {
2207 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2208 : buffer_(buffer), fname_(fname) {}
2210 virtual boost::shared_ptr<ForkedProcess> clone() const
2212 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2217 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2218 from_utf8(fname_.absFilename())));
2219 return run(DontWait);
2223 virtual int generateChild();
2225 Buffer const & buffer_;
2230 int AutoSaveBuffer::generateChild()
2232 // tmp_ret will be located (usually) in /tmp
2233 // will that be a problem?
2234 // Note that this calls ForkedCalls::fork(), so it's
2235 // ok cross-platform.
2236 pid_t const pid = fork();
2237 // If you want to debug the autosave
2238 // you should set pid to -1, and comment out the fork.
2239 if (pid != 0 && pid != -1)
2242 // pid = -1 signifies that lyx was unable
2243 // to fork. But we will do the save
2245 bool failed = false;
2246 FileName const tmp_ret = FileName::tempName("lyxauto");
2247 if (!tmp_ret.empty()) {
2248 buffer_.writeFile(tmp_ret);
2249 // assume successful write of tmp_ret
2250 if (!tmp_ret.moveTo(fname_))
2256 // failed to write/rename tmp_ret so try writing direct
2257 if (!buffer_.writeFile(fname_)) {
2258 // It is dangerous to do this in the child,
2259 // but safe in the parent, so...
2260 if (pid == -1) // emit message signal.
2261 buffer_.message(_("Autosave failed!"));
2265 if (pid == 0) // we are the child so...
2274 // Perfect target for a thread...
2275 void Buffer::autoSave() const
2277 if (isBakClean() || isReadonly()) {
2278 // We don't save now, but we'll try again later
2279 resetAutosaveTimers();
2283 // emit message signal.
2284 message(_("Autosaving current document..."));
2286 // create autosave filename
2287 string fname = filePath();
2289 fname += d->filename.onlyFileName();
2292 AutoSaveBuffer autosave(*this, FileName(fname));
2296 resetAutosaveTimers();
2300 string Buffer::bufferFormat() const
2310 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2311 string & result_file) const
2313 string backend_format;
2314 OutputParams runparams(¶ms().encoding());
2315 runparams.flavor = OutputParams::LATEX;
2316 runparams.linelen = lyxrc.plaintext_linelen;
2317 vector<string> backs = backends();
2318 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2319 // Get shortest path to format
2320 Graph::EdgePath path;
2321 for (vector<string>::const_iterator it = backs.begin();
2322 it != backs.end(); ++it) {
2323 Graph::EdgePath p = theConverters().getPath(*it, format);
2324 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2325 backend_format = *it;
2330 runparams.flavor = theConverters().getFlavor(path);
2332 Alert::error(_("Couldn't export file"),
2333 bformat(_("No information for exporting the format %1$s."),
2334 formats.prettyName(format)));
2338 backend_format = format;
2339 // FIXME: Don't hardcode format names here, but use a flag
2340 if (backend_format == "pdflatex")
2341 runparams.flavor = OutputParams::PDFLATEX;
2344 string filename = latexName(false);
2345 filename = addName(temppath(), filename);
2346 filename = changeExtension(filename,
2347 formats.extension(backend_format));
2350 updateMacroInstances();
2352 // Plain text backend
2353 if (backend_format == "text")
2354 writePlaintextFile(*this, FileName(filename), runparams);
2356 else if (backend_format == "lyx")
2357 writeFile(FileName(filename));
2359 else if (isDocBook()) {
2360 runparams.nice = !put_in_tempdir;
2361 makeDocBookFile(FileName(filename), runparams);
2364 else if (backend_format == format) {
2365 runparams.nice = true;
2366 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2368 } else if (!lyxrc.tex_allows_spaces
2369 && contains(filePath(), ' ')) {
2370 Alert::error(_("File name error"),
2371 _("The directory path to the document cannot contain spaces."));
2374 runparams.nice = false;
2375 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2379 string const error_type = (format == "program")
2380 ? "Build" : bufferFormat();
2381 string const ext = formats.extension(format);
2382 FileName const tmp_result_file(changeExtension(filename, ext));
2383 bool const success = theConverters().convert(this, FileName(filename),
2384 tmp_result_file, FileName(absFileName()), backend_format, format,
2385 errorList(error_type));
2386 // Emit the signal to show the error list.
2387 if (format != backend_format)
2392 if (put_in_tempdir) {
2393 result_file = tmp_result_file.absFilename();
2397 result_file = changeExtension(absFileName(), ext);
2398 // We need to copy referenced files (e. g. included graphics
2399 // if format == "dvi") to the result dir.
2400 vector<ExportedFile> const files =
2401 runparams.exportdata->externalFiles(format);
2402 string const dest = onlyPath(result_file);
2403 CopyStatus status = SUCCESS;
2404 for (vector<ExportedFile>::const_iterator it = files.begin();
2405 it != files.end() && status != CANCEL; ++it) {
2406 string const fmt = formats.getFormatFromFile(it->sourceName);
2407 status = copyFile(fmt, it->sourceName,
2408 makeAbsPath(it->exportName, dest),
2409 it->exportName, status == FORCE);
2411 if (status == CANCEL) {
2412 message(_("Document export cancelled."));
2413 } else if (tmp_result_file.exists()) {
2414 // Finally copy the main file
2415 status = copyFile(format, tmp_result_file,
2416 FileName(result_file), result_file,
2418 message(bformat(_("Document exported as %1$s "
2420 formats.prettyName(format),
2421 makeDisplayPath(result_file)));
2423 // This must be a dummy converter like fax (bug 1888)
2424 message(bformat(_("Document exported as %1$s"),
2425 formats.prettyName(format)));
2432 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2435 return doExport(format, put_in_tempdir, result_file);
2439 bool Buffer::preview(string const & format) const
2442 if (!doExport(format, true, result_file))
2444 return formats.view(*this, FileName(result_file), format);
2448 bool Buffer::isExportable(string const & format) const
2450 vector<string> backs = backends();
2451 for (vector<string>::const_iterator it = backs.begin();
2452 it != backs.end(); ++it)
2453 if (theConverters().isReachable(*it, format))
2459 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2461 vector<string> backs = backends();
2462 vector<Format const *> result =
2463 theConverters().getReachable(backs[0], only_viewable, true);
2464 for (vector<string>::const_iterator it = backs.begin() + 1;
2465 it != backs.end(); ++it) {
2466 vector<Format const *> r =
2467 theConverters().getReachable(*it, only_viewable, false);
2468 result.insert(result.end(), r.begin(), r.end());
2474 vector<string> Buffer::backends() const
2477 if (params().baseClass()->isTeXClassAvailable()) {
2478 v.push_back(bufferFormat());
2479 // FIXME: Don't hardcode format names here, but use a flag
2480 if (v.back() == "latex")
2481 v.push_back("pdflatex");
2483 v.push_back("text");
2489 bool Buffer::readFileHelper(FileName const & s)
2491 // File information about normal file
2493 docstring const file = makeDisplayPath(s.absFilename(), 50);
2494 docstring text = bformat(_("The specified document\n%1$s"
2495 "\ncould not be read."), file);
2496 Alert::error(_("Could not read document"), text);
2500 // Check if emergency save file exists and is newer.
2501 FileName const e(s.absFilename() + ".emergency");
2503 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2504 docstring const file = makeDisplayPath(s.absFilename(), 20);
2505 docstring const text =
2506 bformat(_("An emergency save of the document "
2508 "Recover emergency save?"), file);
2509 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2510 _("&Recover"), _("&Load Original"),
2514 // the file is not saved if we load the emergency file.
2524 // Now check if autosave file is newer.
2525 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2527 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2528 docstring const file = makeDisplayPath(s.absFilename(), 20);
2529 docstring const text =
2530 bformat(_("The backup of the document "
2531 "%1$s is newer.\n\nLoad the "
2532 "backup instead?"), file);
2533 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2534 _("&Load backup"), _("Load &original"),
2538 // the file is not saved if we load the autosave file.
2542 // Here we delete the autosave
2553 bool Buffer::loadLyXFile(FileName const & s)
2555 if (s.isReadableFile()) {
2556 if (readFileHelper(s)) {
2557 lyxvc().file_found_hook(s);
2558 if (!s.isWritable())
2563 docstring const file = makeDisplayPath(s.absFilename(), 20);
2564 // Here we probably should run
2565 if (LyXVC::file_not_found_hook(s)) {
2566 docstring const text =
2567 bformat(_("Do you want to retrieve the document"
2568 " %1$s from version control?"), file);
2569 int const ret = Alert::prompt(_("Retrieve from version control?"),
2570 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2573 // How can we know _how_ to do the checkout?
2574 // With the current VC support it has to be,
2575 // a RCS file since CVS do not have special ,v files.
2577 return loadLyXFile(s);
2585 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2587 TeXErrors::Errors::const_iterator cit = terr.begin();
2588 TeXErrors::Errors::const_iterator end = terr.end();
2590 for (; cit != end; ++cit) {
2593 int errorRow = cit->error_in_line;
2594 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2600 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2601 } while (found && id_start == id_end && pos_start == pos_end);
2603 errorList.push_back(ErrorItem(cit->error_desc,
2604 cit->error_text, id_start, pos_start, pos_end));