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/assert.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 = 325;
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
219 /// Creates the per buffer temporary directory
220 static FileName createBufferTmpDir()
223 // We are in our own directory. Why bother to mangle name?
224 // In fact I wrote this code to circumvent a problematic behaviour
225 // (bug?) of EMX mkstemp().
226 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
227 convert<string>(count++));
229 if (!tmpfl.createDirectory(0777)) {
230 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
231 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
232 from_utf8(tmpfl.absFilename())));
238 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
239 : parent_buffer(0), lyx_clean(true), bak_clean(true), unnamed(false),
240 read_only(readonly_), filename(file), file_fully_loaded(false),
241 toc_backend(&parent), macro_lock(false),
242 embedded_files(), timestamp_(0), checksum_(0), wa_(0),
245 temppath = createBufferTmpDir();
246 lyxvc.setBuffer(&parent);
248 wa_ = new frontend::WorkAreaManager;
252 Buffer::Buffer(string const & file, bool readonly)
253 : d(new Impl(*this, FileName(file), readonly)), gui_(0)
255 LYXERR(Debug::INFO, "Buffer::Buffer()");
257 d->inset.setBuffer(*this);
258 d->inset.initParagraphs(*this);
259 d->inset.setAutoBreakRows(true);
260 d->inset.getText(0)->setMacrocontextPosition(par_iterator_begin());
266 LYXERR(Debug::INFO, "Buffer::~Buffer()");
267 // here the buffer should take care that it is
268 // saved properly, before it goes into the void.
270 // GuiView already destroyed
273 // clear references to children in macro tables
274 d->children_positions.clear();
275 d->position_to_children.clear();
277 if (!d->temppath.destroyDirectory()) {
278 Alert::warning(_("Could not remove temporary directory"),
279 bformat(_("Could not remove the temporary directory %1$s"),
280 from_utf8(d->temppath.absFilename())));
283 // Remove any previewed LaTeX snippets associated with this buffer.
284 graphics::Previews::get().removeLoader(*this);
290 void Buffer::changed() const
297 frontend::WorkAreaManager & Buffer::workAreaManager() const
299 LASSERT(d->wa_, /**/);
304 Text & Buffer::text() const
306 return const_cast<Text &>(d->inset.text_);
310 Inset & Buffer::inset() const
312 return const_cast<InsetText &>(d->inset);
316 BufferParams & Buffer::params()
322 BufferParams const & Buffer::params() const
328 ParagraphList & Buffer::paragraphs()
330 return text().paragraphs();
334 ParagraphList const & Buffer::paragraphs() const
336 return text().paragraphs();
340 LyXVC & Buffer::lyxvc()
346 LyXVC const & Buffer::lyxvc() const
352 string const Buffer::temppath() const
354 return d->temppath.absFilename();
358 TexRow const & Buffer::texrow() const
364 TocBackend & Buffer::tocBackend() const
366 return d->toc_backend;
370 EmbeddedFileList & Buffer::embeddedFiles()
372 return d->embedded_files;
376 EmbeddedFileList const & Buffer::embeddedFiles() const
378 return d->embedded_files;
382 bool Buffer::embedded() const
384 return params().embedded;
388 Undo & Buffer::undo()
394 string Buffer::latexName(bool const no_path) const
396 FileName latex_name = makeLatexName(d->filename);
397 return no_path ? latex_name.onlyFileName()
398 : latex_name.absFilename();
402 string Buffer::logName(LogType * type) const
404 string const filename = latexName(false);
406 if (filename.empty()) {
412 string const path = temppath();
414 FileName const fname(addName(temppath(),
415 onlyFilename(changeExtension(filename,
417 FileName const bname(
418 addName(path, onlyFilename(
419 changeExtension(filename,
420 formats.extension("literate") + ".out"))));
422 // If no Latex log or Build log is newer, show Build log
424 if (bname.exists() &&
425 (!fname.exists() || fname.lastModified() < bname.lastModified())) {
426 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
429 return bname.absFilename();
431 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
434 return fname.absFilename();
438 void Buffer::setReadonly(bool const flag)
440 if (d->read_only != flag) {
447 void Buffer::setFileName(string const & newfile)
449 d->filename = makeAbsPath(newfile);
450 setReadonly(d->filename.isReadOnly());
455 int Buffer::readHeader(Lexer & lex)
457 int unknown_tokens = 0;
459 int begin_header_line = -1;
461 // Initialize parameters that may be/go lacking in header:
462 params().branchlist().clear();
463 params().preamble.erase();
464 params().options.erase();
465 params().float_placement.erase();
466 params().paperwidth.erase();
467 params().paperheight.erase();
468 params().leftmargin.erase();
469 params().rightmargin.erase();
470 params().topmargin.erase();
471 params().bottommargin.erase();
472 params().headheight.erase();
473 params().headsep.erase();
474 params().footskip.erase();
475 params().columnsep.erase();
476 params().listings_params.clear();
477 params().clearLayoutModules();
478 params().pdfoptions().clear();
480 for (int i = 0; i < 4; ++i) {
481 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
482 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
485 ErrorList & errorList = d->errorLists["Parse"];
494 if (token == "\\end_header")
498 if (token == "\\begin_header") {
499 begin_header_line = line;
503 LYXERR(Debug::PARSER, "Handling document header token: `"
506 string unknown = params().readToken(lex, token, d->filename.onlyPath(),
508 if (!unknown.empty()) {
509 if (unknown[0] != '\\' && token == "\\textclass") {
510 Alert::warning(_("Unknown document class"),
511 bformat(_("Using the default document class, because the "
512 "class %1$s is unknown."), from_utf8(unknown)));
515 docstring const s = bformat(_("Unknown token: "
519 errorList.push_back(ErrorItem(_("Document header error"),
524 if (begin_header_line) {
525 docstring const s = _("\\begin_header is missing");
526 errorList.push_back(ErrorItem(_("Document header error"),
530 params().makeDocumentClass();
532 return unknown_tokens;
537 // changed to be public and have one parameter
538 // Returns false if "\end_document" is not read (Asger)
539 bool Buffer::readDocument(Lexer & lex)
541 ErrorList & errorList = d->errorLists["Parse"];
544 if (!lex.checkFor("\\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 LASSERT(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 LASSERT(!filename.empty(), /**/);
734 // the first (non-comment) token _must_ be...
735 if (!lex.checkFor("\\lyxformat")) {
736 Alert::error(_("Document format failure"),
737 bformat(_("%1$s is not a readable LyX document."),
738 from_utf8(filename.absFilename())));
744 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
745 // if present remove ".," from string.
746 size_t dot = tmp_format.find_first_of(".,");
747 //lyxerr << " dot found at " << dot << endl;
748 if (dot != string::npos)
749 tmp_format.erase(dot, 1);
750 int const file_format = convert<int>(tmp_format);
751 //lyxerr << "format: " << file_format << endl;
753 // save timestamp and checksum of the original disk file, making sure
754 // to not overwrite them with those of the file created in the tempdir
755 // when it has to be converted to the current format.
757 // Save the timestamp and checksum of disk file. If filename is an
758 // emergency file, save the timestamp and checksum of the original lyx file
759 // because isExternallyModified will check for this file. (BUG4193)
760 string diskfile = filename.absFilename();
761 if (suffixIs(diskfile, ".emergency"))
762 diskfile = diskfile.substr(0, diskfile.size() - 10);
763 saveCheckSum(FileName(diskfile));
766 if (file_format != LYX_FORMAT) {
769 // lyx2lyx would fail
772 FileName const tmpfile = FileName::tempName();
773 if (tmpfile.empty()) {
774 Alert::error(_("Conversion failed"),
775 bformat(_("%1$s is from a different"
776 " version of LyX, but a temporary"
777 " file for converting it could"
779 from_utf8(filename.absFilename())));
782 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
783 if (lyx2lyx.empty()) {
784 Alert::error(_("Conversion script not found"),
785 bformat(_("%1$s is from a different"
786 " version of LyX, but the"
787 " conversion script lyx2lyx"
788 " could not be found."),
789 from_utf8(filename.absFilename())));
792 ostringstream command;
793 command << os::python()
794 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
795 << " -t " << convert<string>(LYX_FORMAT)
796 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
797 << ' ' << quoteName(filename.toFilesystemEncoding());
798 string const command_str = command.str();
800 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
802 cmd_ret const ret = runCommand(command_str);
803 if (ret.first != 0) {
804 Alert::error(_("Conversion script failed"),
805 bformat(_("%1$s is from a different version"
806 " of LyX, but the lyx2lyx script"
807 " failed to convert it."),
808 from_utf8(filename.absFilename())));
811 bool const ret = readFile(tmpfile);
812 // Do stuff with tmpfile name and buffer name here.
813 return ret ? success : failure;
818 if (readDocument(lex)) {
819 Alert::error(_("Document format failure"),
820 bformat(_("%1$s ended unexpectedly, which means"
821 " that it is probably corrupted."),
822 from_utf8(filename.absFilename())));
825 d->file_fully_loaded = true;
830 // Should probably be moved to somewhere else: BufferView? LyXView?
831 bool Buffer::save() const
833 // We don't need autosaves in the immediate future. (Asger)
834 resetAutosaveTimers();
836 string const encodedFilename = d->filename.toFilesystemEncoding();
839 bool madeBackup = false;
841 // make a backup if the file already exists
842 if (lyxrc.make_backup && fileName().exists()) {
843 backupName = FileName(absFileName() + '~');
844 if (!lyxrc.backupdir_path.empty()) {
845 string const mangledName =
846 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
847 backupName = FileName(addName(lyxrc.backupdir_path,
850 if (fileName().copyTo(backupName)) {
853 Alert::error(_("Backup failure"),
854 bformat(_("Cannot create backup file %1$s.\n"
855 "Please check whether the directory exists and is writeable."),
856 from_utf8(backupName.absFilename())));
857 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
861 // ask if the disk file has been externally modified (use checksum method)
862 if (fileName().exists() && isExternallyModified(checksum_method)) {
863 docstring const file = makeDisplayPath(absFileName(), 20);
864 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
865 "you want to overwrite this file?"), file);
866 int const ret = Alert::prompt(_("Overwrite modified file?"),
867 text, 1, 1, _("&Overwrite"), _("&Cancel"));
872 if (writeFile(d->filename)) {
876 // Saving failed, so backup is not backup
878 backupName.moveTo(d->filename);
884 bool Buffer::writeFile(FileName const & fname) const
886 if (d->read_only && fname == d->filename)
892 if (params().embedded)
893 // first write the .lyx file to the temporary directory
894 content = FileName(addName(temppath(), "content.lyx"));
898 docstring const str = bformat(_("Saving document %1$s..."),
899 makeDisplayPath(content.absFilename()));
902 if (params().compressed) {
903 gz::ogzstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
904 retval = ofs && write(ofs);
906 ofstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
907 retval = ofs && write(ofs);
911 message(str + _(" could not write file!"));
915 removeAutosaveFile(d->filename.absFilename());
917 if (params().embedded) {
918 message(str + _(" writing embedded files."));
919 // if embedding is enabled, write file.lyx and all the embedded files
920 // to the zip file fname.
921 if (!d->embedded_files.writeFile(fname, *this)) {
922 message(str + _(" could not write embedded files!"));
926 saveCheckSum(d->filename);
927 message(str + _(" done."));
933 bool Buffer::write(ostream & ofs) const
936 // Use the standard "C" locale for file output.
937 ofs.imbue(locale::classic());
940 // The top of the file should not be written by params().
942 // write out a comment in the top of the file
943 ofs << "#LyX " << lyx_version
944 << " created this file. For more info see http://www.lyx.org/\n"
945 << "\\lyxformat " << LYX_FORMAT << "\n"
946 << "\\begin_document\n";
948 /// For each author, set 'used' to true if there is a change
949 /// by this author in the document; otherwise set it to 'false'.
950 AuthorList::Authors::const_iterator a_it = params().authors().begin();
951 AuthorList::Authors::const_iterator a_end = params().authors().end();
952 for (; a_it != a_end; ++a_it)
953 a_it->second.setUsed(false);
955 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
956 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
957 for ( ; it != end; ++it)
958 it->checkAuthors(params().authors());
960 // now write out the buffer parameters.
961 ofs << "\\begin_header\n";
962 params().writeFile(ofs);
963 ofs << "\\end_header\n";
966 ofs << "\n\\begin_body\n";
967 text().write(*this, ofs);
968 ofs << "\n\\end_body\n";
970 // Write marker that shows file is complete
971 ofs << "\\end_document" << endl;
973 // Shouldn't really be needed....
976 // how to check if close went ok?
977 // Following is an attempt... (BE 20001011)
979 // good() returns false if any error occured, including some
981 // bad() returns true if something bad happened in the buffer,
982 // which should include file system full errors.
987 lyxerr << "File was not closed properly." << endl;
994 bool Buffer::makeLaTeXFile(FileName const & fname,
995 string const & original_path,
996 OutputParams const & runparams,
997 bool output_preamble, bool output_body) const
999 string const encoding = runparams.encoding->iconvName();
1000 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1003 try { ofs.reset(encoding); }
1004 catch (iconv_codecvt_facet_exception & e) {
1005 lyxerr << "Caught iconv exception: " << e.what() << endl;
1006 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1007 "verify that the support software for your encoding (%1$s) is "
1008 "properly installed"), from_ascii(encoding)));
1011 if (!openFileWrite(ofs, fname))
1014 //TexStream ts(ofs.rdbuf(), &texrow());
1015 ErrorList & errorList = d->errorLists["Export"];
1017 bool failed_export = false;
1020 writeLaTeXSource(ofs, original_path,
1021 runparams, output_preamble, output_body);
1023 catch (EncodingException & e) {
1024 odocstringstream ods;
1025 ods.put(e.failed_char);
1027 oss << "0x" << hex << e.failed_char << dec;
1028 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1029 " (code point %2$s)"),
1030 ods.str(), from_utf8(oss.str()));
1031 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1032 "representable in the chosen encoding.\n"
1033 "Changing the document encoding to utf8 could help."),
1034 e.par_id, e.pos, e.pos + 1));
1035 failed_export = true;
1037 catch (iconv_codecvt_facet_exception & e) {
1038 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1039 _(e.what()), -1, 0, 0));
1040 failed_export = true;
1042 catch (exception const & e) {
1043 errorList.push_back(ErrorItem(_("conversion failed"),
1044 _(e.what()), -1, 0, 0));
1045 failed_export = true;
1048 lyxerr << "Caught some really weird exception..." << endl;
1049 LyX::cref().exit(1);
1054 failed_export = true;
1055 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1059 return !failed_export;
1063 void Buffer::writeLaTeXSource(odocstream & os,
1064 string const & original_path,
1065 OutputParams const & runparams_in,
1066 bool const output_preamble, bool const output_body) const
1068 // The child documents, if any, shall be already loaded at this point.
1070 OutputParams runparams = runparams_in;
1072 // validate the buffer.
1073 LYXERR(Debug::LATEX, " Validating buffer...");
1074 LaTeXFeatures features(*this, params(), runparams);
1076 LYXERR(Debug::LATEX, " Buffer validation done.");
1078 // The starting paragraph of the coming rows is the
1079 // first paragraph of the document. (Asger)
1080 if (output_preamble && runparams.nice) {
1081 os << "%% LyX " << lyx_version << " created this file. "
1082 "For more info, see http://www.lyx.org/.\n"
1083 "%% Do not edit unless you really know what "
1085 d->texrow.newline();
1086 d->texrow.newline();
1088 LYXERR(Debug::INFO, "lyx document header finished");
1090 // Don't move this behind the parent_buffer=0 code below,
1091 // because then the macros will not get the right "redefinition"
1092 // flag as they don't see the parent macros which are output before.
1095 // fold macros if possible, still with parent buffer as the
1096 // macros will be put in the prefix anyway.
1097 updateMacroInstances();
1099 // There are a few differences between nice LaTeX and usual files:
1100 // usual is \batchmode and has a
1101 // special input@path to allow the including of figures
1102 // with either \input or \includegraphics (what figinsets do).
1103 // input@path is set when the actual parameter
1104 // original_path is set. This is done for usual tex-file, but not
1105 // for nice-latex-file. (Matthias 250696)
1106 // Note that input@path is only needed for something the user does
1107 // in the preamble, included .tex files or ERT, files included by
1108 // LyX work without it.
1109 if (output_preamble) {
1110 if (!runparams.nice) {
1111 // code for usual, NOT nice-latex-file
1112 os << "\\batchmode\n"; // changed
1113 // from \nonstopmode
1114 d->texrow.newline();
1116 if (!original_path.empty()) {
1118 // We don't know the encoding of inputpath
1119 docstring const inputpath = from_utf8(latex_path(original_path));
1120 os << "\\makeatletter\n"
1121 << "\\def\\input@path{{"
1122 << inputpath << "/}}\n"
1123 << "\\makeatother\n";
1124 d->texrow.newline();
1125 d->texrow.newline();
1126 d->texrow.newline();
1129 // get parent macros (if this buffer has a parent) which will be
1130 // written at the document begin further down.
1131 MacroSet parentMacros;
1132 listParentMacros(parentMacros, features);
1134 // Write the preamble
1135 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1141 os << "\\begin{document}\n";
1142 d->texrow.newline();
1144 // output the parent macros
1145 MacroSet::iterator it = parentMacros.begin();
1146 MacroSet::iterator end = parentMacros.end();
1147 for (; it != end; ++it)
1148 (*it)->write(os, true);
1149 } // output_preamble
1151 d->texrow.start(paragraphs().begin()->id(), 0);
1153 LYXERR(Debug::INFO, "preamble finished, now the body.");
1155 // if we are doing a real file with body, even if this is the
1156 // child of some other buffer, let's cut the link here.
1157 // This happens for example if only a child document is printed.
1158 Buffer const * save_parent = 0;
1159 if (output_preamble) {
1160 save_parent = d->parent_buffer;
1161 d->parent_buffer = 0;
1165 latexParagraphs(*this, text(), os, d->texrow, runparams);
1167 // Restore the parenthood if needed
1168 if (output_preamble)
1169 d->parent_buffer = save_parent;
1171 // add this just in case after all the paragraphs
1173 d->texrow.newline();
1175 if (output_preamble) {
1176 os << "\\end{document}\n";
1177 d->texrow.newline();
1178 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1180 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1182 runparams_in.encoding = runparams.encoding;
1184 // Just to be sure. (Asger)
1185 d->texrow.newline();
1187 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1188 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1192 bool Buffer::isLatex() const
1194 return params().documentClass().outputType() == LATEX;
1198 bool Buffer::isLiterate() const
1200 return params().documentClass().outputType() == LITERATE;
1204 bool Buffer::isDocBook() const
1206 return params().documentClass().outputType() == DOCBOOK;
1210 void Buffer::makeDocBookFile(FileName const & fname,
1211 OutputParams const & runparams,
1212 bool const body_only) const
1214 LYXERR(Debug::LATEX, "makeDocBookFile...");
1217 if (!openFileWrite(ofs, fname))
1220 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1224 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1228 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1229 OutputParams const & runparams,
1230 bool const only_body) const
1232 LaTeXFeatures features(*this, params(), runparams);
1237 DocumentClass const & tclass = params().documentClass();
1238 string const top_element = tclass.latexname();
1241 if (runparams.flavor == OutputParams::XML)
1242 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1245 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1248 if (! tclass.class_header().empty())
1249 os << from_ascii(tclass.class_header());
1250 else if (runparams.flavor == OutputParams::XML)
1251 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1252 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1254 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1256 docstring preamble = from_utf8(params().preamble);
1257 if (runparams.flavor != OutputParams::XML ) {
1258 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1259 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1260 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1261 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1264 string const name = runparams.nice
1265 ? changeExtension(absFileName(), ".sgml") : fname;
1266 preamble += features.getIncludedFiles(name);
1267 preamble += features.getLyXSGMLEntities();
1269 if (!preamble.empty()) {
1270 os << "\n [ " << preamble << " ]";
1275 string top = top_element;
1277 if (runparams.flavor == OutputParams::XML)
1278 top += params().language->code();
1280 top += params().language->code().substr(0,2);
1283 if (!params().options.empty()) {
1285 top += params().options;
1288 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1289 << " file was created by LyX " << lyx_version
1290 << "\n See http://www.lyx.org/ for more information -->\n";
1292 params().documentClass().counters().reset();
1296 sgml::openTag(os, top);
1298 docbookParagraphs(paragraphs(), *this, os, runparams);
1299 sgml::closeTag(os, top_element);
1303 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1304 // Other flags: -wall -v0 -x
1305 int Buffer::runChktex()
1309 // get LaTeX-Filename
1310 FileName const path(temppath());
1311 string const name = addName(path.absFilename(), latexName());
1312 string const org_path = filePath();
1314 PathChanger p(path); // path to LaTeX file
1315 message(_("Running chktex..."));
1317 // Generate the LaTeX file if neccessary
1318 OutputParams runparams(¶ms().encoding());
1319 runparams.flavor = OutputParams::LATEX;
1320 runparams.nice = false;
1321 makeLaTeXFile(FileName(name), org_path, runparams);
1324 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1325 int const res = chktex.run(terr); // run chktex
1328 Alert::error(_("chktex failure"),
1329 _("Could not run chktex successfully."));
1330 } else if (res > 0) {
1331 ErrorList & errlist = d->errorLists["ChkTeX"];
1333 bufferErrors(terr, errlist);
1344 void Buffer::validate(LaTeXFeatures & features) const
1346 params().validate(features);
1350 for_each(paragraphs().begin(), paragraphs().end(),
1351 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1353 if (lyxerr.debugging(Debug::LATEX)) {
1354 features.showStruct();
1359 void Buffer::getLabelList(vector<docstring> & list) const
1361 // If this is a child document, use the parent's list instead.
1362 if (d->parent_buffer) {
1363 d->parent_buffer->getLabelList(list);
1368 Toc & toc = d->toc_backend.toc("label");
1369 TocIterator toc_it = toc.begin();
1370 TocIterator end = toc.end();
1371 for (; toc_it != end; ++toc_it) {
1372 if (toc_it->depth() == 0)
1373 list.push_back(toc_it->str());
1378 void Buffer::updateBibfilesCache() const
1380 // If this is a child document, use the parent's cache instead.
1381 if (d->parent_buffer) {
1382 d->parent_buffer->updateBibfilesCache();
1386 d->bibfilesCache_.clear();
1387 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1388 if (it->lyxCode() == BIBTEX_CODE) {
1389 InsetBibtex const & inset =
1390 static_cast<InsetBibtex const &>(*it);
1391 EmbeddedFileList const bibfiles = inset.getBibFiles();
1392 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1395 } else if (it->lyxCode() == INCLUDE_CODE) {
1396 InsetInclude & inset =
1397 static_cast<InsetInclude &>(*it);
1398 inset.updateBibfilesCache();
1399 EmbeddedFileList const & bibfiles =
1400 inset.getBibfilesCache(*this);
1401 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1409 EmbeddedFileList const & Buffer::getBibfilesCache() const
1411 // If this is a child document, use the parent's cache instead.
1412 if (d->parent_buffer)
1413 return d->parent_buffer->getBibfilesCache();
1415 // We update the cache when first used instead of at loading time.
1416 if (d->bibfilesCache_.empty())
1417 const_cast<Buffer *>(this)->updateBibfilesCache();
1419 return d->bibfilesCache_;
1423 bool Buffer::isDepClean(string const & name) const
1425 DepClean::const_iterator const it = d->dep_clean.find(name);
1426 if (it == d->dep_clean.end())
1432 void Buffer::markDepClean(string const & name)
1434 d->dep_clean[name] = true;
1438 bool Buffer::dispatch(string const & command, bool * result)
1440 return dispatch(lyxaction.lookupFunc(command), result);
1444 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1446 bool dispatched = true;
1448 switch (func.action) {
1449 case LFUN_BUFFER_EXPORT: {
1450 bool const tmp = doExport(to_utf8(func.argument()), false);
1463 void Buffer::changeLanguage(Language const * from, Language const * to)
1465 LASSERT(from, /**/);
1468 for_each(par_iterator_begin(),
1470 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1474 bool Buffer::isMultiLingual() const
1476 ParConstIterator end = par_iterator_end();
1477 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1478 if (it->isMultiLingual(params()))
1485 DocIterator Buffer::getParFromID(int const id) const
1488 // John says this is called with id == -1 from undo
1489 lyxerr << "getParFromID(), id: " << id << endl;
1490 return doc_iterator_end(inset());
1493 for (DocIterator it = doc_iterator_begin(inset()); !it.atEnd(); it.forwardPar())
1494 if (it.paragraph().id() == id)
1497 return doc_iterator_end(inset());
1501 bool Buffer::hasParWithID(int const id) const
1503 return !getParFromID(id).atEnd();
1507 ParIterator Buffer::par_iterator_begin()
1509 return ParIterator(doc_iterator_begin(inset()));
1513 ParIterator Buffer::par_iterator_end()
1515 return ParIterator(doc_iterator_end(inset()));
1519 ParConstIterator Buffer::par_iterator_begin() const
1521 return lyx::par_const_iterator_begin(inset());
1525 ParConstIterator Buffer::par_iterator_end() const
1527 return lyx::par_const_iterator_end(inset());
1531 Language const * Buffer::language() const
1533 return params().language;
1537 docstring const Buffer::B_(string const & l10n) const
1539 return params().B_(l10n);
1543 bool Buffer::isClean() const
1545 return d->lyx_clean;
1549 bool Buffer::isBakClean() const
1551 return d->bak_clean;
1555 bool Buffer::isExternallyModified(CheckMethod method) const
1557 LASSERT(d->filename.exists(), /**/);
1558 // if method == timestamp, check timestamp before checksum
1559 return (method == checksum_method
1560 || d->timestamp_ != d->filename.lastModified())
1561 && d->checksum_ != d->filename.checksum();
1565 void Buffer::saveCheckSum(FileName const & file) const
1567 if (file.exists()) {
1568 d->timestamp_ = file.lastModified();
1569 d->checksum_ = file.checksum();
1571 // in the case of save to a new file.
1578 void Buffer::markClean() const
1580 if (!d->lyx_clean) {
1581 d->lyx_clean = true;
1584 // if the .lyx file has been saved, we don't need an
1586 d->bak_clean = true;
1590 void Buffer::markBakClean() const
1592 d->bak_clean = true;
1596 void Buffer::setUnnamed(bool flag)
1602 bool Buffer::isUnnamed() const
1608 // FIXME: this function should be moved to buffer_pimpl.C
1609 void Buffer::markDirty()
1612 d->lyx_clean = false;
1615 d->bak_clean = false;
1617 DepClean::iterator it = d->dep_clean.begin();
1618 DepClean::const_iterator const end = d->dep_clean.end();
1620 for (; it != end; ++it)
1625 FileName Buffer::fileName() const
1631 string Buffer::absFileName() const
1633 return d->filename.absFilename();
1637 string Buffer::filePath() const
1639 return d->filename.onlyPath().absFilename() + "/";
1643 bool Buffer::isReadonly() const
1645 return d->read_only;
1649 void Buffer::setParent(Buffer const * buffer)
1651 // Avoids recursive include.
1652 d->parent_buffer = buffer == this ? 0 : buffer;
1657 Buffer const * Buffer::parent()
1659 return d->parent_buffer;
1663 Buffer const * Buffer::masterBuffer() const
1665 if (!d->parent_buffer)
1668 return d->parent_buffer->masterBuffer();
1672 template<typename M>
1673 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
1678 typename M::iterator it = m.lower_bound(x);
1679 if (it == m.begin())
1687 MacroData const * Buffer::getBufferMacro(docstring const & name,
1688 DocIterator const & pos) const
1690 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
1692 // if paragraphs have no macro context set, pos will be empty
1696 // we haven't found anything yet
1697 DocIterator bestPos = par_iterator_begin();
1698 MacroData const * bestData = 0;
1700 // find macro definitions for name
1701 Impl::NamePositionScopeMacroMap::iterator nameIt
1702 = d->macros.find(name);
1703 if (nameIt != d->macros.end()) {
1704 // find last definition in front of pos or at pos itself
1705 Impl::PositionScopeMacroMap::const_iterator it
1706 = greatest_below(nameIt->second, pos);
1707 if (it != nameIt->second.end()) {
1709 // scope ends behind pos?
1710 if (pos < it->second.first) {
1711 // Looks good, remember this. If there
1712 // is no external macro behind this,
1713 // we found the right one already.
1714 bestPos = it->first;
1715 bestData = &it->second.second;
1719 // try previous macro if there is one
1720 if (it == nameIt->second.begin())
1727 // find macros in included files
1728 Impl::PositionScopeBufferMap::const_iterator it
1729 = greatest_below(d->position_to_children, pos);
1730 if (it == d->position_to_children.end())
1731 // no children before
1735 // do we know something better (i.e. later) already?
1736 if (it->first < bestPos )
1739 // scope ends behind pos?
1740 if (pos < it->second.first) {
1741 // look for macro in external file
1742 d->macro_lock = true;
1743 MacroData const * data
1744 = it->second.second->getMacro(name, false);
1745 d->macro_lock = false;
1747 bestPos = it->first;
1753 // try previous file if there is one
1754 if (it == d->position_to_children.begin())
1759 // return the best macro we have found
1764 MacroData const * Buffer::getMacro(docstring const & name,
1765 DocIterator const & pos, bool global) const
1770 // query buffer macros
1771 MacroData const * data = getBufferMacro(name, pos);
1775 // If there is a master buffer, query that
1776 if (d->parent_buffer) {
1777 d->macro_lock = true;
1778 MacroData const * macro = d->parent_buffer->getMacro(
1779 name, *this, false);
1780 d->macro_lock = false;
1786 data = MacroTable::globalMacros().get(name);
1795 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
1797 // set scope end behind the last paragraph
1798 DocIterator scope = par_iterator_begin();
1799 scope.pit() = scope.lastpit() + 1;
1801 return getMacro(name, scope, global);
1805 MacroData const * Buffer::getMacro(docstring const & name,
1806 Buffer const & child, bool global) const
1808 // look where the child buffer is included first
1809 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
1810 if (it == d->children_positions.end())
1813 // check for macros at the inclusion position
1814 return getMacro(name, it->second, global);
1818 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
1820 pit_type lastpit = it.lastpit();
1822 // look for macros in each paragraph
1823 while (it.pit() <= lastpit) {
1824 Paragraph & par = it.paragraph();
1826 // iterate over the insets of the current paragraph
1827 InsetList const & insets = par.insetList();
1828 InsetList::const_iterator iit = insets.begin();
1829 InsetList::const_iterator end = insets.end();
1830 for (; iit != end; ++iit) {
1831 it.pos() = iit->pos;
1833 // is it a nested text inset?
1834 if (iit->inset->asInsetText()) {
1835 // Inset needs its own scope?
1836 InsetText const * itext
1837 = iit->inset->asInsetText();
1838 bool newScope = itext->isMacroScope();
1840 // scope which ends just behind the inset
1841 DocIterator insetScope = it;
1844 // collect macros in inset
1845 it.push_back(CursorSlice(*iit->inset));
1846 updateMacros(it, newScope ? insetScope : scope);
1851 // is it an external file?
1852 if (iit->inset->lyxCode() == INCLUDE_CODE) {
1853 // get buffer of external file
1854 InsetCommand const & inset
1855 = static_cast<InsetCommand const &>(*iit->inset);
1856 InsetCommandParams const & ip = inset.params();
1857 d->macro_lock = true;
1858 Buffer * child = loadIfNeeded(*this, ip);
1859 d->macro_lock = false;
1863 // register its position, but only when it is
1864 // included first in the buffer
1865 if (d->children_positions.find(child)
1866 == d->children_positions.end())
1867 d->children_positions[child] = it;
1869 // register child with its scope
1870 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
1874 if (iit->inset->lyxCode() != MATHMACRO_CODE)
1878 MathMacroTemplate & macroTemplate
1879 = static_cast<MathMacroTemplate &>(*iit->inset);
1880 MacroContext mc(*this, it);
1881 macroTemplate.updateToContext(mc);
1884 bool valid = macroTemplate.validMacro();
1885 // FIXME: Should be fixNameAndCheckIfValid() in fact,
1886 // then the BufferView's cursor will be invalid in
1887 // some cases which leads to crashes.
1892 d->macros[macroTemplate.name()][it] =
1893 Impl::ScopeMacro(scope, MacroData(*this, it));
1903 void Buffer::updateMacros() const
1908 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
1910 // start with empty table
1912 d->children_positions.clear();
1913 d->position_to_children.clear();
1915 // Iterate over buffer, starting with first paragraph
1916 // The scope must be bigger than any lookup DocIterator
1917 // later. For the global lookup, lastpit+1 is used, hence
1918 // we use lastpit+2 here.
1919 DocIterator it = par_iterator_begin();
1920 DocIterator outerScope = it;
1921 outerScope.pit() = outerScope.lastpit() + 2;
1922 updateMacros(it, outerScope);
1926 void Buffer::updateMacroInstances() const
1928 LYXERR(Debug::MACROS, "updateMacroInstances for "
1929 << d->filename.onlyFileName());
1930 DocIterator it = doc_iterator_begin(inset());
1931 DocIterator end = doc_iterator_end(inset());
1932 for (; it != end; it.forwardPos()) {
1933 // look for MathData cells in InsetMathNest insets
1934 Inset * inset = it.nextInset();
1938 InsetMath * minset = inset->asInsetMath();
1942 // update macro in all cells of the InsetMathNest
1943 DocIterator::idx_type n = minset->nargs();
1944 MacroContext mc = MacroContext(*this, it);
1945 for (DocIterator::idx_type i = 0; i < n; ++i) {
1946 MathData & data = minset->cell(i);
1947 data.updateMacros(0, mc);
1953 void Buffer::listMacroNames(MacroNameSet & macros) const
1958 d->macro_lock = true;
1960 // loop over macro names
1961 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
1962 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
1963 for (; nameIt != nameEnd; ++nameIt)
1964 macros.insert(nameIt->first);
1966 // loop over children
1967 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
1968 Impl::BufferPositionMap::iterator end = d->children_positions.end();
1969 for (; it != end; ++it)
1970 it->first->listMacroNames(macros);
1973 if (d->parent_buffer)
1974 d->parent_buffer->listMacroNames(macros);
1976 d->macro_lock = false;
1980 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
1982 if (!d->parent_buffer)
1986 d->parent_buffer->listMacroNames(names);
1989 MacroNameSet::iterator it = names.begin();
1990 MacroNameSet::iterator end = names.end();
1991 for (; it != end; ++it) {
1993 MacroData const * data =
1994 d->parent_buffer->getMacro(*it, *this, false);
1996 macros.insert(data);
1998 // we cannot access the original MathMacroTemplate anymore
1999 // here to calls validate method. So we do its work here manually.
2000 // FIXME: somehow make the template accessible here.
2001 if (data->optionals() > 0)
2002 features.require("xargs");
2008 Buffer::References & Buffer::references(docstring const & label)
2010 if (d->parent_buffer)
2011 return const_cast<Buffer *>(masterBuffer())->references(label);
2013 RefCache::iterator it = d->ref_cache_.find(label);
2014 if (it != d->ref_cache_.end())
2015 return it->second.second;
2017 static InsetLabel const * dummy_il = 0;
2018 static References const dummy_refs;
2019 it = d->ref_cache_.insert(
2020 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2021 return it->second.second;
2025 Buffer::References const & Buffer::references(docstring const & label) const
2027 return const_cast<Buffer *>(this)->references(label);
2031 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2033 masterBuffer()->d->ref_cache_[label].first = il;
2037 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2039 return masterBuffer()->d->ref_cache_[label].first;
2043 void Buffer::clearReferenceCache() const
2045 if (!d->parent_buffer)
2046 d->ref_cache_.clear();
2050 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2053 //FIXME: This does not work for child documents yet.
2054 LASSERT(code == CITE_CODE, /**/);
2055 // Check if the label 'from' appears more than once
2056 vector<docstring> labels;
2059 keys.fillWithBibKeys(this);
2060 BiblioInfo::const_iterator bit = keys.begin();
2061 BiblioInfo::const_iterator bend = keys.end();
2063 for (; bit != bend; ++bit)
2065 labels.push_back(bit->first);
2068 if (count(labels.begin(), labels.end(), from) > 1)
2071 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2072 if (it->lyxCode() == code) {
2073 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2074 docstring const oldValue = inset.getParam(paramName);
2075 if (oldValue == from)
2076 inset.setParam(paramName, to);
2082 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2083 pit_type par_end, bool full_source)
2085 OutputParams runparams(¶ms().encoding());
2086 runparams.nice = true;
2087 runparams.flavor = OutputParams::LATEX;
2088 runparams.linelen = lyxrc.plaintext_linelen;
2089 // No side effect of file copying and image conversion
2090 runparams.dryrun = true;
2094 os << "% " << _("Preview source code") << "\n\n";
2095 d->texrow.newline();
2096 d->texrow.newline();
2098 writeLaTeXSource(os, filePath(), runparams, true, true);
2100 writeDocBookSource(os, absFileName(), runparams, false);
2102 runparams.par_begin = par_begin;
2103 runparams.par_end = par_end;
2104 if (par_begin + 1 == par_end) {
2106 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2110 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2111 convert<docstring>(par_begin),
2112 convert<docstring>(par_end - 1))
2115 d->texrow.newline();
2116 d->texrow.newline();
2117 // output paragraphs
2119 latexParagraphs(*this, text(), os, d->texrow, runparams);
2122 docbookParagraphs(paragraphs(), *this, os, runparams);
2127 ErrorList & Buffer::errorList(string const & type) const
2129 static ErrorList emptyErrorList;
2130 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2131 if (I == d->errorLists.end())
2132 return emptyErrorList;
2138 void Buffer::structureChanged() const
2141 gui_->structureChanged();
2145 void Buffer::errors(string const & err) const
2152 void Buffer::message(docstring const & msg) const
2159 void Buffer::setBusy(bool on) const
2166 void Buffer::setReadOnly(bool on) const
2169 d->wa_->setReadOnly(on);
2173 void Buffer::updateTitles() const
2176 d->wa_->updateTitles();
2180 void Buffer::resetAutosaveTimers() const
2183 gui_->resetAutosaveTimers();
2187 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2196 class AutoSaveBuffer : public ForkedProcess {
2199 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2200 : buffer_(buffer), fname_(fname) {}
2202 virtual boost::shared_ptr<ForkedProcess> clone() const
2204 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2209 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2210 from_utf8(fname_.absFilename())));
2211 return run(DontWait);
2215 virtual int generateChild();
2217 Buffer const & buffer_;
2222 int AutoSaveBuffer::generateChild()
2224 // tmp_ret will be located (usually) in /tmp
2225 // will that be a problem?
2226 // Note that this calls ForkedCalls::fork(), so it's
2227 // ok cross-platform.
2228 pid_t const pid = fork();
2229 // If you want to debug the autosave
2230 // you should set pid to -1, and comment out the fork.
2231 if (pid != 0 && pid != -1)
2234 // pid = -1 signifies that lyx was unable
2235 // to fork. But we will do the save
2237 bool failed = false;
2238 FileName const tmp_ret = FileName::tempName("lyxauto");
2239 if (!tmp_ret.empty()) {
2240 buffer_.writeFile(tmp_ret);
2241 // assume successful write of tmp_ret
2242 if (!tmp_ret.moveTo(fname_))
2248 // failed to write/rename tmp_ret so try writing direct
2249 if (!buffer_.writeFile(fname_)) {
2250 // It is dangerous to do this in the child,
2251 // but safe in the parent, so...
2252 if (pid == -1) // emit message signal.
2253 buffer_.message(_("Autosave failed!"));
2257 if (pid == 0) // we are the child so...
2266 // Perfect target for a thread...
2267 void Buffer::autoSave() const
2269 if (isBakClean() || isReadonly()) {
2270 // We don't save now, but we'll try again later
2271 resetAutosaveTimers();
2275 // emit message signal.
2276 message(_("Autosaving current document..."));
2278 // create autosave filename
2279 string fname = filePath();
2281 fname += d->filename.onlyFileName();
2284 AutoSaveBuffer autosave(*this, FileName(fname));
2288 resetAutosaveTimers();
2292 string Buffer::bufferFormat() const
2302 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2303 string & result_file) const
2305 string backend_format;
2306 OutputParams runparams(¶ms().encoding());
2307 runparams.flavor = OutputParams::LATEX;
2308 runparams.linelen = lyxrc.plaintext_linelen;
2309 vector<string> backs = backends();
2310 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2311 // Get shortest path to format
2312 Graph::EdgePath path;
2313 for (vector<string>::const_iterator it = backs.begin();
2314 it != backs.end(); ++it) {
2315 Graph::EdgePath p = theConverters().getPath(*it, format);
2316 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2317 backend_format = *it;
2322 runparams.flavor = theConverters().getFlavor(path);
2324 Alert::error(_("Couldn't export file"),
2325 bformat(_("No information for exporting the format %1$s."),
2326 formats.prettyName(format)));
2330 backend_format = format;
2331 // FIXME: Don't hardcode format names here, but use a flag
2332 if (backend_format == "pdflatex")
2333 runparams.flavor = OutputParams::PDFLATEX;
2336 string filename = latexName(false);
2337 filename = addName(temppath(), filename);
2338 filename = changeExtension(filename,
2339 formats.extension(backend_format));
2342 updateMacroInstances();
2344 // Plain text backend
2345 if (backend_format == "text")
2346 writePlaintextFile(*this, FileName(filename), runparams);
2348 else if (backend_format == "lyx")
2349 writeFile(FileName(filename));
2351 else if (isDocBook()) {
2352 runparams.nice = !put_in_tempdir;
2353 makeDocBookFile(FileName(filename), runparams);
2356 else if (backend_format == format) {
2357 runparams.nice = true;
2358 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2360 } else if (!lyxrc.tex_allows_spaces
2361 && contains(filePath(), ' ')) {
2362 Alert::error(_("File name error"),
2363 _("The directory path to the document cannot contain spaces."));
2366 runparams.nice = false;
2367 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2371 string const error_type = (format == "program")
2372 ? "Build" : bufferFormat();
2373 string const ext = formats.extension(format);
2374 FileName const tmp_result_file(changeExtension(filename, ext));
2375 bool const success = theConverters().convert(this, FileName(filename),
2376 tmp_result_file, FileName(absFileName()), backend_format, format,
2377 errorList(error_type));
2378 // Emit the signal to show the error list.
2379 if (format != backend_format)
2384 if (put_in_tempdir) {
2385 result_file = tmp_result_file.absFilename();
2389 result_file = changeExtension(absFileName(), ext);
2390 // We need to copy referenced files (e. g. included graphics
2391 // if format == "dvi") to the result dir.
2392 vector<ExportedFile> const files =
2393 runparams.exportdata->externalFiles(format);
2394 string const dest = onlyPath(result_file);
2395 CopyStatus status = SUCCESS;
2396 for (vector<ExportedFile>::const_iterator it = files.begin();
2397 it != files.end() && status != CANCEL; ++it) {
2398 string const fmt = formats.getFormatFromFile(it->sourceName);
2399 status = copyFile(fmt, it->sourceName,
2400 makeAbsPath(it->exportName, dest),
2401 it->exportName, status == FORCE);
2403 if (status == CANCEL) {
2404 message(_("Document export cancelled."));
2405 } else if (tmp_result_file.exists()) {
2406 // Finally copy the main file
2407 status = copyFile(format, tmp_result_file,
2408 FileName(result_file), result_file,
2410 message(bformat(_("Document exported as %1$s "
2412 formats.prettyName(format),
2413 makeDisplayPath(result_file)));
2415 // This must be a dummy converter like fax (bug 1888)
2416 message(bformat(_("Document exported as %1$s"),
2417 formats.prettyName(format)));
2424 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2427 return doExport(format, put_in_tempdir, result_file);
2431 bool Buffer::preview(string const & format) const
2434 if (!doExport(format, true, result_file))
2436 return formats.view(*this, FileName(result_file), format);
2440 bool Buffer::isExportable(string const & format) const
2442 vector<string> backs = backends();
2443 for (vector<string>::const_iterator it = backs.begin();
2444 it != backs.end(); ++it)
2445 if (theConverters().isReachable(*it, format))
2451 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2453 vector<string> backs = backends();
2454 vector<Format const *> result =
2455 theConverters().getReachable(backs[0], only_viewable, true);
2456 for (vector<string>::const_iterator it = backs.begin() + 1;
2457 it != backs.end(); ++it) {
2458 vector<Format const *> r =
2459 theConverters().getReachable(*it, only_viewable, false);
2460 result.insert(result.end(), r.begin(), r.end());
2466 vector<string> Buffer::backends() const
2469 if (params().baseClass()->isTeXClassAvailable()) {
2470 v.push_back(bufferFormat());
2471 // FIXME: Don't hardcode format names here, but use a flag
2472 if (v.back() == "latex")
2473 v.push_back("pdflatex");
2475 v.push_back("text");
2481 bool Buffer::readFileHelper(FileName const & s)
2483 // File information about normal file
2485 docstring const file = makeDisplayPath(s.absFilename(), 50);
2486 docstring text = bformat(_("The specified document\n%1$s"
2487 "\ncould not be read."), file);
2488 Alert::error(_("Could not read document"), text);
2492 // Check if emergency save file exists and is newer.
2493 FileName const e(s.absFilename() + ".emergency");
2495 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2496 docstring const file = makeDisplayPath(s.absFilename(), 20);
2497 docstring const text =
2498 bformat(_("An emergency save of the document "
2500 "Recover emergency save?"), file);
2501 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2502 _("&Recover"), _("&Load Original"),
2506 // the file is not saved if we load the emergency file.
2516 // Now check if autosave file is newer.
2517 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2519 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2520 docstring const file = makeDisplayPath(s.absFilename(), 20);
2521 docstring const text =
2522 bformat(_("The backup of the document "
2523 "%1$s is newer.\n\nLoad the "
2524 "backup instead?"), file);
2525 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2526 _("&Load backup"), _("Load &original"),
2530 // the file is not saved if we load the autosave file.
2534 // Here we delete the autosave
2545 bool Buffer::loadLyXFile(FileName const & s)
2547 if (s.isReadableFile()) {
2548 if (readFileHelper(s)) {
2549 lyxvc().file_found_hook(s);
2550 if (!s.isWritable())
2555 docstring const file = makeDisplayPath(s.absFilename(), 20);
2556 // Here we probably should run
2557 if (LyXVC::file_not_found_hook(s)) {
2558 docstring const text =
2559 bformat(_("Do you want to retrieve the document"
2560 " %1$s from version control?"), file);
2561 int const ret = Alert::prompt(_("Retrieve from version control?"),
2562 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2565 // How can we know _how_ to do the checkout?
2566 // With the current VC support it has to be,
2567 // a RCS file since CVS do not have special ,v files.
2569 return loadLyXFile(s);
2577 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2579 TeXErrors::Errors::const_iterator cit = terr.begin();
2580 TeXErrors::Errors::const_iterator end = terr.end();
2582 for (; cit != end; ++cit) {
2585 int errorRow = cit->error_in_line;
2586 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2592 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2593 } while (found && id_start == id_end && pos_start == pos_end);
2595 errorList.push_back(ErrorItem(cit->error_desc,
2596 cit->error_text, id_start, pos_start, pos_end));