3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Stefan Schimanski
9 * Full author contact details are available in file CREDITS.
17 #include "LayoutFile.h"
18 #include "BiblioInfo.h"
19 #include "BranchList.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
25 #include "Converter.h"
27 #include "DocIterator.h"
28 #include "EmbeddedFiles.h"
30 #include "ErrorList.h"
33 #include "FuncRequest.h"
34 #include "InsetIterator.h"
35 #include "InsetList.h"
37 #include "LaTeXFeatures.h"
41 #include "LyXAction.h"
45 #include "output_docbook.h"
47 #include "output_latex.h"
48 #include "output_plaintext.h"
49 #include "paragraph_funcs.h"
50 #include "Paragraph.h"
51 #include "ParagraphParameters.h"
52 #include "ParIterator.h"
53 #include "PDFOptions.h"
56 #include "TexStream.h"
58 #include "TextClass.h"
59 #include "TocBackend.h"
61 #include "VCBackend.h"
65 #include "insets/InsetBibitem.h"
66 #include "insets/InsetBibtex.h"
67 #include "insets/InsetInclude.h"
68 #include "insets/InsetText.h"
70 #include "mathed/MacroTable.h"
71 #include "mathed/MathMacroTemplate.h"
72 #include "mathed/MathSupport.h"
74 #include "frontends/alert.h"
75 #include "frontends/Delegates.h"
76 #include "frontends/WorkAreaManager.h"
78 #include "graphics/Previews.h"
80 #include "support/convert.h"
81 #include "support/debug.h"
82 #include "support/ExceptionMessage.h"
83 #include "support/FileName.h"
84 #include "support/FileNameList.h"
85 #include "support/filetools.h"
86 #include "support/ForkedCalls.h"
87 #include "support/gettext.h"
88 #include "support/gzstream.h"
89 #include "support/lstrings.h"
90 #include "support/lyxalgo.h"
91 #include "support/os.h"
92 #include "support/Package.h"
93 #include "support/Path.h"
94 #include "support/textutils.h"
95 #include "support/types.h"
96 #include "support/FileZipListDir.h"
98 #include <boost/bind.hpp>
99 #include <boost/shared_ptr.hpp>
110 using namespace lyx::support;
114 namespace Alert = frontend::Alert;
115 namespace os = support::os;
119 int const LYX_FORMAT = 325;
121 typedef map<string, bool> DepClean;
122 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
129 Impl(Buffer & parent, FileName const & file, bool readonly);
142 mutable TexRow texrow;
143 Buffer const * parent_buffer;
145 /// need to regenerate .tex?
149 mutable bool lyx_clean;
151 /// is autosave needed?
152 mutable bool bak_clean;
154 /// is this a unnamed file (New...)?
160 /// name of the file the buffer is associated with.
163 /** Set to true only when the file is fully loaded.
164 * Used to prevent the premature generation of previews
165 * and by the citation inset.
167 bool file_fully_loaded;
170 mutable TocBackend toc_backend;
173 typedef pair<DocIterator, MacroData> ScopeMacro;
174 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
175 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
176 /// map from the macro name to the position map,
177 /// which maps the macro definition position to the scope and the MacroData.
178 NamePositionScopeMacroMap macros;
181 /// positions of child buffers in the buffer
182 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
183 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
184 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
185 /// position of children buffers in this buffer
186 BufferPositionMap children_positions;
187 /// map from children inclusion positions to their scope and their buffer
188 PositionScopeBufferMap position_to_children;
190 /// Container for all sort of Buffer dependant errors.
191 map<string, ErrorList> errorLists;
193 /// all embedded files of this buffer
194 EmbeddedFileList embedded_files;
196 /// timestamp and checksum used to test if the file has been externally
197 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
199 unsigned long checksum_;
202 frontend::WorkAreaManager * wa_;
207 /// A cache for the bibfiles (including bibfiles of loaded child
208 /// documents), needed for appropriate update of natbib labels.
209 mutable EmbeddedFileList bibfilesCache_;
211 mutable RefCache ref_cache_;
213 /// our Text that should be wrapped in an InsetText
217 /// Creates the per buffer temporary directory
218 static FileName createBufferTmpDir()
221 // We are in our own directory. Why bother to mangle name?
222 // In fact I wrote this code to circumvent a problematic behaviour
223 // (bug?) of EMX mkstemp().
224 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
225 convert<string>(count++));
227 if (!tmpfl.createDirectory(0777)) {
228 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
229 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
230 from_utf8(tmpfl.absFilename())));
236 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
237 : parent_buffer(0), lyx_clean(true), bak_clean(true), unnamed(false),
238 read_only(readonly_), filename(file), file_fully_loaded(false),
239 toc_backend(&parent), macro_lock(false),
240 embedded_files(), timestamp_(0), checksum_(0), wa_(0),
243 temppath = createBufferTmpDir();
244 lyxvc.setBuffer(&parent);
246 wa_ = new frontend::WorkAreaManager;
250 Buffer::Buffer(string const & file, bool readonly)
251 : d(new Impl(*this, FileName(file), readonly)), gui_(0)
253 LYXERR(Debug::INFO, "Buffer::Buffer()");
255 d->inset.setBuffer(*this);
256 d->inset.initParagraphs(*this);
257 d->inset.setAutoBreakRows(true);
258 d->inset.getText(0)->setMacrocontextPosition(par_iterator_begin());
264 LYXERR(Debug::INFO, "Buffer::~Buffer()");
265 // here the buffer should take care that it is
266 // saved properly, before it goes into the void.
268 // GuiView already destroyed
271 // clear references to children in macro tables
272 d->children_positions.clear();
273 d->position_to_children.clear();
275 if (!d->temppath.destroyDirectory()) {
276 Alert::warning(_("Could not remove temporary directory"),
277 bformat(_("Could not remove the temporary directory %1$s"),
278 from_utf8(d->temppath.absFilename())));
281 // Remove any previewed LaTeX snippets associated with this buffer.
282 graphics::Previews::get().removeLoader(*this);
288 void Buffer::changed() const
295 frontend::WorkAreaManager & Buffer::workAreaManager() const
297 BOOST_ASSERT(d->wa_);
302 Text & Buffer::text() const
304 return const_cast<Text &>(d->inset.text_);
308 Inset & Buffer::inset() const
310 return const_cast<InsetText &>(d->inset);
314 BufferParams & Buffer::params()
320 BufferParams const & Buffer::params() const
326 ParagraphList & Buffer::paragraphs()
328 return text().paragraphs();
332 ParagraphList const & Buffer::paragraphs() const
334 return text().paragraphs();
338 LyXVC & Buffer::lyxvc()
344 LyXVC const & Buffer::lyxvc() const
350 string const Buffer::temppath() const
352 return d->temppath.absFilename();
356 TexRow const & Buffer::texrow() const
362 TocBackend & Buffer::tocBackend() const
364 return d->toc_backend;
368 EmbeddedFileList & Buffer::embeddedFiles()
370 return d->embedded_files;
374 EmbeddedFileList const & Buffer::embeddedFiles() const
376 return d->embedded_files;
380 bool Buffer::embedded() const
382 return params().embedded;
386 Undo & Buffer::undo()
392 string Buffer::latexName(bool const no_path) const
394 FileName latex_name = makeLatexName(d->filename);
395 return no_path ? latex_name.onlyFileName()
396 : latex_name.absFilename();
400 string Buffer::logName(LogType * type) const
402 string const filename = latexName(false);
404 if (filename.empty()) {
410 string const path = temppath();
412 FileName const fname(addName(temppath(),
413 onlyFilename(changeExtension(filename,
415 FileName const bname(
416 addName(path, onlyFilename(
417 changeExtension(filename,
418 formats.extension("literate") + ".out"))));
420 // If no Latex log or Build log is newer, show Build log
422 if (bname.exists() &&
423 (!fname.exists() || fname.lastModified() < bname.lastModified())) {
424 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
427 return bname.absFilename();
429 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
432 return fname.absFilename();
436 void Buffer::setReadonly(bool const flag)
438 if (d->read_only != flag) {
445 void Buffer::setFileName(string const & newfile)
447 d->filename = makeAbsPath(newfile);
448 setReadonly(d->filename.isReadOnly());
453 int Buffer::readHeader(Lexer & lex)
455 int unknown_tokens = 0;
457 int begin_header_line = -1;
459 // Initialize parameters that may be/go lacking in header:
460 params().branchlist().clear();
461 params().preamble.erase();
462 params().options.erase();
463 params().float_placement.erase();
464 params().paperwidth.erase();
465 params().paperheight.erase();
466 params().leftmargin.erase();
467 params().rightmargin.erase();
468 params().topmargin.erase();
469 params().bottommargin.erase();
470 params().headheight.erase();
471 params().headsep.erase();
472 params().footskip.erase();
473 params().columnsep.erase();
474 params().listings_params.clear();
475 params().clearLayoutModules();
476 params().pdfoptions().clear();
478 for (int i = 0; i < 4; ++i) {
479 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
480 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
483 ErrorList & errorList = d->errorLists["Parse"];
492 if (token == "\\end_header")
496 if (token == "\\begin_header") {
497 begin_header_line = line;
501 LYXERR(Debug::PARSER, "Handling document header token: `"
504 string unknown = params().readToken(lex, token, d->filename.onlyPath(),
506 if (!unknown.empty()) {
507 if (unknown[0] != '\\' && token == "\\textclass") {
508 Alert::warning(_("Unknown document class"),
509 bformat(_("Using the default document class, because the "
510 "class %1$s is unknown."), from_utf8(unknown)));
513 docstring const s = bformat(_("Unknown token: "
517 errorList.push_back(ErrorItem(_("Document header error"),
522 if (begin_header_line) {
523 docstring const s = _("\\begin_header is missing");
524 errorList.push_back(ErrorItem(_("Document header error"),
528 params().makeDocumentClass();
530 return unknown_tokens;
535 // changed to be public and have one parameter
536 // Returns false if "\end_document" is not read (Asger)
537 bool Buffer::readDocument(Lexer & lex)
539 ErrorList & errorList = d->errorLists["Parse"];
542 if (!lex.checkFor("\\begin_document")) {
543 docstring const s = _("\\begin_document is missing");
544 errorList.push_back(ErrorItem(_("Document header error"),
548 // we are reading in a brand new document
549 BOOST_ASSERT(paragraphs().empty());
553 if (params().outputChanges) {
554 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
555 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
556 LaTeXFeatures::isAvailable("xcolor");
558 if (!dvipost && !xcolorsoul) {
559 Alert::warning(_("Changes not shown in LaTeX output"),
560 _("Changes will not be highlighted in LaTeX output, "
561 "because neither dvipost nor xcolor/soul are installed.\n"
562 "Please install these packages or redefine "
563 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
564 } else if (!xcolorsoul) {
565 Alert::warning(_("Changes not shown in LaTeX output"),
566 _("Changes will not be highlighted in LaTeX output "
567 "when using pdflatex, because xcolor and soul are not installed.\n"
568 "Please install both packages or redefine "
569 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
574 bool const res = text().read(*this, lex, errorList, &(d->inset));
576 // Enable embeded files, which will set temp path and move
577 // inconsistent inzip files if needed.
579 embeddedFiles().validate(*this);
580 embeddedFiles().enable(params().embedded, *this, false);
581 } catch (ExceptionMessage const & message) {
582 Alert::error(message.title_, message.details_);
583 Alert::warning(_("Failed to read embedded files"),
584 _("Due to most likely a bug, LyX failed to locate all embedded "
585 "file. If you unzip the LyX file, you should be able to see and "
586 "open content.lyx which is your main text. You may also be able "
587 "to recover some embedded files. Please report this bug to the "
588 "lyx-devel mailing list."));
593 updateMacroInstances();
598 // needed to insert the selection
599 void Buffer::insertStringAsLines(ParagraphList & pars,
600 pit_type & pit, pos_type & pos,
601 Font const & fn, docstring const & str, bool autobreakrows)
605 // insert the string, don't insert doublespace
606 bool space_inserted = true;
607 for (docstring::const_iterator cit = str.begin();
608 cit != str.end(); ++cit) {
609 Paragraph & par = pars[pit];
611 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
612 breakParagraph(params(), pars, pit, pos,
613 par.layout().isEnvironment());
616 space_inserted = true;
620 // do not insert consecutive spaces if !free_spacing
621 } else if ((*cit == ' ' || *cit == '\t') &&
622 space_inserted && !par.isFreeSpacing()) {
624 } else if (*cit == '\t') {
625 if (!par.isFreeSpacing()) {
626 // tabs are like spaces here
627 par.insertChar(pos, ' ', font, params().trackChanges);
629 space_inserted = true;
631 const pos_type n = 8 - pos % 8;
632 for (pos_type i = 0; i < n; ++i) {
633 par.insertChar(pos, ' ', font, params().trackChanges);
636 space_inserted = true;
638 } else if (!isPrintable(*cit)) {
639 // Ignore unprintables
642 // just insert the character
643 par.insertChar(pos, *cit, font, params().trackChanges);
645 space_inserted = (*cit == ' ');
652 bool Buffer::readString(string const & s)
654 params().compressed = false;
656 // remove dummy empty par
657 paragraphs().clear();
661 FileName const name = FileName::tempName();
662 switch (readFile(lex, name, true)) {
666 // We need to call lyx2lyx, so write the input to a file
667 ofstream os(name.toFilesystemEncoding().c_str());
670 return readFile(name);
680 bool Buffer::readFile(FileName const & filename)
682 FileName fname(filename);
683 // Check if the file is compressed.
684 string format = filename.guessFormatFromContents();
685 if (format == "zip") {
686 // decompress to a temp directory
687 LYXERR(Debug::FILES, filename << " is in zip format. Unzip to " << temppath());
688 ::unzipToDir(filename.toFilesystemEncoding(), temppath());
690 FileName lyxfile(addName(temppath(), "content.lyx"));
691 // if both manifest.txt and file.lyx exist, this is am embedded file
692 if (lyxfile.exists()) {
693 // if in bundled format, save checksum of the compressed file, not content.lyx
694 saveCheckSum(filename);
695 params().embedded = true;
699 // The embedded lyx file can also be compressed, for backward compatibility
700 format = fname.guessFormatFromContents();
701 if (format == "gzip" || format == "zip" || format == "compress")
702 params().compressed = true;
704 // remove dummy empty par
705 paragraphs().clear();
708 if (readFile(lex, fname) != success)
715 bool Buffer::isFullyLoaded() const
717 return d->file_fully_loaded;
721 void Buffer::setFullyLoaded(bool value)
723 d->file_fully_loaded = value;
727 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
730 BOOST_ASSERT(!filename.empty());
732 // the first (non-comment) token _must_ be...
733 if (!lex.checkFor("\\lyxformat")) {
734 Alert::error(_("Document format failure"),
735 bformat(_("%1$s is not a readable LyX document."),
736 from_utf8(filename.absFilename())));
742 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
743 // if present remove ".," from string.
744 size_t dot = tmp_format.find_first_of(".,");
745 //lyxerr << " dot found at " << dot << endl;
746 if (dot != string::npos)
747 tmp_format.erase(dot, 1);
748 int const file_format = convert<int>(tmp_format);
749 //lyxerr << "format: " << file_format << endl;
751 // save timestamp and checksum of the original disk file, making sure
752 // to not overwrite them with those of the file created in the tempdir
753 // when it has to be converted to the current format.
755 // Save the timestamp and checksum of disk file. If filename is an
756 // emergency file, save the timestamp and checksum of the original lyx file
757 // because isExternallyModified will check for this file. (BUG4193)
758 string diskfile = filename.absFilename();
759 if (suffixIs(diskfile, ".emergency"))
760 diskfile = diskfile.substr(0, diskfile.size() - 10);
761 saveCheckSum(FileName(diskfile));
764 if (file_format != LYX_FORMAT) {
767 // lyx2lyx would fail
770 FileName const tmpfile = FileName::tempName();
771 if (tmpfile.empty()) {
772 Alert::error(_("Conversion failed"),
773 bformat(_("%1$s is from a different"
774 " version of LyX, but a temporary"
775 " file for converting it could"
777 from_utf8(filename.absFilename())));
780 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
781 if (lyx2lyx.empty()) {
782 Alert::error(_("Conversion script not found"),
783 bformat(_("%1$s is from a different"
784 " version of LyX, but the"
785 " conversion script lyx2lyx"
786 " could not be found."),
787 from_utf8(filename.absFilename())));
790 ostringstream command;
791 command << os::python()
792 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
793 << " -t " << convert<string>(LYX_FORMAT)
794 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
795 << ' ' << quoteName(filename.toFilesystemEncoding());
796 string const command_str = command.str();
798 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
800 cmd_ret const ret = runCommand(command_str);
801 if (ret.first != 0) {
802 Alert::error(_("Conversion script failed"),
803 bformat(_("%1$s is from a different version"
804 " of LyX, but the lyx2lyx script"
805 " failed to convert it."),
806 from_utf8(filename.absFilename())));
809 bool const ret = readFile(tmpfile);
810 // Do stuff with tmpfile name and buffer name here.
811 return ret ? success : failure;
816 if (readDocument(lex)) {
817 Alert::error(_("Document format failure"),
818 bformat(_("%1$s ended unexpectedly, which means"
819 " that it is probably corrupted."),
820 from_utf8(filename.absFilename())));
823 d->file_fully_loaded = true;
828 // Should probably be moved to somewhere else: BufferView? LyXView?
829 bool Buffer::save() const
831 // We don't need autosaves in the immediate future. (Asger)
832 resetAutosaveTimers();
834 string const encodedFilename = d->filename.toFilesystemEncoding();
837 bool madeBackup = false;
839 // make a backup if the file already exists
840 if (lyxrc.make_backup && fileName().exists()) {
841 backupName = FileName(absFileName() + '~');
842 if (!lyxrc.backupdir_path.empty()) {
843 string const mangledName =
844 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
845 backupName = FileName(addName(lyxrc.backupdir_path,
848 if (fileName().copyTo(backupName)) {
851 Alert::error(_("Backup failure"),
852 bformat(_("Cannot create backup file %1$s.\n"
853 "Please check whether the directory exists and is writeable."),
854 from_utf8(backupName.absFilename())));
855 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
859 // ask if the disk file has been externally modified (use checksum method)
860 if (fileName().exists() && isExternallyModified(checksum_method)) {
861 docstring const file = makeDisplayPath(absFileName(), 20);
862 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
863 "you want to overwrite this file?"), file);
864 int const ret = Alert::prompt(_("Overwrite modified file?"),
865 text, 1, 1, _("&Overwrite"), _("&Cancel"));
870 if (writeFile(d->filename)) {
874 // Saving failed, so backup is not backup
876 backupName.moveTo(d->filename);
882 bool Buffer::writeFile(FileName const & fname) const
884 if (d->read_only && fname == d->filename)
890 if (params().embedded)
891 // first write the .lyx file to the temporary directory
892 content = FileName(addName(temppath(), "content.lyx"));
896 docstring const str = bformat(_("Saving document %1$s..."),
897 makeDisplayPath(content.absFilename()));
900 if (params().compressed) {
901 gz::ogzstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
902 retval = ofs && write(ofs);
904 ofstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
905 retval = ofs && write(ofs);
909 message(str + _(" could not write file!"));
913 removeAutosaveFile(d->filename.absFilename());
915 if (params().embedded) {
916 message(str + _(" writing embedded files."));
917 // if embedding is enabled, write file.lyx and all the embedded files
918 // to the zip file fname.
919 if (!d->embedded_files.writeFile(fname, *this)) {
920 message(str + _(" could not write embedded files!"));
924 saveCheckSum(d->filename);
925 message(str + _(" done."));
931 bool Buffer::write(ostream & ofs) const
934 // Use the standard "C" locale for file output.
935 ofs.imbue(locale::classic());
938 // The top of the file should not be written by params().
940 // write out a comment in the top of the file
941 ofs << "#LyX " << lyx_version
942 << " created this file. For more info see http://www.lyx.org/\n"
943 << "\\lyxformat " << LYX_FORMAT << "\n"
944 << "\\begin_document\n";
946 /// For each author, set 'used' to true if there is a change
947 /// by this author in the document; otherwise set it to 'false'.
948 AuthorList::Authors::const_iterator a_it = params().authors().begin();
949 AuthorList::Authors::const_iterator a_end = params().authors().end();
950 for (; a_it != a_end; ++a_it)
951 a_it->second.setUsed(false);
953 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
954 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
955 for ( ; it != end; ++it)
956 it->checkAuthors(params().authors());
958 // now write out the buffer parameters.
959 ofs << "\\begin_header\n";
960 params().writeFile(ofs);
961 ofs << "\\end_header\n";
964 ofs << "\n\\begin_body\n";
965 text().write(*this, ofs);
966 ofs << "\n\\end_body\n";
968 // Write marker that shows file is complete
969 ofs << "\\end_document" << endl;
971 // Shouldn't really be needed....
974 // how to check if close went ok?
975 // Following is an attempt... (BE 20001011)
977 // good() returns false if any error occured, including some
979 // bad() returns true if something bad happened in the buffer,
980 // which should include file system full errors.
985 lyxerr << "File was not closed properly." << endl;
992 bool Buffer::makeLaTeXFile(FileName const & fname,
993 string const & original_path,
994 OutputParams const & runparams,
995 bool output_preamble, bool output_body) const
997 string const encoding = runparams.encoding->iconvName();
998 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1001 try { ofs.reset(encoding); }
1002 catch (iconv_codecvt_facet_exception & e) {
1003 lyxerr << "Caught iconv exception: " << e.what() << endl;
1004 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1005 "verify that the support software for your encoding (%1$s) is "
1006 "properly installed"), from_ascii(encoding)));
1009 if (!openFileWrite(ofs, fname))
1012 //TexStream ts(ofs.rdbuf(), &texrow());
1013 ErrorList & errorList = d->errorLists["Export"];
1015 bool failed_export = false;
1018 writeLaTeXSource(ofs, original_path,
1019 runparams, output_preamble, output_body);
1021 catch (EncodingException & e) {
1022 odocstringstream ods;
1023 ods.put(e.failed_char);
1025 oss << "0x" << hex << e.failed_char << dec;
1026 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1027 " (code point %2$s)"),
1028 ods.str(), from_utf8(oss.str()));
1029 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1030 "representable in the chosen encoding.\n"
1031 "Changing the document encoding to utf8 could help."),
1032 e.par_id, e.pos, e.pos + 1));
1033 failed_export = true;
1035 catch (iconv_codecvt_facet_exception & e) {
1036 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1037 _(e.what()), -1, 0, 0));
1038 failed_export = true;
1040 catch (exception const & e) {
1041 errorList.push_back(ErrorItem(_("conversion failed"),
1042 _(e.what()), -1, 0, 0));
1043 failed_export = true;
1046 lyxerr << "Caught some really weird exception..." << endl;
1047 LyX::cref().exit(1);
1052 failed_export = true;
1053 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1057 return !failed_export;
1061 void Buffer::writeLaTeXSource(odocstream & os,
1062 string const & original_path,
1063 OutputParams const & runparams_in,
1064 bool const output_preamble, bool const output_body) const
1066 // The child documents, if any, shall be already loaded at this point.
1068 OutputParams runparams = runparams_in;
1070 // validate the buffer.
1071 LYXERR(Debug::LATEX, " Validating buffer...");
1072 LaTeXFeatures features(*this, params(), runparams);
1074 LYXERR(Debug::LATEX, " Buffer validation done.");
1076 // The starting paragraph of the coming rows is the
1077 // first paragraph of the document. (Asger)
1078 if (output_preamble && runparams.nice) {
1079 os << "%% LyX " << lyx_version << " created this file. "
1080 "For more info, see http://www.lyx.org/.\n"
1081 "%% Do not edit unless you really know what "
1083 d->texrow.newline();
1084 d->texrow.newline();
1086 LYXERR(Debug::INFO, "lyx document header finished");
1088 // Don't move this behind the parent_buffer=0 code below,
1089 // because then the macros will not get the right "redefinition"
1090 // flag as they don't see the parent macros which are output before.
1093 // fold macros if possible, still with parent buffer as the
1094 // macros will be put in the prefix anyway.
1095 updateMacroInstances();
1097 // There are a few differences between nice LaTeX and usual files:
1098 // usual is \batchmode and has a
1099 // special input@path to allow the including of figures
1100 // with either \input or \includegraphics (what figinsets do).
1101 // input@path is set when the actual parameter
1102 // original_path is set. This is done for usual tex-file, but not
1103 // for nice-latex-file. (Matthias 250696)
1104 // Note that input@path is only needed for something the user does
1105 // in the preamble, included .tex files or ERT, files included by
1106 // LyX work without it.
1107 if (output_preamble) {
1108 if (!runparams.nice) {
1109 // code for usual, NOT nice-latex-file
1110 os << "\\batchmode\n"; // changed
1111 // from \nonstopmode
1112 d->texrow.newline();
1114 if (!original_path.empty()) {
1116 // We don't know the encoding of inputpath
1117 docstring const inputpath = from_utf8(latex_path(original_path));
1118 os << "\\makeatletter\n"
1119 << "\\def\\input@path{{"
1120 << inputpath << "/}}\n"
1121 << "\\makeatother\n";
1122 d->texrow.newline();
1123 d->texrow.newline();
1124 d->texrow.newline();
1127 // get parent macros (if this buffer has a parent) which will be
1128 // written at the document begin further down.
1129 MacroSet parentMacros;
1130 listParentMacros(parentMacros, features);
1132 // Write the preamble
1133 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1139 os << "\\begin{document}\n";
1140 d->texrow.newline();
1142 // output the parent macros
1143 MacroSet::iterator it = parentMacros.begin();
1144 MacroSet::iterator end = parentMacros.end();
1145 for (; it != end; ++it)
1146 (*it)->write(os, true);
1147 } // output_preamble
1149 d->texrow.start(paragraphs().begin()->id(), 0);
1151 LYXERR(Debug::INFO, "preamble finished, now the body.");
1153 // if we are doing a real file with body, even if this is the
1154 // child of some other buffer, let's cut the link here.
1155 // This happens for example if only a child document is printed.
1156 Buffer const * save_parent = 0;
1157 if (output_preamble) {
1158 save_parent = d->parent_buffer;
1159 d->parent_buffer = 0;
1163 latexParagraphs(*this, text(), os, d->texrow, runparams);
1165 // Restore the parenthood if needed
1166 if (output_preamble)
1167 d->parent_buffer = save_parent;
1169 // add this just in case after all the paragraphs
1171 d->texrow.newline();
1173 if (output_preamble) {
1174 os << "\\end{document}\n";
1175 d->texrow.newline();
1176 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1178 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1180 runparams_in.encoding = runparams.encoding;
1182 // Just to be sure. (Asger)
1183 d->texrow.newline();
1185 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1186 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1190 bool Buffer::isLatex() const
1192 return params().documentClass().outputType() == LATEX;
1196 bool Buffer::isLiterate() const
1198 return params().documentClass().outputType() == LITERATE;
1202 bool Buffer::isDocBook() const
1204 return params().documentClass().outputType() == DOCBOOK;
1208 void Buffer::makeDocBookFile(FileName const & fname,
1209 OutputParams const & runparams,
1210 bool const body_only) const
1212 LYXERR(Debug::LATEX, "makeDocBookFile...");
1215 if (!openFileWrite(ofs, fname))
1218 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1222 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1226 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1227 OutputParams const & runparams,
1228 bool const only_body) const
1230 LaTeXFeatures features(*this, params(), runparams);
1235 DocumentClass const & tclass = params().documentClass();
1236 string const top_element = tclass.latexname();
1239 if (runparams.flavor == OutputParams::XML)
1240 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1243 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1246 if (! tclass.class_header().empty())
1247 os << from_ascii(tclass.class_header());
1248 else if (runparams.flavor == OutputParams::XML)
1249 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1250 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1252 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1254 docstring preamble = from_utf8(params().preamble);
1255 if (runparams.flavor != OutputParams::XML ) {
1256 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1257 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1258 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1259 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1262 string const name = runparams.nice
1263 ? changeExtension(absFileName(), ".sgml") : fname;
1264 preamble += features.getIncludedFiles(name);
1265 preamble += features.getLyXSGMLEntities();
1267 if (!preamble.empty()) {
1268 os << "\n [ " << preamble << " ]";
1273 string top = top_element;
1275 if (runparams.flavor == OutputParams::XML)
1276 top += params().language->code();
1278 top += params().language->code().substr(0,2);
1281 if (!params().options.empty()) {
1283 top += params().options;
1286 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1287 << " file was created by LyX " << lyx_version
1288 << "\n See http://www.lyx.org/ for more information -->\n";
1290 params().documentClass().counters().reset();
1294 sgml::openTag(os, top);
1296 docbookParagraphs(paragraphs(), *this, os, runparams);
1297 sgml::closeTag(os, top_element);
1301 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1302 // Other flags: -wall -v0 -x
1303 int Buffer::runChktex()
1307 // get LaTeX-Filename
1308 FileName const path(temppath());
1309 string const name = addName(path.absFilename(), latexName());
1310 string const org_path = filePath();
1312 PathChanger p(path); // path to LaTeX file
1313 message(_("Running chktex..."));
1315 // Generate the LaTeX file if neccessary
1316 OutputParams runparams(¶ms().encoding());
1317 runparams.flavor = OutputParams::LATEX;
1318 runparams.nice = false;
1319 makeLaTeXFile(FileName(name), org_path, runparams);
1322 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1323 int const res = chktex.run(terr); // run chktex
1326 Alert::error(_("chktex failure"),
1327 _("Could not run chktex successfully."));
1328 } else if (res > 0) {
1329 ErrorList & errlist = d->errorLists["ChkTeX"];
1331 bufferErrors(terr, errlist);
1342 void Buffer::validate(LaTeXFeatures & features) const
1344 params().validate(features);
1348 for_each(paragraphs().begin(), paragraphs().end(),
1349 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1351 if (lyxerr.debugging(Debug::LATEX)) {
1352 features.showStruct();
1357 void Buffer::getLabelList(vector<docstring> & list) const
1359 // If this is a child document, use the parent's list instead.
1360 if (d->parent_buffer) {
1361 d->parent_buffer->getLabelList(list);
1366 Toc & toc = d->toc_backend.toc("label");
1367 TocIterator toc_it = toc.begin();
1368 TocIterator end = toc.end();
1369 for (; toc_it != end; ++toc_it) {
1370 if (toc_it->depth() == 0)
1371 list.push_back(toc_it->str());
1376 void Buffer::updateBibfilesCache() const
1378 // If this is a child document, use the parent's cache instead.
1379 if (d->parent_buffer) {
1380 d->parent_buffer->updateBibfilesCache();
1384 d->bibfilesCache_.clear();
1385 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1386 if (it->lyxCode() == BIBTEX_CODE) {
1387 InsetBibtex const & inset =
1388 static_cast<InsetBibtex const &>(*it);
1389 EmbeddedFileList const bibfiles = inset.getBibFiles();
1390 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1393 } else if (it->lyxCode() == INCLUDE_CODE) {
1394 InsetInclude & inset =
1395 static_cast<InsetInclude &>(*it);
1396 inset.updateBibfilesCache();
1397 EmbeddedFileList const & bibfiles =
1398 inset.getBibfilesCache(*this);
1399 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1407 EmbeddedFileList const & Buffer::getBibfilesCache() const
1409 // If this is a child document, use the parent's cache instead.
1410 if (d->parent_buffer)
1411 return d->parent_buffer->getBibfilesCache();
1413 // We update the cache when first used instead of at loading time.
1414 if (d->bibfilesCache_.empty())
1415 const_cast<Buffer *>(this)->updateBibfilesCache();
1417 return d->bibfilesCache_;
1421 bool Buffer::isDepClean(string const & name) const
1423 DepClean::const_iterator const it = d->dep_clean.find(name);
1424 if (it == d->dep_clean.end())
1430 void Buffer::markDepClean(string const & name)
1432 d->dep_clean[name] = true;
1436 bool Buffer::dispatch(string const & command, bool * result)
1438 return dispatch(lyxaction.lookupFunc(command), result);
1442 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1444 bool dispatched = true;
1446 switch (func.action) {
1447 case LFUN_BUFFER_EXPORT: {
1448 bool const tmp = doExport(to_utf8(func.argument()), false);
1461 void Buffer::changeLanguage(Language const * from, Language const * to)
1466 for_each(par_iterator_begin(),
1468 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1472 bool Buffer::isMultiLingual() const
1474 ParConstIterator end = par_iterator_end();
1475 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1476 if (it->isMultiLingual(params()))
1483 DocIterator Buffer::getParFromID(int const id) const
1486 // John says this is called with id == -1 from undo
1487 lyxerr << "getParFromID(), id: " << id << endl;
1488 return doc_iterator_end(inset());
1491 for (DocIterator it = doc_iterator_begin(inset()); !it.atEnd(); it.forwardPar())
1492 if (it.paragraph().id() == id)
1495 return doc_iterator_end(inset());
1499 bool Buffer::hasParWithID(int const id) const
1501 return !getParFromID(id).atEnd();
1505 ParIterator Buffer::par_iterator_begin()
1507 return ParIterator(doc_iterator_begin(inset()));
1511 ParIterator Buffer::par_iterator_end()
1513 return ParIterator(doc_iterator_end(inset()));
1517 ParConstIterator Buffer::par_iterator_begin() const
1519 return lyx::par_const_iterator_begin(inset());
1523 ParConstIterator Buffer::par_iterator_end() const
1525 return lyx::par_const_iterator_end(inset());
1529 Language const * Buffer::language() const
1531 return params().language;
1535 docstring const Buffer::B_(string const & l10n) const
1537 return params().B_(l10n);
1541 bool Buffer::isClean() const
1543 return d->lyx_clean;
1547 bool Buffer::isBakClean() const
1549 return d->bak_clean;
1553 bool Buffer::isExternallyModified(CheckMethod method) const
1555 BOOST_ASSERT(d->filename.exists());
1556 // if method == timestamp, check timestamp before checksum
1557 return (method == checksum_method
1558 || d->timestamp_ != d->filename.lastModified())
1559 && d->checksum_ != d->filename.checksum();
1563 void Buffer::saveCheckSum(FileName const & file) const
1565 if (file.exists()) {
1566 d->timestamp_ = file.lastModified();
1567 d->checksum_ = file.checksum();
1569 // in the case of save to a new file.
1576 void Buffer::markClean() const
1578 if (!d->lyx_clean) {
1579 d->lyx_clean = true;
1582 // if the .lyx file has been saved, we don't need an
1584 d->bak_clean = true;
1588 void Buffer::markBakClean() const
1590 d->bak_clean = true;
1594 void Buffer::setUnnamed(bool flag)
1600 bool Buffer::isUnnamed() const
1606 // FIXME: this function should be moved to buffer_pimpl.C
1607 void Buffer::markDirty()
1610 d->lyx_clean = false;
1613 d->bak_clean = false;
1615 DepClean::iterator it = d->dep_clean.begin();
1616 DepClean::const_iterator const end = d->dep_clean.end();
1618 for (; it != end; ++it)
1623 FileName Buffer::fileName() const
1629 string Buffer::absFileName() const
1631 return d->filename.absFilename();
1635 string Buffer::filePath() const
1637 return d->filename.onlyPath().absFilename() + "/";
1641 bool Buffer::isReadonly() const
1643 return d->read_only;
1647 void Buffer::setParent(Buffer const * buffer)
1649 // Avoids recursive include.
1650 d->parent_buffer = buffer == this ? 0 : buffer;
1655 Buffer const * Buffer::parent()
1657 return d->parent_buffer;
1661 Buffer const * Buffer::masterBuffer() const
1663 if (!d->parent_buffer)
1666 return d->parent_buffer->masterBuffer();
1670 template<typename M>
1671 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
1676 typename M::iterator it = m.lower_bound(x);
1677 if (it == m.begin())
1685 MacroData const * Buffer::getBufferMacro(docstring const & name,
1686 DocIterator const & pos) const
1688 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
1690 // if paragraphs have no macro context set, pos will be empty
1694 // we haven't found anything yet
1695 DocIterator bestPos = par_iterator_begin();
1696 MacroData const * bestData = 0;
1698 // find macro definitions for name
1699 Impl::NamePositionScopeMacroMap::iterator nameIt
1700 = d->macros.find(name);
1701 if (nameIt != d->macros.end()) {
1702 // find last definition in front of pos or at pos itself
1703 Impl::PositionScopeMacroMap::const_iterator it
1704 = greatest_below(nameIt->second, pos);
1705 if (it != nameIt->second.end()) {
1707 // scope ends behind pos?
1708 if (pos < it->second.first) {
1709 // Looks good, remember this. If there
1710 // is no external macro behind this,
1711 // we found the right one already.
1712 bestPos = it->first;
1713 bestData = &it->second.second;
1717 // try previous macro if there is one
1718 if (it == nameIt->second.begin())
1725 // find macros in included files
1726 Impl::PositionScopeBufferMap::const_iterator it
1727 = greatest_below(d->position_to_children, pos);
1728 if (it == d->position_to_children.end())
1729 // no children before
1733 // do we know something better (i.e. later) already?
1734 if (it->first < bestPos )
1737 // scope ends behind pos?
1738 if (pos < it->second.first) {
1739 // look for macro in external file
1740 d->macro_lock = true;
1741 MacroData const * data
1742 = it->second.second->getMacro(name, false);
1743 d->macro_lock = false;
1745 bestPos = it->first;
1751 // try previous file if there is one
1752 if (it == d->position_to_children.begin())
1757 // return the best macro we have found
1762 MacroData const * Buffer::getMacro(docstring const & name,
1763 DocIterator const & pos, bool global) const
1768 // query buffer macros
1769 MacroData const * data = getBufferMacro(name, pos);
1773 // If there is a master buffer, query that
1774 if (d->parent_buffer) {
1775 d->macro_lock = true;
1776 MacroData const * macro = d->parent_buffer->getMacro(
1777 name, *this, false);
1778 d->macro_lock = false;
1784 data = MacroTable::globalMacros().get(name);
1793 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
1795 // set scope end behind the last paragraph
1796 DocIterator scope = par_iterator_begin();
1797 scope.pit() = scope.lastpit() + 1;
1799 return getMacro(name, scope, global);
1803 MacroData const * Buffer::getMacro(docstring const & name,
1804 Buffer const & child, bool global) const
1806 // look where the child buffer is included first
1807 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
1808 if (it == d->children_positions.end())
1811 // check for macros at the inclusion position
1812 return getMacro(name, it->second, global);
1816 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
1818 pit_type lastpit = it.lastpit();
1820 // look for macros in each paragraph
1821 while (it.pit() <= lastpit) {
1822 Paragraph & par = it.paragraph();
1824 // iterate over the insets of the current paragraph
1825 InsetList const & insets = par.insetList();
1826 InsetList::const_iterator iit = insets.begin();
1827 InsetList::const_iterator end = insets.end();
1828 for (; iit != end; ++iit) {
1829 it.pos() = iit->pos;
1831 // is it a nested text inset?
1832 if (iit->inset->asInsetText()) {
1833 // Inset needs its own scope?
1834 InsetText const * itext
1835 = iit->inset->asInsetText();
1836 bool newScope = itext->isMacroScope();
1838 // scope which ends just behind the inset
1839 DocIterator insetScope = it;
1842 // collect macros in inset
1843 it.push_back(CursorSlice(*iit->inset));
1844 updateMacros(it, newScope ? insetScope : scope);
1849 // is it an external file?
1850 if (iit->inset->lyxCode() == INCLUDE_CODE) {
1851 // get buffer of external file
1852 InsetCommand const & inset
1853 = static_cast<InsetCommand const &>(*iit->inset);
1854 InsetCommandParams const & ip = inset.params();
1855 d->macro_lock = true;
1856 Buffer * child = loadIfNeeded(*this, ip);
1857 d->macro_lock = false;
1861 // register its position, but only when it is
1862 // included first in the buffer
1863 if (d->children_positions.find(child)
1864 == d->children_positions.end())
1865 d->children_positions[child] = it;
1867 // register child with its scope
1868 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
1872 if (iit->inset->lyxCode() != MATHMACRO_CODE)
1876 MathMacroTemplate & macroTemplate
1877 = static_cast<MathMacroTemplate &>(*iit->inset);
1878 MacroContext mc(*this, it);
1879 macroTemplate.updateToContext(mc);
1882 bool valid = macroTemplate.validMacro();
1883 // FIXME: Should be fixNameAndCheckIfValid() in fact,
1884 // then the BufferView's cursor will be invalid in
1885 // some cases which leads to crashes.
1890 d->macros[macroTemplate.name()][it] =
1891 Impl::ScopeMacro(scope, MacroData(*this, it));
1901 void Buffer::updateMacros() const
1906 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
1908 // start with empty table
1910 d->children_positions.clear();
1911 d->position_to_children.clear();
1913 // Iterate over buffer, starting with first paragraph
1914 // The scope must be bigger than any lookup DocIterator
1915 // later. For the global lookup, lastpit+1 is used, hence
1916 // we use lastpit+2 here.
1917 DocIterator it = par_iterator_begin();
1918 DocIterator outerScope = it;
1919 outerScope.pit() = outerScope.lastpit() + 2;
1920 updateMacros(it, outerScope);
1924 void Buffer::updateMacroInstances() const
1926 LYXERR(Debug::MACROS, "updateMacroInstances for "
1927 << d->filename.onlyFileName());
1928 DocIterator it = doc_iterator_begin(inset());
1929 DocIterator end = doc_iterator_end(inset());
1930 for (; it != end; it.forwardPos()) {
1931 // look for MathData cells in InsetMathNest insets
1932 Inset * inset = it.nextInset();
1936 InsetMath * minset = inset->asInsetMath();
1940 // update macro in all cells of the InsetMathNest
1941 DocIterator::idx_type n = minset->nargs();
1942 MacroContext mc = MacroContext(*this, it);
1943 for (DocIterator::idx_type i = 0; i < n; ++i) {
1944 MathData & data = minset->cell(i);
1945 data.updateMacros(0, mc);
1951 void Buffer::listMacroNames(MacroNameSet & macros) const
1956 d->macro_lock = true;
1958 // loop over macro names
1959 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
1960 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
1961 for (; nameIt != nameEnd; ++nameIt)
1962 macros.insert(nameIt->first);
1964 // loop over children
1965 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
1966 Impl::BufferPositionMap::iterator end = d->children_positions.end();
1967 for (; it != end; ++it)
1968 it->first->listMacroNames(macros);
1971 if (d->parent_buffer)
1972 d->parent_buffer->listMacroNames(macros);
1974 d->macro_lock = false;
1978 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
1980 if (!d->parent_buffer)
1984 d->parent_buffer->listMacroNames(names);
1987 MacroNameSet::iterator it = names.begin();
1988 MacroNameSet::iterator end = names.end();
1989 for (; it != end; ++it) {
1991 MacroData const * data =
1992 d->parent_buffer->getMacro(*it, *this, false);
1994 macros.insert(data);
1996 // we cannot access the original MathMacroTemplate anymore
1997 // here to calls validate method. So we do its work here manually.
1998 // FIXME: somehow make the template accessible here.
1999 if (data->optionals() > 0)
2000 features.require("xargs");
2006 Buffer::References & Buffer::references(docstring const & label)
2008 if (d->parent_buffer)
2009 return const_cast<Buffer *>(masterBuffer())->references(label);
2011 RefCache::iterator it = d->ref_cache_.find(label);
2012 if (it != d->ref_cache_.end())
2013 return it->second.second;
2015 static InsetLabel const * dummy_il = 0;
2016 static References const dummy_refs;
2017 it = d->ref_cache_.insert(
2018 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2019 return it->second.second;
2023 Buffer::References const & Buffer::references(docstring const & label) const
2025 return const_cast<Buffer *>(this)->references(label);
2029 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2031 masterBuffer()->d->ref_cache_[label].first = il;
2035 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2037 return masterBuffer()->d->ref_cache_[label].first;
2041 void Buffer::clearReferenceCache() const
2043 if (!d->parent_buffer)
2044 d->ref_cache_.clear();
2048 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2051 //FIXME: This does not work for child documents yet.
2052 BOOST_ASSERT(code == CITE_CODE);
2053 // Check if the label 'from' appears more than once
2054 vector<docstring> labels;
2057 keys.fillWithBibKeys(this);
2058 BiblioInfo::const_iterator bit = keys.begin();
2059 BiblioInfo::const_iterator bend = keys.end();
2061 for (; bit != bend; ++bit)
2063 labels.push_back(bit->first);
2066 if (count(labels.begin(), labels.end(), from) > 1)
2069 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2070 if (it->lyxCode() == code) {
2071 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2072 docstring const oldValue = inset.getParam(paramName);
2073 if (oldValue == from)
2074 inset.setParam(paramName, to);
2080 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2081 pit_type par_end, bool full_source)
2083 OutputParams runparams(¶ms().encoding());
2084 runparams.nice = true;
2085 runparams.flavor = OutputParams::LATEX;
2086 runparams.linelen = lyxrc.plaintext_linelen;
2087 // No side effect of file copying and image conversion
2088 runparams.dryrun = true;
2092 os << "% " << _("Preview source code") << "\n\n";
2093 d->texrow.newline();
2094 d->texrow.newline();
2096 writeLaTeXSource(os, filePath(), runparams, true, true);
2098 writeDocBookSource(os, absFileName(), runparams, false);
2100 runparams.par_begin = par_begin;
2101 runparams.par_end = par_end;
2102 if (par_begin + 1 == par_end) {
2104 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2108 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2109 convert<docstring>(par_begin),
2110 convert<docstring>(par_end - 1))
2113 d->texrow.newline();
2114 d->texrow.newline();
2115 // output paragraphs
2117 latexParagraphs(*this, text(), os, d->texrow, runparams);
2120 docbookParagraphs(paragraphs(), *this, os, runparams);
2125 ErrorList & Buffer::errorList(string const & type) const
2127 static ErrorList emptyErrorList;
2128 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2129 if (I == d->errorLists.end())
2130 return emptyErrorList;
2136 void Buffer::structureChanged() const
2139 gui_->structureChanged();
2143 void Buffer::errors(string const & err) const
2150 void Buffer::message(docstring const & msg) const
2157 void Buffer::setBusy(bool on) const
2164 void Buffer::setReadOnly(bool on) const
2167 d->wa_->setReadOnly(on);
2171 void Buffer::updateTitles() const
2174 d->wa_->updateTitles();
2178 void Buffer::resetAutosaveTimers() const
2181 gui_->resetAutosaveTimers();
2185 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2194 class AutoSaveBuffer : public ForkedProcess {
2197 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2198 : buffer_(buffer), fname_(fname) {}
2200 virtual boost::shared_ptr<ForkedProcess> clone() const
2202 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2207 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2208 from_utf8(fname_.absFilename())));
2209 return run(DontWait);
2213 virtual int generateChild();
2215 Buffer const & buffer_;
2220 int AutoSaveBuffer::generateChild()
2222 // tmp_ret will be located (usually) in /tmp
2223 // will that be a problem?
2224 // Note that this calls ForkedCalls::fork(), so it's
2225 // ok cross-platform.
2226 pid_t const pid = fork();
2227 // If you want to debug the autosave
2228 // you should set pid to -1, and comment out the fork.
2229 if (pid != 0 && pid != -1)
2232 // pid = -1 signifies that lyx was unable
2233 // to fork. But we will do the save
2235 bool failed = false;
2236 FileName const tmp_ret = FileName::tempName("lyxauto");
2237 if (!tmp_ret.empty()) {
2238 buffer_.writeFile(tmp_ret);
2239 // assume successful write of tmp_ret
2240 if (!tmp_ret.moveTo(fname_))
2246 // failed to write/rename tmp_ret so try writing direct
2247 if (!buffer_.writeFile(fname_)) {
2248 // It is dangerous to do this in the child,
2249 // but safe in the parent, so...
2250 if (pid == -1) // emit message signal.
2251 buffer_.message(_("Autosave failed!"));
2255 if (pid == 0) // we are the child so...
2264 // Perfect target for a thread...
2265 void Buffer::autoSave() const
2267 if (isBakClean() || isReadonly()) {
2268 // We don't save now, but we'll try again later
2269 resetAutosaveTimers();
2273 // emit message signal.
2274 message(_("Autosaving current document..."));
2276 // create autosave filename
2277 string fname = filePath();
2279 fname += d->filename.onlyFileName();
2282 AutoSaveBuffer autosave(*this, FileName(fname));
2286 resetAutosaveTimers();
2290 string Buffer::bufferFormat() const
2300 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2301 string & result_file) const
2303 string backend_format;
2304 OutputParams runparams(¶ms().encoding());
2305 runparams.flavor = OutputParams::LATEX;
2306 runparams.linelen = lyxrc.plaintext_linelen;
2307 vector<string> backs = backends();
2308 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2309 // Get shortest path to format
2310 Graph::EdgePath path;
2311 for (vector<string>::const_iterator it = backs.begin();
2312 it != backs.end(); ++it) {
2313 Graph::EdgePath p = theConverters().getPath(*it, format);
2314 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2315 backend_format = *it;
2320 runparams.flavor = theConverters().getFlavor(path);
2322 Alert::error(_("Couldn't export file"),
2323 bformat(_("No information for exporting the format %1$s."),
2324 formats.prettyName(format)));
2328 backend_format = format;
2329 // FIXME: Don't hardcode format names here, but use a flag
2330 if (backend_format == "pdflatex")
2331 runparams.flavor = OutputParams::PDFLATEX;
2334 string filename = latexName(false);
2335 filename = addName(temppath(), filename);
2336 filename = changeExtension(filename,
2337 formats.extension(backend_format));
2340 updateMacroInstances();
2342 // Plain text backend
2343 if (backend_format == "text")
2344 writePlaintextFile(*this, FileName(filename), runparams);
2346 else if (backend_format == "lyx")
2347 writeFile(FileName(filename));
2349 else if (isDocBook()) {
2350 runparams.nice = !put_in_tempdir;
2351 makeDocBookFile(FileName(filename), runparams);
2354 else if (backend_format == format) {
2355 runparams.nice = true;
2356 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2358 } else if (!lyxrc.tex_allows_spaces
2359 && contains(filePath(), ' ')) {
2360 Alert::error(_("File name error"),
2361 _("The directory path to the document cannot contain spaces."));
2364 runparams.nice = false;
2365 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2369 string const error_type = (format == "program")
2370 ? "Build" : bufferFormat();
2371 string const ext = formats.extension(format);
2372 FileName const tmp_result_file(changeExtension(filename, ext));
2373 bool const success = theConverters().convert(this, FileName(filename),
2374 tmp_result_file, FileName(absFileName()), backend_format, format,
2375 errorList(error_type));
2376 // Emit the signal to show the error list.
2377 if (format != backend_format)
2382 if (put_in_tempdir) {
2383 result_file = tmp_result_file.absFilename();
2387 result_file = changeExtension(absFileName(), ext);
2388 // We need to copy referenced files (e. g. included graphics
2389 // if format == "dvi") to the result dir.
2390 vector<ExportedFile> const files =
2391 runparams.exportdata->externalFiles(format);
2392 string const dest = onlyPath(result_file);
2393 CopyStatus status = SUCCESS;
2394 for (vector<ExportedFile>::const_iterator it = files.begin();
2395 it != files.end() && status != CANCEL; ++it) {
2396 string const fmt = formats.getFormatFromFile(it->sourceName);
2397 status = copyFile(fmt, it->sourceName,
2398 makeAbsPath(it->exportName, dest),
2399 it->exportName, status == FORCE);
2401 if (status == CANCEL) {
2402 message(_("Document export cancelled."));
2403 } else if (tmp_result_file.exists()) {
2404 // Finally copy the main file
2405 status = copyFile(format, tmp_result_file,
2406 FileName(result_file), result_file,
2408 message(bformat(_("Document exported as %1$s "
2410 formats.prettyName(format),
2411 makeDisplayPath(result_file)));
2413 // This must be a dummy converter like fax (bug 1888)
2414 message(bformat(_("Document exported as %1$s"),
2415 formats.prettyName(format)));
2422 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2425 return doExport(format, put_in_tempdir, result_file);
2429 bool Buffer::preview(string const & format) const
2432 if (!doExport(format, true, result_file))
2434 return formats.view(*this, FileName(result_file), format);
2438 bool Buffer::isExportable(string const & format) const
2440 vector<string> backs = backends();
2441 for (vector<string>::const_iterator it = backs.begin();
2442 it != backs.end(); ++it)
2443 if (theConverters().isReachable(*it, format))
2449 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2451 vector<string> backs = backends();
2452 vector<Format const *> result =
2453 theConverters().getReachable(backs[0], only_viewable, true);
2454 for (vector<string>::const_iterator it = backs.begin() + 1;
2455 it != backs.end(); ++it) {
2456 vector<Format const *> r =
2457 theConverters().getReachable(*it, only_viewable, false);
2458 result.insert(result.end(), r.begin(), r.end());
2464 vector<string> Buffer::backends() const
2467 if (params().baseClass()->isTeXClassAvailable()) {
2468 v.push_back(bufferFormat());
2469 // FIXME: Don't hardcode format names here, but use a flag
2470 if (v.back() == "latex")
2471 v.push_back("pdflatex");
2473 v.push_back("text");
2479 bool Buffer::readFileHelper(FileName const & s)
2481 // File information about normal file
2483 docstring const file = makeDisplayPath(s.absFilename(), 50);
2484 docstring text = bformat(_("The specified document\n%1$s"
2485 "\ncould not be read."), file);
2486 Alert::error(_("Could not read document"), text);
2490 // Check if emergency save file exists and is newer.
2491 FileName const e(s.absFilename() + ".emergency");
2493 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2494 docstring const file = makeDisplayPath(s.absFilename(), 20);
2495 docstring const text =
2496 bformat(_("An emergency save of the document "
2498 "Recover emergency save?"), file);
2499 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2500 _("&Recover"), _("&Load Original"),
2504 // the file is not saved if we load the emergency file.
2514 // Now check if autosave file is newer.
2515 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2517 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2518 docstring const file = makeDisplayPath(s.absFilename(), 20);
2519 docstring const text =
2520 bformat(_("The backup of the document "
2521 "%1$s is newer.\n\nLoad the "
2522 "backup instead?"), file);
2523 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2524 _("&Load backup"), _("Load &original"),
2528 // the file is not saved if we load the autosave file.
2532 // Here we delete the autosave
2543 bool Buffer::loadLyXFile(FileName const & s)
2545 if (s.isReadableFile()) {
2546 if (readFileHelper(s)) {
2547 lyxvc().file_found_hook(s);
2548 if (!s.isWritable())
2553 docstring const file = makeDisplayPath(s.absFilename(), 20);
2554 // Here we probably should run
2555 if (LyXVC::file_not_found_hook(s)) {
2556 docstring const text =
2557 bformat(_("Do you want to retrieve the document"
2558 " %1$s from version control?"), file);
2559 int const ret = Alert::prompt(_("Retrieve from version control?"),
2560 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2563 // How can we know _how_ to do the checkout?
2564 // With the current VC support it has to be,
2565 // a RCS file since CVS do not have special ,v files.
2567 return loadLyXFile(s);
2575 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2577 TeXErrors::Errors::const_iterator cit = terr.begin();
2578 TeXErrors::Errors::const_iterator end = terr.end();
2580 for (; cit != end; ++cit) {
2583 int errorRow = cit->error_in_line;
2584 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2590 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2591 } while (found && id_start == id_end && pos_start == pos_end);
2593 errorList.push_back(ErrorItem(cit->error_desc,
2594 cit->error_text, id_start, pos_start, pos_end));