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"
57 #include "TexStream.h"
59 #include "TextClass.h"
60 #include "TocBackend.h"
62 #include "VCBackend.h"
66 #include "insets/InsetBibitem.h"
67 #include "insets/InsetBibtex.h"
68 #include "insets/InsetInclude.h"
69 #include "insets/InsetText.h"
71 #include "mathed/MacroTable.h"
72 #include "mathed/MathMacroTemplate.h"
73 #include "mathed/MathSupport.h"
75 #include "frontends/alert.h"
76 #include "frontends/Delegates.h"
77 #include "frontends/WorkAreaManager.h"
79 #include "graphics/Previews.h"
81 #include "support/convert.h"
82 #include "support/debug.h"
83 #include "support/ExceptionMessage.h"
84 #include "support/FileName.h"
85 #include "support/FileNameList.h"
86 #include "support/filetools.h"
87 #include "support/ForkedCalls.h"
88 #include "support/gettext.h"
89 #include "support/gzstream.h"
90 #include "support/lstrings.h"
91 #include "support/lyxalgo.h"
92 #include "support/os.h"
93 #include "support/Package.h"
94 #include "support/Path.h"
95 #include "support/textutils.h"
96 #include "support/types.h"
97 #include "support/FileZipListDir.h"
99 #include <boost/bind.hpp>
100 #include <boost/shared_ptr.hpp>
111 using namespace lyx::support;
115 namespace Alert = frontend::Alert;
116 namespace os = support::os;
120 int const LYX_FORMAT = 318;
122 typedef map<string, bool> DepClean;
123 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
130 Impl(Buffer & parent, FileName const & file, bool readonly);
143 mutable TexRow texrow;
144 Buffer const * parent_buffer;
146 /// need to regenerate .tex?
150 mutable bool lyx_clean;
152 /// is autosave needed?
153 mutable bool bak_clean;
155 /// is this a unnamed file (New...)?
161 /// name of the file the buffer is associated with.
164 /** Set to true only when the file is fully loaded.
165 * Used to prevent the premature generation of previews
166 * and by the citation inset.
168 bool file_fully_loaded;
171 mutable TocBackend toc_backend;
174 typedef pair<DocIterator, MacroData> ScopeMacro;
175 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
176 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
177 /// map from the macro name to the position map,
178 /// which maps the macro definition position to the scope and the MacroData.
179 NamePositionScopeMacroMap macros;
182 /// positions of child buffers in the buffer
183 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
184 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
185 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
186 /// position of children buffers in this buffer
187 BufferPositionMap children_positions;
188 /// map from children inclusion positions to their scope and their buffer
189 PositionScopeBufferMap position_to_children;
191 /// Container for all sort of Buffer dependant errors.
192 map<string, ErrorList> errorLists;
194 /// all embedded files of this buffer
195 EmbeddedFileList embedded_files;
197 /// timestamp and checksum used to test if the file has been externally
198 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
200 unsigned long checksum_;
203 frontend::WorkAreaManager * wa_;
208 /// A cache for the bibfiles (including bibfiles of loaded child
209 /// documents), needed for appropriate update of natbib labels.
210 mutable EmbeddedFileList bibfilesCache_;
212 mutable RefCache ref_cache_;
214 /// our Text that should be wrapped in an InsetText
218 /// Creates the per buffer temporary directory
219 static FileName createBufferTmpDir()
222 // We are in our own directory. Why bother to mangle name?
223 // In fact I wrote this code to circumvent a problematic behaviour
224 // (bug?) of EMX mkstemp().
225 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
226 convert<string>(count++));
228 if (!tmpfl.createDirectory(0777)) {
229 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
230 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
231 from_utf8(tmpfl.absFilename())));
237 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
238 : parent_buffer(0), lyx_clean(true), bak_clean(true), unnamed(false),
239 read_only(readonly_), filename(file), file_fully_loaded(false),
240 toc_backend(&parent), macro_lock(false),
241 embedded_files(), timestamp_(0), checksum_(0), wa_(0),
244 temppath = createBufferTmpDir();
245 lyxvc.setBuffer(&parent);
247 wa_ = new frontend::WorkAreaManager;
251 Buffer::Buffer(string const & file, bool readonly)
252 : d(new Impl(*this, FileName(file), readonly)), gui_(0)
254 LYXERR(Debug::INFO, "Buffer::Buffer()");
256 d->inset.setBuffer(*this);
257 d->inset.initParagraphs(*this);
258 d->inset.setAutoBreakRows(true);
259 d->inset.getText(0)->setMacrocontextPosition(par_iterator_begin());
265 LYXERR(Debug::INFO, "Buffer::~Buffer()");
266 // here the buffer should take care that it is
267 // saved properly, before it goes into the void.
269 // GuiView already destroyed
272 // clear references to children in macro tables
273 d->children_positions.clear();
274 d->position_to_children.clear();
276 if (!d->temppath.destroyDirectory()) {
277 Alert::warning(_("Could not remove temporary directory"),
278 bformat(_("Could not remove the temporary directory %1$s"),
279 from_utf8(d->temppath.absFilename())));
282 // Remove any previewed LaTeX snippets associated with this buffer.
283 graphics::Previews::get().removeLoader(*this);
289 void Buffer::changed() const
296 frontend::WorkAreaManager & Buffer::workAreaManager() const
298 BOOST_ASSERT(d->wa_);
303 Text & Buffer::text() const
305 return const_cast<Text &>(d->inset.text_);
309 Inset & Buffer::inset() const
311 return const_cast<InsetText &>(d->inset);
315 BufferParams & Buffer::params()
321 BufferParams const & Buffer::params() const
327 ParagraphList & Buffer::paragraphs()
329 return text().paragraphs();
333 ParagraphList const & Buffer::paragraphs() const
335 return text().paragraphs();
339 LyXVC & Buffer::lyxvc()
345 LyXVC const & Buffer::lyxvc() const
351 string const Buffer::temppath() const
353 return d->temppath.absFilename();
357 TexRow const & Buffer::texrow() const
363 TocBackend & Buffer::tocBackend() const
365 return d->toc_backend;
369 EmbeddedFileList & Buffer::embeddedFiles()
371 return d->embedded_files;
375 EmbeddedFileList const & Buffer::embeddedFiles() const
377 return d->embedded_files;
381 bool Buffer::embedded() const
383 return params().embedded;
387 Undo & Buffer::undo()
393 string Buffer::latexName(bool const no_path) const
395 FileName latex_name = makeLatexName(d->filename);
396 return no_path ? latex_name.onlyFileName()
397 : latex_name.absFilename();
401 string Buffer::logName(LogType * type) const
403 string const filename = latexName(false);
405 if (filename.empty()) {
411 string const path = temppath();
413 FileName const fname(addName(temppath(),
414 onlyFilename(changeExtension(filename,
416 FileName const bname(
417 addName(path, onlyFilename(
418 changeExtension(filename,
419 formats.extension("literate") + ".out"))));
421 // If no Latex log or Build log is newer, show Build log
423 if (bname.exists() &&
424 (!fname.exists() || fname.lastModified() < bname.lastModified())) {
425 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
428 return bname.absFilename();
430 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
433 return fname.absFilename();
437 void Buffer::setReadonly(bool const flag)
439 if (d->read_only != flag) {
446 void Buffer::setFileName(string const & newfile)
448 d->filename = makeAbsPath(newfile);
449 setReadonly(d->filename.isReadOnly());
454 int Buffer::readHeader(Lexer & lex)
456 int unknown_tokens = 0;
458 int begin_header_line = -1;
460 // Initialize parameters that may be/go lacking in header:
461 params().branchlist().clear();
462 params().preamble.erase();
463 params().options.erase();
464 params().float_placement.erase();
465 params().paperwidth.erase();
466 params().paperheight.erase();
467 params().leftmargin.erase();
468 params().rightmargin.erase();
469 params().topmargin.erase();
470 params().bottommargin.erase();
471 params().headheight.erase();
472 params().headsep.erase();
473 params().footskip.erase();
474 params().columnsep.erase();
475 params().listings_params.clear();
476 params().clearLayoutModules();
477 params().pdfoptions().clear();
479 for (int i = 0; i < 4; ++i) {
480 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
481 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
484 ErrorList & errorList = d->errorLists["Parse"];
488 string const token = lex.getString();
493 if (token == "\\end_header")
497 if (token == "\\begin_header") {
498 begin_header_line = line;
502 LYXERR(Debug::PARSER, "Handling document header token: `"
505 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.
580 embeddedFiles().enable(params().embedded, *this, false);
583 updateMacroInstances();
588 // needed to insert the selection
589 void Buffer::insertStringAsLines(ParagraphList & pars,
590 pit_type & pit, pos_type & pos,
591 Font const & fn, docstring const & str, bool autobreakrows)
595 // insert the string, don't insert doublespace
596 bool space_inserted = true;
597 for (docstring::const_iterator cit = str.begin();
598 cit != str.end(); ++cit) {
599 Paragraph & par = pars[pit];
601 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
602 breakParagraph(params(), pars, pit, pos,
603 par.layout().isEnvironment());
606 space_inserted = true;
610 // do not insert consecutive spaces if !free_spacing
611 } else if ((*cit == ' ' || *cit == '\t') &&
612 space_inserted && !par.isFreeSpacing()) {
614 } else if (*cit == '\t') {
615 if (!par.isFreeSpacing()) {
616 // tabs are like spaces here
617 par.insertChar(pos, ' ', font, params().trackChanges);
619 space_inserted = true;
621 const pos_type n = 8 - pos % 8;
622 for (pos_type i = 0; i < n; ++i) {
623 par.insertChar(pos, ' ', font, params().trackChanges);
626 space_inserted = true;
628 } else if (!isPrintable(*cit)) {
629 // Ignore unprintables
632 // just insert the character
633 par.insertChar(pos, *cit, font, params().trackChanges);
635 space_inserted = (*cit == ' ');
642 bool Buffer::readString(string const & s)
644 params().compressed = false;
646 // remove dummy empty par
647 paragraphs().clear();
651 FileName const name = FileName::tempName();
652 switch (readFile(lex, name, true)) {
656 // We need to call lyx2lyx, so write the input to a file
657 ofstream os(name.toFilesystemEncoding().c_str());
660 return readFile(name);
670 bool Buffer::readFile(FileName const & filename)
672 FileName fname(filename);
673 // Check if the file is compressed.
674 string format = filename.guessFormatFromContents();
675 if (format == "zip") {
676 // decompress to a temp directory
677 LYXERR(Debug::FILES, filename << " is in zip format. Unzip to " << temppath());
678 ::unzipToDir(filename.toFilesystemEncoding(), temppath());
680 FileName lyxfile(addName(temppath(), "content.lyx"));
681 // if both manifest.txt and file.lyx exist, this is am embedded file
682 if (lyxfile.exists()) {
683 // if in bundled format, save checksum of the compressed file, not content.lyx
684 saveCheckSum(filename);
685 params().embedded = true;
689 // The embedded lyx file can also be compressed, for backward compatibility
690 format = fname.guessFormatFromContents();
691 if (format == "gzip" || format == "zip" || format == "compress")
692 params().compressed = true;
694 // remove dummy empty par
695 paragraphs().clear();
698 if (readFile(lex, fname) != success)
705 bool Buffer::isFullyLoaded() const
707 return d->file_fully_loaded;
711 void Buffer::setFullyLoaded(bool value)
713 d->file_fully_loaded = value;
717 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
720 BOOST_ASSERT(!filename.empty());
723 Alert::error(_("Document could not be read"),
724 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
729 string const token = lex.getString();
732 Alert::error(_("Document could not be read"),
733 bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
737 // the first token _must_ be...
738 if (token != "\\lyxformat") {
739 lyxerr << "Token: " << token << endl;
741 Alert::error(_("Document format failure"),
742 bformat(_("%1$s is not a LyX document."),
743 from_utf8(filename.absFilename())));
748 string tmp_format = lex.getString();
749 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
750 // if present remove ".," from string.
751 string::size_type dot = tmp_format.find_first_of(".,");
752 //lyxerr << " dot found at " << dot << endl;
753 if (dot != string::npos)
754 tmp_format.erase(dot, 1);
755 int const file_format = convert<int>(tmp_format);
756 //lyxerr << "format: " << file_format << endl;
758 // save timestamp and checksum of the original disk file, making sure
759 // to not overwrite them with those of the file created in the tempdir
760 // when it has to be converted to the current format.
762 // Save the timestamp and checksum of disk file. If filename is an
763 // emergency file, save the timestamp and checksum of the original lyx file
764 // because isExternallyModified will check for this file. (BUG4193)
765 string diskfile = filename.absFilename();
766 if (suffixIs(diskfile, ".emergency"))
767 diskfile = diskfile.substr(0, diskfile.size() - 10);
768 saveCheckSum(FileName(diskfile));
771 if (file_format != LYX_FORMAT) {
774 // lyx2lyx would fail
777 FileName const tmpfile = FileName::tempName();
778 if (tmpfile.empty()) {
779 Alert::error(_("Conversion failed"),
780 bformat(_("%1$s is from a different"
781 " version of LyX, but a temporary"
782 " file for converting it could"
784 from_utf8(filename.absFilename())));
787 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
788 if (lyx2lyx.empty()) {
789 Alert::error(_("Conversion script not found"),
790 bformat(_("%1$s is from a different"
791 " version of LyX, but the"
792 " conversion script lyx2lyx"
793 " could not be found."),
794 from_utf8(filename.absFilename())));
797 ostringstream command;
798 command << os::python()
799 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
800 << " -t " << convert<string>(LYX_FORMAT)
801 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
802 << ' ' << quoteName(filename.toFilesystemEncoding());
803 string const command_str = command.str();
805 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
807 cmd_ret const ret = runCommand(command_str);
808 if (ret.first != 0) {
809 Alert::error(_("Conversion script failed"),
810 bformat(_("%1$s is from a different version"
811 " of LyX, but the lyx2lyx script"
812 " failed to convert it."),
813 from_utf8(filename.absFilename())));
816 bool const ret = readFile(tmpfile);
817 // Do stuff with tmpfile name and buffer name here.
818 return ret ? success : failure;
823 if (readDocument(lex)) {
824 Alert::error(_("Document format failure"),
825 bformat(_("%1$s ended unexpectedly, which means"
826 " that it is probably corrupted."),
827 from_utf8(filename.absFilename())));
830 d->file_fully_loaded = true;
835 // Should probably be moved to somewhere else: BufferView? LyXView?
836 bool Buffer::save() const
838 // We don't need autosaves in the immediate future. (Asger)
839 resetAutosaveTimers();
841 string const encodedFilename = d->filename.toFilesystemEncoding();
844 bool madeBackup = false;
846 // make a backup if the file already exists
847 if (lyxrc.make_backup && fileName().exists()) {
848 backupName = FileName(absFileName() + '~');
849 if (!lyxrc.backupdir_path.empty()) {
850 string const mangledName =
851 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
852 backupName = FileName(addName(lyxrc.backupdir_path,
855 if (fileName().copyTo(backupName)) {
858 Alert::error(_("Backup failure"),
859 bformat(_("Cannot create backup file %1$s.\n"
860 "Please check whether the directory exists and is writeable."),
861 from_utf8(backupName.absFilename())));
862 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
866 // ask if the disk file has been externally modified (use checksum method)
867 if (fileName().exists() && isExternallyModified(checksum_method)) {
868 docstring const file = makeDisplayPath(absFileName(), 20);
869 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
870 "you want to overwrite this file?"), file);
871 int const ret = Alert::prompt(_("Overwrite modified file?"),
872 text, 1, 1, _("&Overwrite"), _("&Cancel"));
877 if (writeFile(d->filename)) {
881 // Saving failed, so backup is not backup
883 backupName.moveTo(d->filename);
889 bool Buffer::writeFile(FileName const & fname) const
891 if (d->read_only && fname == d->filename)
897 if (params().embedded)
898 // first write the .lyx file to the temporary directory
899 content = FileName(addName(temppath(), "content.lyx"));
903 docstring const str = bformat(_("Saving document %1$s..."),
904 makeDisplayPath(content.absFilename()));
907 if (params().compressed) {
908 gz::ogzstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
909 retval = ofs && write(ofs);
911 ofstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
912 retval = ofs && write(ofs);
916 message(str + _(" could not write file!."));
920 removeAutosaveFile(d->filename.absFilename());
922 if (params().embedded) {
923 message(str + _(" writing embedded files!."));
924 // if embedding is enabled, write file.lyx and all the embedded files
925 // to the zip file fname.
926 if (!d->embedded_files.writeFile(fname, *this)) {
927 message(str + _(" could not write embedded files!."));
931 saveCheckSum(d->filename);
932 message(str + _(" done."));
938 bool Buffer::write(ostream & ofs) const
941 // Use the standard "C" locale for file output.
942 ofs.imbue(locale::classic());
945 // The top of the file should not be written by params().
947 // write out a comment in the top of the file
948 ofs << "#LyX " << lyx_version
949 << " created this file. For more info see http://www.lyx.org/\n"
950 << "\\lyxformat " << LYX_FORMAT << "\n"
951 << "\\begin_document\n";
953 /// For each author, set 'used' to true if there is a change
954 /// by this author in the document; otherwise set it to 'false'.
955 AuthorList::Authors::const_iterator a_it = params().authors().begin();
956 AuthorList::Authors::const_iterator a_end = params().authors().end();
957 for (; a_it != a_end; ++a_it)
958 a_it->second.setUsed(false);
960 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
961 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
962 for ( ; it != end; ++it)
963 it->checkAuthors(params().authors());
965 // now write out the buffer parameters.
966 ofs << "\\begin_header\n";
967 params().writeFile(ofs);
968 ofs << "\\end_header\n";
971 ofs << "\n\\begin_body\n";
972 text().write(*this, ofs);
973 ofs << "\n\\end_body\n";
975 // Write marker that shows file is complete
976 ofs << "\\end_document" << endl;
978 // Shouldn't really be needed....
981 // how to check if close went ok?
982 // Following is an attempt... (BE 20001011)
984 // good() returns false if any error occured, including some
986 // bad() returns true if something bad happened in the buffer,
987 // which should include file system full errors.
992 lyxerr << "File was not closed properly." << endl;
999 bool Buffer::makeLaTeXFile(FileName const & fname,
1000 string const & original_path,
1001 OutputParams const & runparams,
1002 bool output_preamble, bool output_body) const
1004 string const encoding = runparams.encoding->iconvName();
1005 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1008 try { ofs.reset(encoding); }
1009 catch (iconv_codecvt_facet_exception & e) {
1010 lyxerr << "Caught iconv exception: " << e.what() << endl;
1011 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1012 "verify that the support software for your encoding (%1$s) is "
1013 "properly installed"), from_ascii(encoding)));
1016 if (!openFileWrite(ofs, fname))
1019 //TexStream ts(ofs.rdbuf(), &texrow());
1020 ErrorList & errorList = d->errorLists["Export"];
1022 bool failed_export = false;
1025 writeLaTeXSource(ofs, original_path,
1026 runparams, output_preamble, output_body);
1028 catch (EncodingException & e) {
1029 odocstringstream ods;
1030 ods.put(e.failed_char);
1032 oss << "0x" << hex << e.failed_char << dec;
1033 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1034 " (code point %2$s)"),
1035 ods.str(), from_utf8(oss.str()));
1036 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1037 "representable in the chosen encoding.\n"
1038 "Changing the document encoding to utf8 could help."),
1039 e.par_id, e.pos, e.pos + 1));
1040 failed_export = true;
1042 catch (iconv_codecvt_facet_exception & e) {
1043 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1044 _(e.what()), -1, 0, 0));
1045 failed_export = true;
1047 catch (exception const & e) {
1048 errorList.push_back(ErrorItem(_("conversion failed"),
1049 _(e.what()), -1, 0, 0));
1050 failed_export = true;
1053 lyxerr << "Caught some really weird exception..." << endl;
1054 LyX::cref().exit(1);
1059 failed_export = true;
1060 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1064 return !failed_export;
1068 void Buffer::writeLaTeXSource(odocstream & os,
1069 string const & original_path,
1070 OutputParams const & runparams_in,
1071 bool const output_preamble, bool const output_body) const
1073 // The child documents, if any, shall be already loaded at this point.
1075 OutputParams runparams = runparams_in;
1077 // validate the buffer.
1078 LYXERR(Debug::LATEX, " Validating buffer...");
1079 LaTeXFeatures features(*this, params(), runparams);
1081 LYXERR(Debug::LATEX, " Buffer validation done.");
1083 // The starting paragraph of the coming rows is the
1084 // first paragraph of the document. (Asger)
1085 if (output_preamble && runparams.nice) {
1086 os << "%% LyX " << lyx_version << " created this file. "
1087 "For more info, see http://www.lyx.org/.\n"
1088 "%% Do not edit unless you really know what "
1090 d->texrow.newline();
1091 d->texrow.newline();
1093 LYXERR(Debug::INFO, "lyx document header finished");
1094 // There are a few differences between nice LaTeX and usual files:
1095 // usual is \batchmode and has a
1096 // special input@path to allow the including of figures
1097 // with either \input or \includegraphics (what figinsets do).
1098 // input@path is set when the actual parameter
1099 // original_path is set. This is done for usual tex-file, but not
1100 // for nice-latex-file. (Matthias 250696)
1101 // Note that input@path is only needed for something the user does
1102 // in the preamble, included .tex files or ERT, files included by
1103 // LyX work without it.
1104 if (output_preamble) {
1105 if (!runparams.nice) {
1106 // code for usual, NOT nice-latex-file
1107 os << "\\batchmode\n"; // changed
1108 // from \nonstopmode
1109 d->texrow.newline();
1111 if (!original_path.empty()) {
1113 // We don't know the encoding of inputpath
1114 docstring const inputpath = from_utf8(latex_path(original_path));
1115 os << "\\makeatletter\n"
1116 << "\\def\\input@path{{"
1117 << inputpath << "/}}\n"
1118 << "\\makeatother\n";
1119 d->texrow.newline();
1120 d->texrow.newline();
1121 d->texrow.newline();
1124 // Write the preamble
1125 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1131 os << "\\begin{document}\n";
1132 d->texrow.newline();
1133 } // output_preamble
1135 d->texrow.start(paragraphs().begin()->id(), 0);
1137 LYXERR(Debug::INFO, "preamble finished, now the body.");
1139 // Don't move this behind the parent_buffer=0 code below,
1140 // because then the macros will not get the right "redefinition"
1141 // flag as they don't see the parent macros which are output before.
1144 // fold macros if possible, still with parent buffer as the
1145 // macros will be put in the prefix anyway.
1146 updateMacroInstances();
1148 // if we are doing a real file with body, even if this is the
1149 // child of some other buffer, let's cut the link here.
1150 // This happens for example if only a child document is printed.
1151 Buffer const * save_parent = 0;
1152 if (output_preamble) {
1153 // output the macros visible for this buffer
1154 writeParentMacros(os);
1156 save_parent = d->parent_buffer;
1157 d->parent_buffer = 0;
1161 latexParagraphs(*this, text(), os, d->texrow, runparams);
1163 // Restore the parenthood if needed
1164 if (output_preamble) {
1165 d->parent_buffer = save_parent;
1167 // restore macros with correct parent buffer (especially
1168 // important for the redefinition flag which depends on the
1173 // add this just in case after all the paragraphs
1175 d->texrow.newline();
1177 if (output_preamble) {
1178 os << "\\end{document}\n";
1179 d->texrow.newline();
1180 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1182 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1184 runparams_in.encoding = runparams.encoding;
1186 // Just to be sure. (Asger)
1187 d->texrow.newline();
1189 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1190 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1194 bool Buffer::isLatex() const
1196 return params().documentClass().outputType() == LATEX;
1200 bool Buffer::isLiterate() const
1202 return params().documentClass().outputType() == LITERATE;
1206 bool Buffer::isDocBook() const
1208 return params().documentClass().outputType() == DOCBOOK;
1212 void Buffer::makeDocBookFile(FileName const & fname,
1213 OutputParams const & runparams,
1214 bool const body_only) const
1216 LYXERR(Debug::LATEX, "makeDocBookFile...");
1219 if (!openFileWrite(ofs, fname))
1222 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1226 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1230 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1231 OutputParams const & runparams,
1232 bool const only_body) const
1234 LaTeXFeatures features(*this, params(), runparams);
1239 DocumentClass const & tclass = params().documentClass();
1240 string const top_element = tclass.latexname();
1243 if (runparams.flavor == OutputParams::XML)
1244 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1247 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1250 if (! tclass.class_header().empty())
1251 os << from_ascii(tclass.class_header());
1252 else if (runparams.flavor == OutputParams::XML)
1253 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1254 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1256 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1258 docstring preamble = from_utf8(params().preamble);
1259 if (runparams.flavor != OutputParams::XML ) {
1260 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1261 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1262 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1263 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1266 string const name = runparams.nice
1267 ? changeExtension(absFileName(), ".sgml") : fname;
1268 preamble += features.getIncludedFiles(name);
1269 preamble += features.getLyXSGMLEntities();
1271 if (!preamble.empty()) {
1272 os << "\n [ " << preamble << " ]";
1277 string top = top_element;
1279 if (runparams.flavor == OutputParams::XML)
1280 top += params().language->code();
1282 top += params().language->code().substr(0,2);
1285 if (!params().options.empty()) {
1287 top += params().options;
1290 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1291 << " file was created by LyX " << lyx_version
1292 << "\n See http://www.lyx.org/ for more information -->\n";
1294 params().documentClass().counters().reset();
1298 sgml::openTag(os, top);
1300 docbookParagraphs(paragraphs(), *this, os, runparams);
1301 sgml::closeTag(os, top_element);
1305 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1306 // Other flags: -wall -v0 -x
1307 int Buffer::runChktex()
1311 // get LaTeX-Filename
1312 FileName const path(temppath());
1313 string const name = addName(path.absFilename(), latexName());
1314 string const org_path = filePath();
1316 PathChanger p(path); // path to LaTeX file
1317 message(_("Running chktex..."));
1319 // Generate the LaTeX file if neccessary
1320 OutputParams runparams(¶ms().encoding());
1321 runparams.flavor = OutputParams::LATEX;
1322 runparams.nice = false;
1323 makeLaTeXFile(FileName(name), org_path, runparams);
1326 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1327 int const res = chktex.run(terr); // run chktex
1330 Alert::error(_("chktex failure"),
1331 _("Could not run chktex successfully."));
1332 } else if (res > 0) {
1333 ErrorList & errlist = d->errorLists["ChkTeX"];
1335 bufferErrors(terr, errlist);
1346 void Buffer::validate(LaTeXFeatures & features) const
1348 params().validate(features);
1352 for_each(paragraphs().begin(), paragraphs().end(),
1353 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1355 if (lyxerr.debugging(Debug::LATEX)) {
1356 features.showStruct();
1361 void Buffer::getLabelList(vector<docstring> & list) const
1363 // If this is a child document, use the parent's list instead.
1364 if (d->parent_buffer) {
1365 d->parent_buffer->getLabelList(list);
1370 Toc & toc = d->toc_backend.toc("label");
1371 TocIterator toc_it = toc.begin();
1372 TocIterator end = toc.end();
1373 for (; toc_it != end; ++toc_it) {
1374 if (toc_it->depth() == 0)
1375 list.push_back(toc_it->str());
1380 void Buffer::updateBibfilesCache() const
1382 // If this is a child document, use the parent's cache instead.
1383 if (d->parent_buffer) {
1384 d->parent_buffer->updateBibfilesCache();
1388 d->bibfilesCache_.clear();
1389 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1390 if (it->lyxCode() == BIBTEX_CODE) {
1391 InsetBibtex const & inset =
1392 static_cast<InsetBibtex const &>(*it);
1393 EmbeddedFileList const bibfiles = inset.embeddedFiles();
1394 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1397 } else if (it->lyxCode() == INCLUDE_CODE) {
1398 InsetInclude & inset =
1399 static_cast<InsetInclude &>(*it);
1400 inset.updateBibfilesCache();
1401 EmbeddedFileList const & bibfiles =
1402 inset.getBibfilesCache(*this);
1403 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1411 EmbeddedFileList const & Buffer::getBibfilesCache() const
1413 // If this is a child document, use the parent's cache instead.
1414 if (d->parent_buffer)
1415 return d->parent_buffer->getBibfilesCache();
1417 // We update the cache when first used instead of at loading time.
1418 if (d->bibfilesCache_.empty())
1419 const_cast<Buffer *>(this)->updateBibfilesCache();
1421 return d->bibfilesCache_;
1425 bool Buffer::isDepClean(string const & name) const
1427 DepClean::const_iterator const it = d->dep_clean.find(name);
1428 if (it == d->dep_clean.end())
1434 void Buffer::markDepClean(string const & name)
1436 d->dep_clean[name] = true;
1440 bool Buffer::dispatch(string const & command, bool * result)
1442 return dispatch(lyxaction.lookupFunc(command), result);
1446 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1448 bool dispatched = true;
1450 switch (func.action) {
1451 case LFUN_BUFFER_EXPORT: {
1452 bool const tmp = doExport(to_utf8(func.argument()), false);
1465 void Buffer::changeLanguage(Language const * from, Language const * to)
1470 for_each(par_iterator_begin(),
1472 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1476 bool Buffer::isMultiLingual() const
1478 ParConstIterator end = par_iterator_end();
1479 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1480 if (it->isMultiLingual(params()))
1487 DocIterator Buffer::getParFromID(int const id) const
1490 // John says this is called with id == -1 from undo
1491 lyxerr << "getParFromID(), id: " << id << endl;
1492 return doc_iterator_end(inset());
1495 for (DocIterator it = doc_iterator_begin(inset()); !it.atEnd(); it.forwardPar())
1496 if (it.paragraph().id() == id)
1499 return doc_iterator_end(inset());
1503 bool Buffer::hasParWithID(int const id) const
1505 return !getParFromID(id).atEnd();
1509 ParIterator Buffer::par_iterator_begin()
1511 return ParIterator(doc_iterator_begin(inset()));
1515 ParIterator Buffer::par_iterator_end()
1517 return ParIterator(doc_iterator_end(inset()));
1521 ParConstIterator Buffer::par_iterator_begin() const
1523 return lyx::par_const_iterator_begin(inset());
1527 ParConstIterator Buffer::par_iterator_end() const
1529 return lyx::par_const_iterator_end(inset());
1533 Language const * Buffer::language() const
1535 return params().language;
1539 docstring const Buffer::B_(string const & l10n) const
1541 return params().B_(l10n);
1545 bool Buffer::isClean() const
1547 return d->lyx_clean;
1551 bool Buffer::isBakClean() const
1553 return d->bak_clean;
1557 bool Buffer::isExternallyModified(CheckMethod method) const
1559 BOOST_ASSERT(d->filename.exists());
1560 // if method == timestamp, check timestamp before checksum
1561 return (method == checksum_method
1562 || d->timestamp_ != d->filename.lastModified())
1563 && d->checksum_ != d->filename.checksum();
1567 void Buffer::saveCheckSum(FileName const & file) const
1569 if (file.exists()) {
1570 d->timestamp_ = file.lastModified();
1571 d->checksum_ = file.checksum();
1573 // in the case of save to a new file.
1580 void Buffer::markClean() const
1582 if (!d->lyx_clean) {
1583 d->lyx_clean = true;
1586 // if the .lyx file has been saved, we don't need an
1588 d->bak_clean = true;
1592 void Buffer::markBakClean() const
1594 d->bak_clean = true;
1598 void Buffer::setUnnamed(bool flag)
1604 bool Buffer::isUnnamed() const
1610 // FIXME: this function should be moved to buffer_pimpl.C
1611 void Buffer::markDirty()
1614 d->lyx_clean = false;
1617 d->bak_clean = false;
1619 DepClean::iterator it = d->dep_clean.begin();
1620 DepClean::const_iterator const end = d->dep_clean.end();
1622 for (; it != end; ++it)
1627 FileName Buffer::fileName() const
1633 string Buffer::absFileName() const
1635 return d->filename.absFilename();
1639 string Buffer::filePath() const
1641 return d->filename.onlyPath().absFilename() + "/";
1645 bool Buffer::isReadonly() const
1647 return d->read_only;
1651 void Buffer::setParent(Buffer const * buffer)
1653 // Avoids recursive include.
1654 d->parent_buffer = buffer == this ? 0 : buffer;
1659 Buffer const * Buffer::parent()
1661 return d->parent_buffer;
1665 Buffer const * Buffer::masterBuffer() const
1667 if (!d->parent_buffer)
1670 return d->parent_buffer->masterBuffer();
1674 template<typename M>
1675 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
1680 typename M::iterator it = m.lower_bound(x);
1681 if (it == m.begin())
1689 MacroData const * Buffer::getBufferMacro(docstring const & name,
1690 DocIterator const & pos) const
1692 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
1694 // if paragraphs have no macro context set, pos will be empty
1698 // we haven't found anything yet
1699 DocIterator bestPos = par_iterator_begin();
1700 MacroData const * bestData = 0;
1702 // find macro definitions for name
1703 Impl::NamePositionScopeMacroMap::iterator nameIt
1704 = d->macros.find(name);
1705 if (nameIt != d->macros.end()) {
1706 // find last definition in front of pos or at pos itself
1707 Impl::PositionScopeMacroMap::const_iterator it
1708 = greatest_below(nameIt->second, pos);
1709 if (it != nameIt->second.end()) {
1711 // scope ends behind pos?
1712 if (pos < it->second.first) {
1713 // Looks good, remember this. If there
1714 // is no external macro behind this,
1715 // we found the right one already.
1716 bestPos = it->first;
1717 bestData = &it->second.second;
1721 // try previous macro if there is one
1722 if (it == nameIt->second.begin())
1729 // find macros in included files
1730 Impl::PositionScopeBufferMap::const_iterator it
1731 = greatest_below(d->position_to_children, pos);
1732 if (it == d->position_to_children.end())
1733 // no children before
1737 // do we know something better (i.e. later) already?
1738 if (it->first < bestPos )
1741 // scope ends behind pos?
1742 if (pos < it->second.first) {
1743 // look for macro in external file
1744 d->macro_lock = true;
1745 MacroData const * data
1746 = it->second.second->getMacro(name, false);
1747 d->macro_lock = false;
1749 bestPos = it->first;
1755 // try previous file if there is one
1756 if (it == d->position_to_children.begin())
1761 // return the best macro we have found
1766 MacroData const * Buffer::getMacro(docstring const & name,
1767 DocIterator const & pos, bool global) const
1772 // query buffer macros
1773 MacroData const * data = getBufferMacro(name, pos);
1777 // If there is a master buffer, query that
1778 if (d->parent_buffer) {
1779 d->macro_lock = true;
1780 MacroData const * macro = d->parent_buffer->getMacro(
1781 name, *this, false);
1782 d->macro_lock = false;
1788 data = MacroTable::globalMacros().get(name);
1797 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
1799 // set scope end behind the last paragraph
1800 DocIterator scope = par_iterator_begin();
1801 scope.pit() = scope.lastpit() + 1;
1803 return getMacro(name, scope, global);
1807 MacroData const * Buffer::getMacro(docstring const & name,
1808 Buffer const & child, bool global) const
1810 // look where the child buffer is included first
1811 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
1812 if (it == d->children_positions.end())
1815 // check for macros at the inclusion position
1816 return getMacro(name, it->second, global);
1820 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
1822 pit_type lastpit = it.lastpit();
1824 // look for macros in each paragraph
1825 while (it.pit() <= lastpit) {
1826 Paragraph & par = it.paragraph();
1828 // iterate over the insets of the current paragraph
1829 InsetList const & insets = par.insetList();
1830 InsetList::const_iterator iit = insets.begin();
1831 InsetList::const_iterator end = insets.end();
1832 for (; iit != end; ++iit) {
1833 it.pos() = iit->pos;
1835 // is it a nested text inset?
1836 if (iit->inset->asInsetText()) {
1837 // Inset needs its own scope?
1838 InsetText const * itext
1839 = iit->inset->asInsetText();
1840 bool newScope = itext->isMacroScope();
1842 // scope which ends just behind the inset
1843 DocIterator insetScope = it;
1846 // collect macros in inset
1847 it.push_back(CursorSlice(*iit->inset));
1848 updateMacros(it, newScope ? insetScope : scope);
1853 // is it an external file?
1854 if (iit->inset->lyxCode() == INCLUDE_CODE) {
1855 // get buffer of external file
1856 InsetCommand const & inset
1857 = static_cast<InsetCommand const &>(*iit->inset);
1858 InsetCommandParams const & ip = inset.params();
1859 d->macro_lock = true;
1860 Buffer * child = loadIfNeeded(*this, ip);
1861 d->macro_lock = false;
1865 // register its position, but only when it is
1866 // included first in the buffer
1867 if (d->children_positions.find(child)
1868 == d->children_positions.end())
1869 d->children_positions[child] = it;
1871 // register child with its scope
1872 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
1876 if (iit->inset->lyxCode() != MATHMACRO_CODE)
1880 MathMacroTemplate & macroTemplate
1881 = static_cast<MathMacroTemplate &>(*iit->inset);
1882 MacroContext mc(*this, it);
1883 macroTemplate.updateToContext(mc);
1886 bool valid = macroTemplate.validMacro();
1887 // FIXME: Should be fixNameAndCheckIfValid() in fact,
1888 // then the BufferView's cursor will be invalid in
1889 // some cases which leads to crashes.
1894 d->macros[macroTemplate.name()][it] =
1895 Impl::ScopeMacro(scope, MacroData(*this, it));
1905 void Buffer::updateMacros() const
1910 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
1912 // start with empty table
1914 d->children_positions.clear();
1915 d->position_to_children.clear();
1917 // Iterate over buffer, starting with first paragraph
1918 // The scope must be bigger than any lookup DocIterator
1919 // later. For the global lookup, lastpit+1 is used, hence
1920 // we use lastpit+2 here.
1921 DocIterator it = par_iterator_begin();
1922 DocIterator outerScope = it;
1923 outerScope.pit() = outerScope.lastpit() + 2;
1924 updateMacros(it, outerScope);
1928 void Buffer::updateMacroInstances() const
1930 LYXERR(Debug::MACROS, "updateMacroInstances for "
1931 << d->filename.onlyFileName());
1932 DocIterator it = doc_iterator_begin(inset());
1933 DocIterator end = doc_iterator_end(inset());
1934 for (; it != end; it.forwardPos()) {
1935 // look for MathData cells in InsetMathNest insets
1936 Inset * inset = it.nextInset();
1940 InsetMath * minset = inset->asInsetMath();
1944 // update macro in all cells of the InsetMathNest
1945 DocIterator::idx_type n = minset->nargs();
1946 MacroContext mc = MacroContext(*this, it);
1947 for (DocIterator::idx_type i = 0; i < n; ++i) {
1948 MathData & data = minset->cell(i);
1949 data.updateMacros(0, mc);
1955 void Buffer::listMacroNames(MacroNameSet & macros) const
1960 d->macro_lock = true;
1962 // loop over macro names
1963 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
1964 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
1965 for (; nameIt != nameEnd; ++nameIt)
1966 macros.insert(nameIt->first);
1968 // loop over children
1969 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
1970 Impl::BufferPositionMap::iterator end = d->children_positions.end();
1971 for (; it != end; ++it)
1972 it->first->listMacroNames(macros);
1975 if (d->parent_buffer)
1976 d->parent_buffer->listMacroNames(macros);
1978 d->macro_lock = false;
1982 void Buffer::writeParentMacros(odocstream & os) const
1984 if (!d->parent_buffer)
1987 // collect macro names
1989 d->parent_buffer->listMacroNames(names);
1991 // resolve and output them
1992 MacroNameSet::iterator it = names.begin();
1993 MacroNameSet::iterator end = names.end();
1994 for (; it != end; ++it) {
1996 MacroData const * data =
1997 d->parent_buffer->getMacro(*it, *this, false);
1999 data->write(os, true);
2004 Buffer::References & Buffer::references(docstring const & label)
2006 if (d->parent_buffer)
2007 return const_cast<Buffer *>(masterBuffer())->references(label);
2009 RefCache::iterator it = d->ref_cache_.find(label);
2010 if (it != d->ref_cache_.end())
2011 return it->second.second;
2013 static InsetLabel const * dummy_il = 0;
2014 static References const dummy_refs;
2015 it = d->ref_cache_.insert(
2016 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2017 return it->second.second;
2021 Buffer::References const & Buffer::references(docstring const & label) const
2023 return const_cast<Buffer *>(this)->references(label);
2027 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2029 masterBuffer()->d->ref_cache_[label].first = il;
2033 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2035 return masterBuffer()->d->ref_cache_[label].first;
2039 void Buffer::clearReferenceCache() const
2041 if (!d->parent_buffer)
2042 d->ref_cache_.clear();
2046 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2049 //FIXME: This does not work for child documents yet.
2050 BOOST_ASSERT(code == CITE_CODE);
2051 // Check if the label 'from' appears more than once
2052 vector<docstring> labels;
2055 keys.fillWithBibKeys(this);
2056 BiblioInfo::const_iterator bit = keys.begin();
2057 BiblioInfo::const_iterator bend = keys.end();
2059 for (; bit != bend; ++bit)
2061 labels.push_back(bit->first);
2064 if (count(labels.begin(), labels.end(), from) > 1)
2067 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2068 if (it->lyxCode() == code) {
2069 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2070 docstring const oldValue = inset.getParam(paramName);
2071 if (oldValue == from)
2072 inset.setParam(paramName, to);
2078 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2079 pit_type par_end, bool full_source)
2081 OutputParams runparams(¶ms().encoding());
2082 runparams.nice = true;
2083 runparams.flavor = OutputParams::LATEX;
2084 runparams.linelen = lyxrc.plaintext_linelen;
2085 // No side effect of file copying and image conversion
2086 runparams.dryrun = true;
2090 os << "% " << _("Preview source code") << "\n\n";
2091 d->texrow.newline();
2092 d->texrow.newline();
2094 writeLaTeXSource(os, filePath(), runparams, true, true);
2096 writeDocBookSource(os, absFileName(), runparams, false);
2098 runparams.par_begin = par_begin;
2099 runparams.par_end = par_end;
2100 if (par_begin + 1 == par_end) {
2102 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2106 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2107 convert<docstring>(par_begin),
2108 convert<docstring>(par_end - 1))
2111 d->texrow.newline();
2112 d->texrow.newline();
2113 // output paragraphs
2115 latexParagraphs(*this, text(), os, d->texrow, runparams);
2118 docbookParagraphs(paragraphs(), *this, os, runparams);
2123 ErrorList & Buffer::errorList(string const & type) const
2125 static ErrorList emptyErrorList;
2126 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2127 if (I == d->errorLists.end())
2128 return emptyErrorList;
2134 void Buffer::structureChanged() const
2137 gui_->structureChanged();
2141 void Buffer::errors(string const & err) const
2148 void Buffer::message(docstring const & msg) const
2155 void Buffer::setBusy(bool on) const
2162 void Buffer::setReadOnly(bool on) const
2165 d->wa_->setReadOnly(on);
2169 void Buffer::updateTitles() const
2172 d->wa_->updateTitles();
2176 void Buffer::resetAutosaveTimers() const
2179 gui_->resetAutosaveTimers();
2183 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2192 class AutoSaveBuffer : public ForkedProcess {
2195 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2196 : buffer_(buffer), fname_(fname) {}
2198 virtual boost::shared_ptr<ForkedProcess> clone() const
2200 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2205 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2206 from_utf8(fname_.absFilename())));
2207 return run(DontWait);
2211 virtual int generateChild();
2213 Buffer const & buffer_;
2218 int AutoSaveBuffer::generateChild()
2220 // tmp_ret will be located (usually) in /tmp
2221 // will that be a problem?
2222 // Note that this calls ForkedCalls::fork(), so it's
2223 // ok cross-platform.
2224 pid_t const pid = fork();
2225 // If you want to debug the autosave
2226 // you should set pid to -1, and comment out the fork.
2227 if (pid != 0 && pid != -1)
2230 // pid = -1 signifies that lyx was unable
2231 // to fork. But we will do the save
2233 bool failed = false;
2234 FileName const tmp_ret = FileName::tempName("lyxauto");
2235 if (!tmp_ret.empty()) {
2236 buffer_.writeFile(tmp_ret);
2237 // assume successful write of tmp_ret
2238 if (!tmp_ret.moveTo(fname_))
2244 // failed to write/rename tmp_ret so try writing direct
2245 if (!buffer_.writeFile(fname_)) {
2246 // It is dangerous to do this in the child,
2247 // but safe in the parent, so...
2248 if (pid == -1) // emit message signal.
2249 buffer_.message(_("Autosave failed!"));
2253 if (pid == 0) // we are the child so...
2262 // Perfect target for a thread...
2263 void Buffer::autoSave() const
2265 if (isBakClean() || isReadonly()) {
2266 // We don't save now, but we'll try again later
2267 resetAutosaveTimers();
2271 // emit message signal.
2272 message(_("Autosaving current document..."));
2274 // create autosave filename
2275 string fname = filePath();
2277 fname += d->filename.onlyFileName();
2280 AutoSaveBuffer autosave(*this, FileName(fname));
2284 resetAutosaveTimers();
2288 string Buffer::bufferFormat() const
2298 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2299 string & result_file) const
2301 string backend_format;
2302 OutputParams runparams(¶ms().encoding());
2303 runparams.flavor = OutputParams::LATEX;
2304 runparams.linelen = lyxrc.plaintext_linelen;
2305 vector<string> backs = backends();
2306 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2307 // Get shortest path to format
2308 Graph::EdgePath path;
2309 for (vector<string>::const_iterator it = backs.begin();
2310 it != backs.end(); ++it) {
2311 Graph::EdgePath p = theConverters().getPath(*it, format);
2312 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2313 backend_format = *it;
2318 runparams.flavor = theConverters().getFlavor(path);
2320 Alert::error(_("Couldn't export file"),
2321 bformat(_("No information for exporting the format %1$s."),
2322 formats.prettyName(format)));
2326 backend_format = format;
2327 // FIXME: Don't hardcode format names here, but use a flag
2328 if (backend_format == "pdflatex")
2329 runparams.flavor = OutputParams::PDFLATEX;
2332 string filename = latexName(false);
2333 filename = addName(temppath(), filename);
2334 filename = changeExtension(filename,
2335 formats.extension(backend_format));
2338 updateMacroInstances();
2340 // Plain text backend
2341 if (backend_format == "text")
2342 writePlaintextFile(*this, FileName(filename), runparams);
2344 else if (backend_format == "lyx")
2345 writeFile(FileName(filename));
2347 else if (isDocBook()) {
2348 runparams.nice = !put_in_tempdir;
2349 makeDocBookFile(FileName(filename), runparams);
2352 else if (backend_format == format) {
2353 runparams.nice = true;
2354 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2356 } else if (!lyxrc.tex_allows_spaces
2357 && contains(filePath(), ' ')) {
2358 Alert::error(_("File name error"),
2359 _("The directory path to the document cannot contain spaces."));
2362 runparams.nice = false;
2363 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2367 string const error_type = (format == "program")
2368 ? "Build" : bufferFormat();
2369 string const ext = formats.extension(format);
2370 FileName const tmp_result_file(changeExtension(filename, ext));
2371 bool const success = theConverters().convert(this, FileName(filename),
2372 tmp_result_file, FileName(absFileName()), backend_format, format,
2373 errorList(error_type));
2374 // Emit the signal to show the error list.
2375 if (format != backend_format)
2380 if (put_in_tempdir) {
2381 result_file = tmp_result_file.absFilename();
2385 result_file = changeExtension(absFileName(), ext);
2386 // We need to copy referenced files (e. g. included graphics
2387 // if format == "dvi") to the result dir.
2388 vector<ExportedFile> const files =
2389 runparams.exportdata->externalFiles(format);
2390 string const dest = onlyPath(result_file);
2391 CopyStatus status = SUCCESS;
2392 for (vector<ExportedFile>::const_iterator it = files.begin();
2393 it != files.end() && status != CANCEL; ++it) {
2394 string const fmt = formats.getFormatFromFile(it->sourceName);
2395 status = copyFile(fmt, it->sourceName,
2396 makeAbsPath(it->exportName, dest),
2397 it->exportName, status == FORCE);
2399 if (status == CANCEL) {
2400 message(_("Document export cancelled."));
2401 } else if (tmp_result_file.exists()) {
2402 // Finally copy the main file
2403 status = copyFile(format, tmp_result_file,
2404 FileName(result_file), result_file,
2406 message(bformat(_("Document exported as %1$s "
2408 formats.prettyName(format),
2409 makeDisplayPath(result_file)));
2411 // This must be a dummy converter like fax (bug 1888)
2412 message(bformat(_("Document exported as %1$s"),
2413 formats.prettyName(format)));
2420 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2423 return doExport(format, put_in_tempdir, result_file);
2427 bool Buffer::preview(string const & format) const
2430 if (!doExport(format, true, result_file))
2432 return formats.view(*this, FileName(result_file), format);
2436 bool Buffer::isExportable(string const & format) const
2438 vector<string> backs = backends();
2439 for (vector<string>::const_iterator it = backs.begin();
2440 it != backs.end(); ++it)
2441 if (theConverters().isReachable(*it, format))
2447 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2449 vector<string> backs = backends();
2450 vector<Format const *> result =
2451 theConverters().getReachable(backs[0], only_viewable, true);
2452 for (vector<string>::const_iterator it = backs.begin() + 1;
2453 it != backs.end(); ++it) {
2454 vector<Format const *> r =
2455 theConverters().getReachable(*it, only_viewable, false);
2456 result.insert(result.end(), r.begin(), r.end());
2462 vector<string> Buffer::backends() const
2465 if (params().baseClass()->isTeXClassAvailable()) {
2466 v.push_back(bufferFormat());
2467 // FIXME: Don't hardcode format names here, but use a flag
2468 if (v.back() == "latex")
2469 v.push_back("pdflatex");
2471 v.push_back("text");
2477 bool Buffer::readFileHelper(FileName const & s)
2479 // File information about normal file
2481 docstring const file = makeDisplayPath(s.absFilename(), 50);
2482 docstring text = bformat(_("The specified document\n%1$s"
2483 "\ncould not be read."), file);
2484 Alert::error(_("Could not read document"), text);
2488 // Check if emergency save file exists and is newer.
2489 FileName const e(s.absFilename() + ".emergency");
2491 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2492 docstring const file = makeDisplayPath(s.absFilename(), 20);
2493 docstring const text =
2494 bformat(_("An emergency save of the document "
2496 "Recover emergency save?"), file);
2497 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2498 _("&Recover"), _("&Load Original"),
2502 // the file is not saved if we load the emergency file.
2512 // Now check if autosave file is newer.
2513 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2515 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2516 docstring const file = makeDisplayPath(s.absFilename(), 20);
2517 docstring const text =
2518 bformat(_("The backup of the document "
2519 "%1$s is newer.\n\nLoad the "
2520 "backup instead?"), file);
2521 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2522 _("&Load backup"), _("Load &original"),
2526 // the file is not saved if we load the autosave file.
2530 // Here we delete the autosave
2541 bool Buffer::loadLyXFile(FileName const & s)
2543 if (s.isReadableFile()) {
2544 if (readFileHelper(s)) {
2545 lyxvc().file_found_hook(s);
2546 if (!s.isWritable())
2551 docstring const file = makeDisplayPath(s.absFilename(), 20);
2552 // Here we probably should run
2553 if (LyXVC::file_not_found_hook(s)) {
2554 docstring const text =
2555 bformat(_("Do you want to retrieve the document"
2556 " %1$s from version control?"), file);
2557 int const ret = Alert::prompt(_("Retrieve from version control?"),
2558 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2561 // How can we know _how_ to do the checkout?
2562 // With the current VC support it has to be,
2563 // a RCS file since CVS do not have special ,v files.
2565 return loadLyXFile(s);
2573 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2575 TeXErrors::Errors::const_iterator cit = terr.begin();
2576 TeXErrors::Errors::const_iterator end = terr.end();
2578 for (; cit != end; ++cit) {
2581 int errorRow = cit->error_in_line;
2582 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2588 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2589 } while (found && id_start == id_end && pos_start == pos_end);
2591 errorList.push_back(ErrorItem(cit->error_desc,
2592 cit->error_text, id_start, pos_start, pos_end));