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"
29 #include "ErrorList.h"
32 #include "FuncRequest.h"
33 #include "InsetIterator.h"
34 #include "InsetList.h"
36 #include "LaTeXFeatures.h"
40 #include "LyXAction.h"
44 #include "output_docbook.h"
46 #include "output_latex.h"
47 #include "output_plaintext.h"
48 #include "paragraph_funcs.h"
49 #include "Paragraph.h"
50 #include "ParagraphParameters.h"
51 #include "ParIterator.h"
52 #include "PDFOptions.h"
55 #include "TexStream.h"
57 #include "TextClass.h"
58 #include "TocBackend.h"
60 #include "VCBackend.h"
64 #include "insets/InsetBibitem.h"
65 #include "insets/InsetBibtex.h"
66 #include "insets/InsetInclude.h"
67 #include "insets/InsetText.h"
69 #include "mathed/MacroTable.h"
70 #include "mathed/MathMacroTemplate.h"
71 #include "mathed/MathSupport.h"
73 #include "frontends/alert.h"
74 #include "frontends/Delegates.h"
75 #include "frontends/WorkAreaManager.h"
77 #include "graphics/Previews.h"
79 #include "support/lassert.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"
97 #include <boost/bind.hpp>
98 #include <boost/shared_ptr.hpp>
109 using namespace lyx::support;
113 namespace Alert = frontend::Alert;
114 namespace os = support::os;
118 // Do not remove the comment below, so we get merge conflict in
119 // independent branches. Instead add your own.
120 int const LYX_FORMAT = 345; // jamatos: xml elements
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);
144 mutable TexRow texrow;
145 Buffer const * parent_buffer;
147 /// need to regenerate .tex?
151 mutable bool lyx_clean;
153 /// is autosave needed?
154 mutable bool bak_clean;
156 /// is this a unnamed file (New...)?
162 /// name of the file the buffer is associated with.
165 /** Set to true only when the file is fully loaded.
166 * Used to prevent the premature generation of previews
167 * and by the citation inset.
169 bool file_fully_loaded;
172 mutable TocBackend toc_backend;
175 typedef pair<DocIterator, MacroData> ScopeMacro;
176 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
177 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
178 /// map from the macro name to the position map,
179 /// which maps the macro definition position to the scope and the MacroData.
180 NamePositionScopeMacroMap macros;
183 /// positions of child buffers in the buffer
184 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
185 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
186 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
187 /// position of children buffers in this buffer
188 BufferPositionMap children_positions;
189 /// map from children inclusion positions to their scope and their buffer
190 PositionScopeBufferMap position_to_children;
192 /// Container for all sort of Buffer dependant errors.
193 map<string, ErrorList> errorLists;
195 /// timestamp and checksum used to test if the file has been externally
196 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
198 unsigned long checksum_;
201 frontend::WorkAreaManager * wa_;
206 /// A cache for the bibfiles (including bibfiles of loaded child
207 /// documents), needed for appropriate update of natbib labels.
208 mutable support::FileNameList bibfilesCache_;
210 // FIXME The caching mechanism could be improved. At present, we have a
211 // cache for each Buffer, that caches all the bibliography info for that
212 // Buffer. A more efficient solution would be to have a global cache per
213 // file, and then to construct the Buffer's bibinfo from that.
214 /// A cache for bibliography info
215 mutable BiblioInfo bibinfo_;
216 /// whether the bibinfo cache is valid
217 bool bibinfoCacheValid_;
218 /// Cache of timestamps of .bib files
219 map<FileName, time_t> bibfileStatus_;
221 mutable RefCache ref_cache_;
223 /// our Text that should be wrapped in an InsetText
228 /// Creates the per buffer temporary directory
229 static FileName createBufferTmpDir()
232 // We are in our own directory. Why bother to mangle name?
233 // In fact I wrote this code to circumvent a problematic behaviour
234 // (bug?) of EMX mkstemp().
235 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
236 convert<string>(count++));
238 if (!tmpfl.createDirectory(0777)) {
239 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
240 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
241 from_utf8(tmpfl.absFilename())));
247 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
248 : parent_buffer(0), lyx_clean(true), bak_clean(true), unnamed(false),
249 read_only(readonly_), filename(file), file_fully_loaded(false),
250 toc_backend(&parent), macro_lock(false), timestamp_(0),
251 checksum_(0), wa_(0), undo_(parent), bibinfoCacheValid_(false)
253 temppath = createBufferTmpDir();
254 lyxvc.setBuffer(&parent);
256 wa_ = new frontend::WorkAreaManager;
260 Buffer::Buffer(string const & file, bool readonly)
261 : d(new Impl(*this, FileName(file), readonly)), gui_(0)
263 LYXERR(Debug::INFO, "Buffer::Buffer()");
265 d->inset = new InsetText(*this);
266 d->inset->setAutoBreakRows(true);
267 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
273 LYXERR(Debug::INFO, "Buffer::~Buffer()");
274 // here the buffer should take care that it is
275 // saved properly, before it goes into the void.
277 // GuiView already destroyed
280 if (d->unnamed && d->filename.extension() == "internal") {
281 // No need to do additional cleanups for internal buffer.
286 // loop over children
287 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
288 Impl::BufferPositionMap::iterator end = d->children_positions.end();
289 for (; it != end; ++it)
290 theBufferList().releaseChild(this, const_cast<Buffer *>(it->first));
292 // clear references to children in macro tables
293 d->children_positions.clear();
294 d->position_to_children.clear();
296 if (!d->temppath.destroyDirectory()) {
297 Alert::warning(_("Could not remove temporary directory"),
298 bformat(_("Could not remove the temporary directory %1$s"),
299 from_utf8(d->temppath.absFilename())));
302 // Remove any previewed LaTeX snippets associated with this buffer.
303 thePreviews().removeLoader(*this);
309 void Buffer::changed() const
316 frontend::WorkAreaManager & Buffer::workAreaManager() const
318 LASSERT(d->wa_, /**/);
323 Text & Buffer::text() const
325 return d->inset->text();
329 Inset & Buffer::inset() const
335 BufferParams & Buffer::params()
341 BufferParams const & Buffer::params() const
347 ParagraphList & Buffer::paragraphs()
349 return text().paragraphs();
353 ParagraphList const & Buffer::paragraphs() const
355 return text().paragraphs();
359 LyXVC & Buffer::lyxvc()
365 LyXVC const & Buffer::lyxvc() const
371 string const Buffer::temppath() const
373 return d->temppath.absFilename();
377 TexRow const & Buffer::texrow() const
383 TocBackend & Buffer::tocBackend() const
385 return d->toc_backend;
389 Undo & Buffer::undo()
395 string Buffer::latexName(bool const no_path) const
397 FileName latex_name = makeLatexName(d->filename);
398 return no_path ? latex_name.onlyFileName()
399 : latex_name.absFilename();
403 string Buffer::logName(LogType * type) const
405 string const filename = latexName(false);
407 if (filename.empty()) {
413 string const path = temppath();
415 FileName const fname(addName(temppath(),
416 onlyFilename(changeExtension(filename,
418 FileName const bname(
419 addName(path, onlyFilename(
420 changeExtension(filename,
421 formats.extension("literate") + ".out"))));
423 // If no Latex log or Build log is newer, show Build log
425 if (bname.exists() &&
426 (!fname.exists() || fname.lastModified() < bname.lastModified())) {
427 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
430 return bname.absFilename();
432 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
435 return fname.absFilename();
439 void Buffer::setReadonly(bool const flag)
441 if (d->read_only != flag) {
448 void Buffer::setFileName(string const & newfile)
450 d->filename = makeAbsPath(newfile);
451 setReadonly(d->filename.isReadOnly());
456 int Buffer::readHeader(Lexer & lex)
458 int unknown_tokens = 0;
460 int begin_header_line = -1;
462 // Initialize parameters that may be/go lacking in header:
463 params().branchlist().clear();
464 params().preamble.erase();
465 params().options.erase();
466 params().master.erase();
467 params().float_placement.erase();
468 params().paperwidth.erase();
469 params().paperheight.erase();
470 params().leftmargin.erase();
471 params().rightmargin.erase();
472 params().topmargin.erase();
473 params().bottommargin.erase();
474 params().headheight.erase();
475 params().headsep.erase();
476 params().footskip.erase();
477 params().columnsep.erase();
478 params().fontsCJK.erase();
479 params().listings_params.clear();
480 params().clearLayoutModules();
481 params().clearRemovedModules();
482 params().pdfoptions().clear();
484 for (int i = 0; i < 4; ++i) {
485 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
486 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
489 ErrorList & errorList = d->errorLists["Parse"];
498 if (token == "\\end_header")
502 if (token == "\\begin_header") {
503 begin_header_line = line;
507 LYXERR(Debug::PARSER, "Handling document header token: `"
510 string unknown = params().readToken(lex, token, d->filename.onlyPath());
511 if (!unknown.empty()) {
512 if (unknown[0] != '\\' && token == "\\textclass") {
513 Alert::warning(_("Unknown document class"),
514 bformat(_("Using the default document class, because the "
515 "class %1$s is unknown."), from_utf8(unknown)));
518 docstring const s = bformat(_("Unknown token: "
522 errorList.push_back(ErrorItem(_("Document header error"),
527 if (begin_header_line) {
528 docstring const s = _("\\begin_header is missing");
529 errorList.push_back(ErrorItem(_("Document header error"),
533 params().makeDocumentClass();
535 return unknown_tokens;
540 // changed to be public and have one parameter
541 // Returns false if "\end_document" is not read (Asger)
542 bool Buffer::readDocument(Lexer & lex)
544 ErrorList & errorList = d->errorLists["Parse"];
547 if (!lex.checkFor("\\begin_document")) {
548 docstring const s = _("\\begin_document is missing");
549 errorList.push_back(ErrorItem(_("Document header error"),
553 // we are reading in a brand new document
554 LASSERT(paragraphs().empty(), /**/);
558 if (params().outputChanges) {
559 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
560 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
561 LaTeXFeatures::isAvailable("xcolor");
563 if (!dvipost && !xcolorsoul) {
564 Alert::warning(_("Changes not shown in LaTeX output"),
565 _("Changes will not be highlighted in LaTeX output, "
566 "because neither dvipost nor xcolor/soul are installed.\n"
567 "Please install these packages or redefine "
568 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
569 } else if (!xcolorsoul) {
570 Alert::warning(_("Changes not shown in LaTeX output"),
571 _("Changes will not be highlighted in LaTeX output "
572 "when using pdflatex, because xcolor and soul are not installed.\n"
573 "Please install both packages or redefine "
574 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
578 if (!params().master.empty()) {
579 FileName const master_file = makeAbsPath(params().master,
580 onlyPath(absFileName()));
581 if (isLyXFilename(master_file.absFilename())) {
582 Buffer * master = checkAndLoadLyXFile(master_file);
583 d->parent_buffer = master;
588 bool const res = text().read(*this, lex, errorList, d->inset);
591 updateMacroInstances();
596 // needed to insert the selection
597 void Buffer::insertStringAsLines(ParagraphList & pars,
598 pit_type & pit, pos_type & pos,
599 Font const & fn, docstring const & str, bool autobreakrows)
603 // insert the string, don't insert doublespace
604 bool space_inserted = true;
605 for (docstring::const_iterator cit = str.begin();
606 cit != str.end(); ++cit) {
607 Paragraph & par = pars[pit];
609 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
610 breakParagraph(params(), pars, pit, pos,
611 par.layout().isEnvironment());
614 space_inserted = true;
618 // do not insert consecutive spaces if !free_spacing
619 } else if ((*cit == ' ' || *cit == '\t') &&
620 space_inserted && !par.isFreeSpacing()) {
622 } else if (*cit == '\t') {
623 if (!par.isFreeSpacing()) {
624 // tabs are like spaces here
625 par.insertChar(pos, ' ', font, params().trackChanges);
627 space_inserted = true;
629 par.insertChar(pos, *cit, font, params().trackChanges);
631 space_inserted = true;
633 } else if (!isPrintable(*cit)) {
634 // Ignore unprintables
637 // just insert the character
638 par.insertChar(pos, *cit, font, params().trackChanges);
640 space_inserted = (*cit == ' ');
647 bool Buffer::readString(string const & s)
649 params().compressed = false;
651 // remove dummy empty par
652 paragraphs().clear();
656 FileName const name = FileName::tempName("Buffer_readString");
657 switch (readFile(lex, name, true)) {
661 // We need to call lyx2lyx, so write the input to a file
662 ofstream os(name.toFilesystemEncoding().c_str());
665 return readFile(name);
675 bool Buffer::readFile(FileName const & filename)
677 FileName fname(filename);
679 // remove dummy empty par
680 paragraphs().clear();
683 if (readFile(lex, fname) != success)
690 bool Buffer::isFullyLoaded() const
692 return d->file_fully_loaded;
696 void Buffer::setFullyLoaded(bool value)
698 d->file_fully_loaded = value;
702 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
705 LASSERT(!filename.empty(), /**/);
707 // the first (non-comment) token _must_ be...
708 if (!lex.checkFor("\\lyxformat")) {
709 Alert::error(_("Document format failure"),
710 bformat(_("%1$s is not a readable LyX document."),
711 from_utf8(filename.absFilename())));
717 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
718 // if present remove ".," from string.
719 size_t dot = tmp_format.find_first_of(".,");
720 //lyxerr << " dot found at " << dot << endl;
721 if (dot != string::npos)
722 tmp_format.erase(dot, 1);
723 int const file_format = convert<int>(tmp_format);
724 //lyxerr << "format: " << file_format << endl;
726 // save timestamp and checksum of the original disk file, making sure
727 // to not overwrite them with those of the file created in the tempdir
728 // when it has to be converted to the current format.
730 // Save the timestamp and checksum of disk file. If filename is an
731 // emergency file, save the timestamp and checksum of the original lyx file
732 // because isExternallyModified will check for this file. (BUG4193)
733 string diskfile = filename.absFilename();
734 if (suffixIs(diskfile, ".emergency"))
735 diskfile = diskfile.substr(0, diskfile.size() - 10);
736 saveCheckSum(FileName(diskfile));
739 if (file_format != LYX_FORMAT) {
742 // lyx2lyx would fail
745 FileName const tmpfile = FileName::tempName("Buffer_readFile");
746 if (tmpfile.empty()) {
747 Alert::error(_("Conversion failed"),
748 bformat(_("%1$s is from a different"
749 " version of LyX, but a temporary"
750 " file for converting it could"
752 from_utf8(filename.absFilename())));
755 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
756 if (lyx2lyx.empty()) {
757 Alert::error(_("Conversion script not found"),
758 bformat(_("%1$s is from a different"
759 " version of LyX, but the"
760 " conversion script lyx2lyx"
761 " could not be found."),
762 from_utf8(filename.absFilename())));
765 ostringstream command;
766 command << os::python()
767 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
768 << " -t " << convert<string>(LYX_FORMAT)
769 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
770 << ' ' << quoteName(filename.toFilesystemEncoding());
771 string const command_str = command.str();
773 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
775 cmd_ret const ret = runCommand(command_str);
776 if (ret.first != 0) {
777 Alert::error(_("Conversion script failed"),
778 bformat(_("%1$s is from a different version"
779 " of LyX, but the lyx2lyx script"
780 " failed to convert it."),
781 from_utf8(filename.absFilename())));
784 bool const ret = readFile(tmpfile);
785 // Do stuff with tmpfile name and buffer name here.
786 return ret ? success : failure;
791 if (readDocument(lex)) {
792 Alert::error(_("Document format failure"),
793 bformat(_("%1$s ended unexpectedly, which means"
794 " that it is probably corrupted."),
795 from_utf8(filename.absFilename())));
798 d->file_fully_loaded = true;
803 // Should probably be moved to somewhere else: BufferView? LyXView?
804 bool Buffer::save() const
806 // We don't need autosaves in the immediate future. (Asger)
807 resetAutosaveTimers();
809 string const encodedFilename = d->filename.toFilesystemEncoding();
812 bool madeBackup = false;
814 // make a backup if the file already exists
815 if (lyxrc.make_backup && fileName().exists()) {
816 backupName = FileName(absFileName() + '~');
817 if (!lyxrc.backupdir_path.empty()) {
818 string const mangledName =
819 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
820 backupName = FileName(addName(lyxrc.backupdir_path,
823 if (fileName().copyTo(backupName)) {
826 Alert::error(_("Backup failure"),
827 bformat(_("Cannot create backup file %1$s.\n"
828 "Please check whether the directory exists and is writeable."),
829 from_utf8(backupName.absFilename())));
830 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
834 // ask if the disk file has been externally modified (use checksum method)
835 if (fileName().exists() && isExternallyModified(checksum_method)) {
836 docstring const file = makeDisplayPath(absFileName(), 20);
837 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
838 "you want to overwrite this file?"), file);
839 int const ret = Alert::prompt(_("Overwrite modified file?"),
840 text, 1, 1, _("&Overwrite"), _("&Cancel"));
845 if (writeFile(d->filename)) {
849 // Saving failed, so backup is not backup
851 backupName.moveTo(d->filename);
857 bool Buffer::writeFile(FileName const & fname) const
859 if (d->read_only && fname == d->filename)
864 docstring const str = bformat(_("Saving document %1$s..."),
865 makeDisplayPath(fname.absFilename()));
868 if (params().compressed) {
869 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
870 retval = ofs && write(ofs);
872 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
873 retval = ofs && write(ofs);
877 message(str + _(" could not write file!"));
881 removeAutosaveFile(d->filename.absFilename());
883 saveCheckSum(d->filename);
884 message(str + _(" done."));
890 bool Buffer::write(ostream & ofs) const
893 // Use the standard "C" locale for file output.
894 ofs.imbue(locale::classic());
897 // The top of the file should not be written by params().
899 // write out a comment in the top of the file
900 ofs << "#LyX " << lyx_version
901 << " created this file. For more info see http://www.lyx.org/\n"
902 << "\\lyxformat " << LYX_FORMAT << "\n"
903 << "\\begin_document\n";
905 /// For each author, set 'used' to true if there is a change
906 /// by this author in the document; otherwise set it to 'false'.
907 AuthorList::Authors::const_iterator a_it = params().authors().begin();
908 AuthorList::Authors::const_iterator a_end = params().authors().end();
909 for (; a_it != a_end; ++a_it)
910 a_it->second.setUsed(false);
912 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
913 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
914 for ( ; it != end; ++it)
915 it->checkAuthors(params().authors());
917 // now write out the buffer parameters.
918 ofs << "\\begin_header\n";
919 params().writeFile(ofs);
920 ofs << "\\end_header\n";
923 ofs << "\n\\begin_body\n";
924 text().write(*this, ofs);
925 ofs << "\n\\end_body\n";
927 // Write marker that shows file is complete
928 ofs << "\\end_document" << endl;
930 // Shouldn't really be needed....
933 // how to check if close went ok?
934 // Following is an attempt... (BE 20001011)
936 // good() returns false if any error occured, including some
938 // bad() returns true if something bad happened in the buffer,
939 // which should include file system full errors.
944 lyxerr << "File was not closed properly." << endl;
951 bool Buffer::makeLaTeXFile(FileName const & fname,
952 string const & original_path,
953 OutputParams const & runparams,
954 bool output_preamble, bool output_body) const
956 string const encoding = runparams.encoding->iconvName();
957 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
960 try { ofs.reset(encoding); }
961 catch (iconv_codecvt_facet_exception & e) {
962 lyxerr << "Caught iconv exception: " << e.what() << endl;
963 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
964 "verify that the support software for your encoding (%1$s) is "
965 "properly installed"), from_ascii(encoding)));
968 if (!openFileWrite(ofs, fname))
971 //TexStream ts(ofs.rdbuf(), &texrow());
972 ErrorList & errorList = d->errorLists["Export"];
974 bool failed_export = false;
977 writeLaTeXSource(ofs, original_path,
978 runparams, output_preamble, output_body);
980 catch (EncodingException & e) {
981 odocstringstream ods;
982 ods.put(e.failed_char);
984 oss << "0x" << hex << e.failed_char << dec;
985 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
986 " (code point %2$s)"),
987 ods.str(), from_utf8(oss.str()));
988 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
989 "representable in the chosen encoding.\n"
990 "Changing the document encoding to utf8 could help."),
991 e.par_id, e.pos, e.pos + 1));
992 failed_export = true;
994 catch (iconv_codecvt_facet_exception & e) {
995 errorList.push_back(ErrorItem(_("iconv conversion failed"),
996 _(e.what()), -1, 0, 0));
997 failed_export = true;
999 catch (exception const & e) {
1000 errorList.push_back(ErrorItem(_("conversion failed"),
1001 _(e.what()), -1, 0, 0));
1002 failed_export = true;
1005 lyxerr << "Caught some really weird exception..." << endl;
1011 failed_export = true;
1012 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1016 return !failed_export;
1020 void Buffer::writeLaTeXSource(odocstream & os,
1021 string const & original_path,
1022 OutputParams const & runparams_in,
1023 bool const output_preamble, bool const output_body) const
1025 // The child documents, if any, shall be already loaded at this point.
1027 OutputParams runparams = runparams_in;
1029 // Classify the unicode characters appearing in math insets
1030 Encodings::initUnicodeMath(*this);
1032 // validate the buffer.
1033 LYXERR(Debug::LATEX, " Validating buffer...");
1034 LaTeXFeatures features(*this, params(), runparams);
1036 LYXERR(Debug::LATEX, " Buffer validation done.");
1038 // The starting paragraph of the coming rows is the
1039 // first paragraph of the document. (Asger)
1040 if (output_preamble && runparams.nice) {
1041 os << "%% LyX " << lyx_version << " created this file. "
1042 "For more info, see http://www.lyx.org/.\n"
1043 "%% Do not edit unless you really know what "
1045 d->texrow.newline();
1046 d->texrow.newline();
1048 LYXERR(Debug::INFO, "lyx document header finished");
1050 // Don't move this behind the parent_buffer=0 code below,
1051 // because then the macros will not get the right "redefinition"
1052 // flag as they don't see the parent macros which are output before.
1055 // fold macros if possible, still with parent buffer as the
1056 // macros will be put in the prefix anyway.
1057 updateMacroInstances();
1059 // There are a few differences between nice LaTeX and usual files:
1060 // usual is \batchmode and has a
1061 // special input@path to allow the including of figures
1062 // with either \input or \includegraphics (what figinsets do).
1063 // input@path is set when the actual parameter
1064 // original_path is set. This is done for usual tex-file, but not
1065 // for nice-latex-file. (Matthias 250696)
1066 // Note that input@path is only needed for something the user does
1067 // in the preamble, included .tex files or ERT, files included by
1068 // LyX work without it.
1069 if (output_preamble) {
1070 if (!runparams.nice) {
1071 // code for usual, NOT nice-latex-file
1072 os << "\\batchmode\n"; // changed
1073 // from \nonstopmode
1074 d->texrow.newline();
1076 if (!original_path.empty()) {
1078 // We don't know the encoding of inputpath
1079 docstring const inputpath = from_utf8(latex_path(original_path));
1080 os << "\\makeatletter\n"
1081 << "\\def\\input@path{{"
1082 << inputpath << "/}}\n"
1083 << "\\makeatother\n";
1084 d->texrow.newline();
1085 d->texrow.newline();
1086 d->texrow.newline();
1089 // get parent macros (if this buffer has a parent) which will be
1090 // written at the document begin further down.
1091 MacroSet parentMacros;
1092 listParentMacros(parentMacros, features);
1094 // Write the preamble
1095 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1097 runparams.use_japanese = features.isRequired("japanese");
1103 os << "\\begin{document}\n";
1104 d->texrow.newline();
1106 // output the parent macros
1107 MacroSet::iterator it = parentMacros.begin();
1108 MacroSet::iterator end = parentMacros.end();
1109 for (; it != end; ++it)
1110 (*it)->write(os, true);
1111 } // output_preamble
1113 d->texrow.start(paragraphs().begin()->id(), 0);
1115 LYXERR(Debug::INFO, "preamble finished, now the body.");
1117 // if we are doing a real file with body, even if this is the
1118 // child of some other buffer, let's cut the link here.
1119 // This happens for example if only a child document is printed.
1120 Buffer const * save_parent = 0;
1121 if (output_preamble) {
1122 save_parent = d->parent_buffer;
1123 d->parent_buffer = 0;
1127 latexParagraphs(*this, text(), os, d->texrow, runparams);
1129 // Restore the parenthood if needed
1130 if (output_preamble)
1131 d->parent_buffer = save_parent;
1133 // add this just in case after all the paragraphs
1135 d->texrow.newline();
1137 if (output_preamble) {
1138 os << "\\end{document}\n";
1139 d->texrow.newline();
1140 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1142 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1144 runparams_in.encoding = runparams.encoding;
1146 // Just to be sure. (Asger)
1147 d->texrow.newline();
1149 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1150 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1154 bool Buffer::isLatex() const
1156 return params().documentClass().outputType() == LATEX;
1160 bool Buffer::isLiterate() const
1162 return params().documentClass().outputType() == LITERATE;
1166 bool Buffer::isDocBook() const
1168 return params().documentClass().outputType() == DOCBOOK;
1172 void Buffer::makeDocBookFile(FileName const & fname,
1173 OutputParams const & runparams,
1174 bool const body_only) const
1176 LYXERR(Debug::LATEX, "makeDocBookFile...");
1179 if (!openFileWrite(ofs, fname))
1182 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1186 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1190 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1191 OutputParams const & runparams,
1192 bool const only_body) const
1194 LaTeXFeatures features(*this, params(), runparams);
1199 DocumentClass const & tclass = params().documentClass();
1200 string const top_element = tclass.latexname();
1203 if (runparams.flavor == OutputParams::XML)
1204 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1207 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1210 if (! tclass.class_header().empty())
1211 os << from_ascii(tclass.class_header());
1212 else if (runparams.flavor == OutputParams::XML)
1213 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1214 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1216 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1218 docstring preamble = from_utf8(params().preamble);
1219 if (runparams.flavor != OutputParams::XML ) {
1220 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1221 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1222 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1223 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1226 string const name = runparams.nice
1227 ? changeExtension(absFileName(), ".sgml") : fname;
1228 preamble += features.getIncludedFiles(name);
1229 preamble += features.getLyXSGMLEntities();
1231 if (!preamble.empty()) {
1232 os << "\n [ " << preamble << " ]";
1237 string top = top_element;
1239 if (runparams.flavor == OutputParams::XML)
1240 top += params().language->code();
1242 top += params().language->code().substr(0, 2);
1245 if (!params().options.empty()) {
1247 top += params().options;
1250 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1251 << " file was created by LyX " << lyx_version
1252 << "\n See http://www.lyx.org/ for more information -->\n";
1254 params().documentClass().counters().reset();
1258 sgml::openTag(os, top);
1260 docbookParagraphs(paragraphs(), *this, os, runparams);
1261 sgml::closeTag(os, top_element);
1265 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1266 // Other flags: -wall -v0 -x
1267 int Buffer::runChktex()
1271 // get LaTeX-Filename
1272 FileName const path(temppath());
1273 string const name = addName(path.absFilename(), latexName());
1274 string const org_path = filePath();
1276 PathChanger p(path); // path to LaTeX file
1277 message(_("Running chktex..."));
1279 // Generate the LaTeX file if neccessary
1280 OutputParams runparams(¶ms().encoding());
1281 runparams.flavor = OutputParams::LATEX;
1282 runparams.nice = false;
1283 makeLaTeXFile(FileName(name), org_path, runparams);
1286 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1287 int const res = chktex.run(terr); // run chktex
1290 Alert::error(_("chktex failure"),
1291 _("Could not run chktex successfully."));
1292 } else if (res > 0) {
1293 ErrorList & errlist = d->errorLists["ChkTeX"];
1295 bufferErrors(terr, errlist);
1306 void Buffer::validate(LaTeXFeatures & features) const
1308 params().validate(features);
1312 for_each(paragraphs().begin(), paragraphs().end(),
1313 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1315 if (lyxerr.debugging(Debug::LATEX)) {
1316 features.showStruct();
1321 void Buffer::getLabelList(vector<docstring> & list) const
1323 // If this is a child document, use the parent's list instead.
1324 if (d->parent_buffer) {
1325 d->parent_buffer->getLabelList(list);
1330 Toc & toc = d->toc_backend.toc("label");
1331 TocIterator toc_it = toc.begin();
1332 TocIterator end = toc.end();
1333 for (; toc_it != end; ++toc_it) {
1334 if (toc_it->depth() == 0)
1335 list.push_back(toc_it->str());
1340 void Buffer::updateBibfilesCache() const
1342 // If this is a child document, use the parent's cache instead.
1343 if (d->parent_buffer) {
1344 d->parent_buffer->updateBibfilesCache();
1348 d->bibfilesCache_.clear();
1349 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1350 if (it->lyxCode() == BIBTEX_CODE) {
1351 InsetBibtex const & inset =
1352 static_cast<InsetBibtex const &>(*it);
1353 support::FileNameList const bibfiles = inset.getBibFiles();
1354 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1357 } else if (it->lyxCode() == INCLUDE_CODE) {
1358 InsetInclude & inset =
1359 static_cast<InsetInclude &>(*it);
1360 inset.updateBibfilesCache();
1361 support::FileNameList const & bibfiles =
1362 inset.getBibfilesCache(*this);
1363 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1368 // the bibinfo cache is now invalid
1369 d->bibinfoCacheValid_ = false;
1373 void Buffer::invalidateBibinfoCache()
1375 d->bibinfoCacheValid_ = false;
1379 support::FileNameList const & Buffer::getBibfilesCache() const
1381 // If this is a child document, use the parent's cache instead.
1382 if (d->parent_buffer)
1383 return d->parent_buffer->getBibfilesCache();
1385 // We update the cache when first used instead of at loading time.
1386 if (d->bibfilesCache_.empty())
1387 const_cast<Buffer *>(this)->updateBibfilesCache();
1389 return d->bibfilesCache_;
1393 BiblioInfo const & Buffer::masterBibInfo() const
1395 // if this is a child document and the parent is already loaded
1396 // use the parent's list instead [ale990412]
1397 Buffer const * const tmp = masterBuffer();
1400 return tmp->masterBibInfo();
1401 return localBibInfo();
1405 BiblioInfo const & Buffer::localBibInfo() const
1407 if (d->bibinfoCacheValid_) {
1408 support::FileNameList const & bibfilesCache = getBibfilesCache();
1409 // compare the cached timestamps with the actual ones.
1410 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1411 support::FileNameList::const_iterator en = bibfilesCache.end();
1412 for (; ei != en; ++ ei) {
1413 time_t lastw = ei->lastModified();
1414 if (lastw != d->bibfileStatus_[*ei]) {
1415 d->bibinfoCacheValid_ = false;
1416 d->bibfileStatus_[*ei] = lastw;
1422 if (!d->bibinfoCacheValid_) {
1423 d->bibinfo_.clear();
1424 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1425 it->fillWithBibKeys(d->bibinfo_, it);
1426 d->bibinfoCacheValid_ = true;
1432 bool Buffer::isDepClean(string const & name) const
1434 DepClean::const_iterator const it = d->dep_clean.find(name);
1435 if (it == d->dep_clean.end())
1441 void Buffer::markDepClean(string const & name)
1443 d->dep_clean[name] = true;
1447 bool Buffer::dispatch(string const & command, bool * result)
1449 return dispatch(lyxaction.lookupFunc(command), result);
1453 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1455 bool dispatched = true;
1457 switch (func.action) {
1458 case LFUN_BUFFER_EXPORT: {
1459 bool const tmp = doExport(to_utf8(func.argument()), false);
1465 case LFUN_BRANCH_ACTIVATE:
1466 case LFUN_BRANCH_DEACTIVATE: {
1467 BranchList & branchList = params().branchlist();
1468 docstring const branchName = func.argument();
1469 Branch * branch = branchList.find(branchName);
1471 LYXERR0("Branch " << branchName << " does not exist.");
1473 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1485 void Buffer::changeLanguage(Language const * from, Language const * to)
1487 LASSERT(from, /**/);
1490 for_each(par_iterator_begin(),
1492 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1496 bool Buffer::isMultiLingual() const
1498 ParConstIterator end = par_iterator_end();
1499 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1500 if (it->isMultiLingual(params()))
1507 DocIterator Buffer::getParFromID(int const id) const
1510 // John says this is called with id == -1 from undo
1511 lyxerr << "getParFromID(), id: " << id << endl;
1512 return doc_iterator_end(inset());
1515 for (DocIterator it = doc_iterator_begin(inset()); !it.atEnd(); it.forwardPar())
1516 if (it.paragraph().id() == id)
1519 return doc_iterator_end(inset());
1523 bool Buffer::hasParWithID(int const id) const
1525 return !getParFromID(id).atEnd();
1529 ParIterator Buffer::par_iterator_begin()
1531 return ParIterator(doc_iterator_begin(inset()));
1535 ParIterator Buffer::par_iterator_end()
1537 return ParIterator(doc_iterator_end(inset()));
1541 ParConstIterator Buffer::par_iterator_begin() const
1543 return lyx::par_const_iterator_begin(inset());
1547 ParConstIterator Buffer::par_iterator_end() const
1549 return lyx::par_const_iterator_end(inset());
1553 Language const * Buffer::language() const
1555 return params().language;
1559 docstring const Buffer::B_(string const & l10n) const
1561 return params().B_(l10n);
1565 bool Buffer::isClean() const
1567 return d->lyx_clean;
1571 bool Buffer::isBakClean() const
1573 return d->bak_clean;
1577 bool Buffer::isExternallyModified(CheckMethod method) const
1579 LASSERT(d->filename.exists(), /**/);
1580 // if method == timestamp, check timestamp before checksum
1581 return (method == checksum_method
1582 || d->timestamp_ != d->filename.lastModified())
1583 && d->checksum_ != d->filename.checksum();
1587 void Buffer::saveCheckSum(FileName const & file) const
1589 if (file.exists()) {
1590 d->timestamp_ = file.lastModified();
1591 d->checksum_ = file.checksum();
1593 // in the case of save to a new file.
1600 void Buffer::markClean() const
1602 if (!d->lyx_clean) {
1603 d->lyx_clean = true;
1606 // if the .lyx file has been saved, we don't need an
1608 d->bak_clean = true;
1612 void Buffer::markBakClean() const
1614 d->bak_clean = true;
1618 void Buffer::setUnnamed(bool flag)
1624 bool Buffer::isUnnamed() const
1630 // FIXME: this function should be moved to buffer_pimpl.C
1631 void Buffer::markDirty()
1634 d->lyx_clean = false;
1637 d->bak_clean = false;
1639 DepClean::iterator it = d->dep_clean.begin();
1640 DepClean::const_iterator const end = d->dep_clean.end();
1642 for (; it != end; ++it)
1647 FileName Buffer::fileName() const
1653 string Buffer::absFileName() const
1655 return d->filename.absFilename();
1659 string Buffer::filePath() const
1661 return d->filename.onlyPath().absFilename() + "/";
1665 bool Buffer::isReadonly() const
1667 return d->read_only;
1671 void Buffer::setParent(Buffer const * buffer)
1673 // Avoids recursive include.
1674 d->parent_buffer = buffer == this ? 0 : buffer;
1679 Buffer const * Buffer::parent()
1681 return d->parent_buffer;
1685 Buffer const * Buffer::masterBuffer() const
1687 if (!d->parent_buffer)
1690 return d->parent_buffer->masterBuffer();
1694 bool Buffer::isChild(Buffer * child) const
1696 return d->children_positions.find(child) != d->children_positions.end();
1700 template<typename M>
1701 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
1706 typename M::iterator it = m.lower_bound(x);
1707 if (it == m.begin())
1715 MacroData const * Buffer::getBufferMacro(docstring const & name,
1716 DocIterator const & pos) const
1718 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
1720 // if paragraphs have no macro context set, pos will be empty
1724 // we haven't found anything yet
1725 DocIterator bestPos = par_iterator_begin();
1726 MacroData const * bestData = 0;
1728 // find macro definitions for name
1729 Impl::NamePositionScopeMacroMap::iterator nameIt
1730 = d->macros.find(name);
1731 if (nameIt != d->macros.end()) {
1732 // find last definition in front of pos or at pos itself
1733 Impl::PositionScopeMacroMap::const_iterator it
1734 = greatest_below(nameIt->second, pos);
1735 if (it != nameIt->second.end()) {
1737 // scope ends behind pos?
1738 if (pos < it->second.first) {
1739 // Looks good, remember this. If there
1740 // is no external macro behind this,
1741 // we found the right one already.
1742 bestPos = it->first;
1743 bestData = &it->second.second;
1747 // try previous macro if there is one
1748 if (it == nameIt->second.begin())
1755 // find macros in included files
1756 Impl::PositionScopeBufferMap::const_iterator it
1757 = greatest_below(d->position_to_children, pos);
1758 if (it == d->position_to_children.end())
1759 // no children before
1763 // do we know something better (i.e. later) already?
1764 if (it->first < bestPos )
1767 // scope ends behind pos?
1768 if (pos < it->second.first) {
1769 // look for macro in external file
1770 d->macro_lock = true;
1771 MacroData const * data
1772 = it->second.second->getMacro(name, false);
1773 d->macro_lock = false;
1775 bestPos = it->first;
1781 // try previous file if there is one
1782 if (it == d->position_to_children.begin())
1787 // return the best macro we have found
1792 MacroData const * Buffer::getMacro(docstring const & name,
1793 DocIterator const & pos, bool global) const
1798 // query buffer macros
1799 MacroData const * data = getBufferMacro(name, pos);
1803 // If there is a master buffer, query that
1804 if (d->parent_buffer) {
1805 d->macro_lock = true;
1806 MacroData const * macro = d->parent_buffer->getMacro(
1807 name, *this, false);
1808 d->macro_lock = false;
1814 data = MacroTable::globalMacros().get(name);
1823 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
1825 // set scope end behind the last paragraph
1826 DocIterator scope = par_iterator_begin();
1827 scope.pit() = scope.lastpit() + 1;
1829 return getMacro(name, scope, global);
1833 MacroData const * Buffer::getMacro(docstring const & name,
1834 Buffer const & child, bool global) const
1836 // look where the child buffer is included first
1837 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
1838 if (it == d->children_positions.end())
1841 // check for macros at the inclusion position
1842 return getMacro(name, it->second, global);
1846 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
1848 pit_type lastpit = it.lastpit();
1850 // look for macros in each paragraph
1851 while (it.pit() <= lastpit) {
1852 Paragraph & par = it.paragraph();
1854 // iterate over the insets of the current paragraph
1855 InsetList const & insets = par.insetList();
1856 InsetList::const_iterator iit = insets.begin();
1857 InsetList::const_iterator end = insets.end();
1858 for (; iit != end; ++iit) {
1859 it.pos() = iit->pos;
1861 // is it a nested text inset?
1862 if (iit->inset->asInsetText()) {
1863 // Inset needs its own scope?
1864 InsetText const * itext
1865 = iit->inset->asInsetText();
1866 bool newScope = itext->isMacroScope();
1868 // scope which ends just behind the inset
1869 DocIterator insetScope = it;
1872 // collect macros in inset
1873 it.push_back(CursorSlice(*iit->inset));
1874 updateMacros(it, newScope ? insetScope : scope);
1879 // is it an external file?
1880 if (iit->inset->lyxCode() == INCLUDE_CODE) {
1881 // get buffer of external file
1882 InsetCommand const & inset
1883 = static_cast<InsetCommand const &>(*iit->inset);
1884 InsetCommandParams const & ip = inset.params();
1885 d->macro_lock = true;
1886 Buffer * child = loadIfNeeded(*this, ip);
1887 d->macro_lock = false;
1891 // register its position, but only when it is
1892 // included first in the buffer
1893 if (d->children_positions.find(child)
1894 == d->children_positions.end())
1895 d->children_positions[child] = it;
1897 // register child with its scope
1898 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
1902 if (iit->inset->lyxCode() != MATHMACRO_CODE)
1906 MathMacroTemplate & macroTemplate
1907 = static_cast<MathMacroTemplate &>(*iit->inset);
1908 MacroContext mc(*this, it);
1909 macroTemplate.updateToContext(mc);
1912 bool valid = macroTemplate.validMacro();
1913 // FIXME: Should be fixNameAndCheckIfValid() in fact,
1914 // then the BufferView's cursor will be invalid in
1915 // some cases which leads to crashes.
1920 d->macros[macroTemplate.name()][it] =
1921 Impl::ScopeMacro(scope, MacroData(*this, it));
1931 void Buffer::updateMacros() const
1936 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
1938 // start with empty table
1940 d->children_positions.clear();
1941 d->position_to_children.clear();
1943 // Iterate over buffer, starting with first paragraph
1944 // The scope must be bigger than any lookup DocIterator
1945 // later. For the global lookup, lastpit+1 is used, hence
1946 // we use lastpit+2 here.
1947 DocIterator it = par_iterator_begin();
1948 DocIterator outerScope = it;
1949 outerScope.pit() = outerScope.lastpit() + 2;
1950 updateMacros(it, outerScope);
1954 void Buffer::updateMacroInstances() const
1956 LYXERR(Debug::MACROS, "updateMacroInstances for "
1957 << d->filename.onlyFileName());
1958 DocIterator it = doc_iterator_begin(inset());
1959 DocIterator end = doc_iterator_end(inset());
1960 for (; it != end; it.forwardPos()) {
1961 // look for MathData cells in InsetMathNest insets
1962 Inset * inset = it.nextInset();
1966 InsetMath * minset = inset->asInsetMath();
1970 // update macro in all cells of the InsetMathNest
1971 DocIterator::idx_type n = minset->nargs();
1972 MacroContext mc = MacroContext(*this, it);
1973 for (DocIterator::idx_type i = 0; i < n; ++i) {
1974 MathData & data = minset->cell(i);
1975 data.updateMacros(0, mc);
1981 void Buffer::listMacroNames(MacroNameSet & macros) const
1986 d->macro_lock = true;
1988 // loop over macro names
1989 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
1990 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
1991 for (; nameIt != nameEnd; ++nameIt)
1992 macros.insert(nameIt->first);
1994 // loop over children
1995 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
1996 Impl::BufferPositionMap::iterator end = d->children_positions.end();
1997 for (; it != end; ++it)
1998 it->first->listMacroNames(macros);
2001 if (d->parent_buffer)
2002 d->parent_buffer->listMacroNames(macros);
2004 d->macro_lock = false;
2008 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2010 if (!d->parent_buffer)
2014 d->parent_buffer->listMacroNames(names);
2017 MacroNameSet::iterator it = names.begin();
2018 MacroNameSet::iterator end = names.end();
2019 for (; it != end; ++it) {
2021 MacroData const * data =
2022 d->parent_buffer->getMacro(*it, *this, false);
2024 macros.insert(data);
2026 // we cannot access the original MathMacroTemplate anymore
2027 // here to calls validate method. So we do its work here manually.
2028 // FIXME: somehow make the template accessible here.
2029 if (data->optionals() > 0)
2030 features.require("xargs");
2036 Buffer::References & Buffer::references(docstring const & label)
2038 if (d->parent_buffer)
2039 return const_cast<Buffer *>(masterBuffer())->references(label);
2041 RefCache::iterator it = d->ref_cache_.find(label);
2042 if (it != d->ref_cache_.end())
2043 return it->second.second;
2045 static InsetLabel const * dummy_il = 0;
2046 static References const dummy_refs;
2047 it = d->ref_cache_.insert(
2048 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2049 return it->second.second;
2053 Buffer::References const & Buffer::references(docstring const & label) const
2055 return const_cast<Buffer *>(this)->references(label);
2059 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2061 masterBuffer()->d->ref_cache_[label].first = il;
2065 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2067 return masterBuffer()->d->ref_cache_[label].first;
2071 void Buffer::clearReferenceCache() const
2073 if (!d->parent_buffer)
2074 d->ref_cache_.clear();
2078 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2081 //FIXME: This does not work for child documents yet.
2082 LASSERT(code == CITE_CODE, /**/);
2083 // Check if the label 'from' appears more than once
2084 vector<docstring> labels;
2086 BiblioInfo const & keys = masterBibInfo();
2087 BiblioInfo::const_iterator bit = keys.begin();
2088 BiblioInfo::const_iterator bend = keys.end();
2090 for (; bit != bend; ++bit)
2092 labels.push_back(bit->first);
2095 if (count(labels.begin(), labels.end(), from) > 1)
2098 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2099 if (it->lyxCode() == code) {
2100 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2101 docstring const oldValue = inset.getParam(paramName);
2102 if (oldValue == from)
2103 inset.setParam(paramName, to);
2109 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2110 pit_type par_end, bool full_source) const
2112 OutputParams runparams(¶ms().encoding());
2113 runparams.nice = true;
2114 runparams.flavor = OutputParams::LATEX;
2115 runparams.linelen = lyxrc.plaintext_linelen;
2116 // No side effect of file copying and image conversion
2117 runparams.dryrun = true;
2121 os << "% " << _("Preview source code") << "\n\n";
2122 d->texrow.newline();
2123 d->texrow.newline();
2125 writeDocBookSource(os, absFileName(), runparams, false);
2127 // latex or literate
2128 writeLaTeXSource(os, string(), runparams, true, true);
2130 runparams.par_begin = par_begin;
2131 runparams.par_end = par_end;
2132 if (par_begin + 1 == par_end) {
2134 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2138 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2139 convert<docstring>(par_begin),
2140 convert<docstring>(par_end - 1))
2143 d->texrow.newline();
2144 d->texrow.newline();
2145 // output paragraphs
2147 docbookParagraphs(paragraphs(), *this, os, runparams);
2149 // latex or literate
2150 latexParagraphs(*this, text(), os, d->texrow, runparams);
2155 ErrorList & Buffer::errorList(string const & type) const
2157 static ErrorList emptyErrorList;
2158 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2159 if (I == d->errorLists.end())
2160 return emptyErrorList;
2166 void Buffer::updateTocItem(std::string const & type,
2167 DocIterator const & dit) const
2170 gui_->updateTocItem(type, dit);
2174 void Buffer::structureChanged() const
2177 gui_->structureChanged();
2181 void Buffer::errors(string const & err) const
2188 void Buffer::message(docstring const & msg) const
2195 void Buffer::setBusy(bool on) const
2202 void Buffer::setReadOnly(bool on) const
2205 d->wa_->setReadOnly(on);
2209 void Buffer::updateTitles() const
2212 d->wa_->updateTitles();
2216 void Buffer::resetAutosaveTimers() const
2219 gui_->resetAutosaveTimers();
2223 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2232 class AutoSaveBuffer : public ForkedProcess {
2235 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2236 : buffer_(buffer), fname_(fname) {}
2238 virtual boost::shared_ptr<ForkedProcess> clone() const
2240 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2245 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2246 from_utf8(fname_.absFilename())));
2247 return run(DontWait);
2251 virtual int generateChild();
2253 Buffer const & buffer_;
2258 int AutoSaveBuffer::generateChild()
2260 // tmp_ret will be located (usually) in /tmp
2261 // will that be a problem?
2262 // Note that this calls ForkedCalls::fork(), so it's
2263 // ok cross-platform.
2264 pid_t const pid = fork();
2265 // If you want to debug the autosave
2266 // you should set pid to -1, and comment out the fork.
2267 if (pid != 0 && pid != -1)
2270 // pid = -1 signifies that lyx was unable
2271 // to fork. But we will do the save
2273 bool failed = false;
2274 FileName const tmp_ret = FileName::tempName("lyxauto");
2275 if (!tmp_ret.empty()) {
2276 buffer_.writeFile(tmp_ret);
2277 // assume successful write of tmp_ret
2278 if (!tmp_ret.moveTo(fname_))
2284 // failed to write/rename tmp_ret so try writing direct
2285 if (!buffer_.writeFile(fname_)) {
2286 // It is dangerous to do this in the child,
2287 // but safe in the parent, so...
2288 if (pid == -1) // emit message signal.
2289 buffer_.message(_("Autosave failed!"));
2293 if (pid == 0) // we are the child so...
2302 // Perfect target for a thread...
2303 void Buffer::autoSave() const
2305 if (isBakClean() || isReadonly()) {
2306 // We don't save now, but we'll try again later
2307 resetAutosaveTimers();
2311 // emit message signal.
2312 message(_("Autosaving current document..."));
2314 // create autosave filename
2315 string fname = filePath();
2317 fname += d->filename.onlyFileName();
2320 AutoSaveBuffer autosave(*this, FileName(fname));
2324 resetAutosaveTimers();
2328 string Buffer::bufferFormat() const
2334 if (params().encoding().package() == Encoding::japanese)
2340 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2341 string & result_file) const
2343 string backend_format;
2344 OutputParams runparams(¶ms().encoding());
2345 runparams.flavor = OutputParams::LATEX;
2346 runparams.linelen = lyxrc.plaintext_linelen;
2347 vector<string> backs = backends();
2348 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2349 // Get shortest path to format
2350 Graph::EdgePath path;
2351 for (vector<string>::const_iterator it = backs.begin();
2352 it != backs.end(); ++it) {
2353 Graph::EdgePath p = theConverters().getPath(*it, format);
2354 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2355 backend_format = *it;
2360 runparams.flavor = theConverters().getFlavor(path);
2362 Alert::error(_("Couldn't export file"),
2363 bformat(_("No information for exporting the format %1$s."),
2364 formats.prettyName(format)));
2368 backend_format = format;
2369 // FIXME: Don't hardcode format names here, but use a flag
2370 if (backend_format == "pdflatex")
2371 runparams.flavor = OutputParams::PDFLATEX;
2374 string filename = latexName(false);
2375 filename = addName(temppath(), filename);
2376 filename = changeExtension(filename,
2377 formats.extension(backend_format));
2380 updateMacroInstances();
2382 // Plain text backend
2383 if (backend_format == "text")
2384 writePlaintextFile(*this, FileName(filename), runparams);
2386 else if (backend_format == "lyx")
2387 writeFile(FileName(filename));
2389 else if (isDocBook()) {
2390 runparams.nice = !put_in_tempdir;
2391 makeDocBookFile(FileName(filename), runparams);
2394 else if (backend_format == format) {
2395 runparams.nice = true;
2396 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2398 } else if (!lyxrc.tex_allows_spaces
2399 && contains(filePath(), ' ')) {
2400 Alert::error(_("File name error"),
2401 _("The directory path to the document cannot contain spaces."));
2404 runparams.nice = false;
2405 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2409 string const error_type = (format == "program")
2410 ? "Build" : bufferFormat();
2411 ErrorList & error_list = d->errorLists[error_type];
2412 string const ext = formats.extension(format);
2413 FileName const tmp_result_file(changeExtension(filename, ext));
2414 bool const success = theConverters().convert(this, FileName(filename),
2415 tmp_result_file, FileName(absFileName()), backend_format, format,
2417 // Emit the signal to show the error list.
2418 if (format != backend_format)
2423 if (put_in_tempdir) {
2424 result_file = tmp_result_file.absFilename();
2428 result_file = changeExtension(absFileName(), ext);
2429 // We need to copy referenced files (e. g. included graphics
2430 // if format == "dvi") to the result dir.
2431 vector<ExportedFile> const files =
2432 runparams.exportdata->externalFiles(format);
2433 string const dest = onlyPath(result_file);
2434 CopyStatus status = SUCCESS;
2435 for (vector<ExportedFile>::const_iterator it = files.begin();
2436 it != files.end() && status != CANCEL; ++it) {
2437 string const fmt = formats.getFormatFromFile(it->sourceName);
2438 status = copyFile(fmt, it->sourceName,
2439 makeAbsPath(it->exportName, dest),
2440 it->exportName, status == FORCE);
2442 if (status == CANCEL) {
2443 message(_("Document export cancelled."));
2444 } else if (tmp_result_file.exists()) {
2445 // Finally copy the main file
2446 status = copyFile(format, tmp_result_file,
2447 FileName(result_file), result_file,
2449 message(bformat(_("Document exported as %1$s "
2451 formats.prettyName(format),
2452 makeDisplayPath(result_file)));
2454 // This must be a dummy converter like fax (bug 1888)
2455 message(bformat(_("Document exported as %1$s"),
2456 formats.prettyName(format)));
2463 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2466 return doExport(format, put_in_tempdir, result_file);
2470 bool Buffer::preview(string const & format) const
2473 if (!doExport(format, true, result_file))
2475 return formats.view(*this, FileName(result_file), format);
2479 bool Buffer::isExportable(string const & format) const
2481 vector<string> backs = backends();
2482 for (vector<string>::const_iterator it = backs.begin();
2483 it != backs.end(); ++it)
2484 if (theConverters().isReachable(*it, format))
2490 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2492 vector<string> backs = backends();
2493 vector<Format const *> result =
2494 theConverters().getReachable(backs[0], only_viewable, true);
2495 for (vector<string>::const_iterator it = backs.begin() + 1;
2496 it != backs.end(); ++it) {
2497 vector<Format const *> r =
2498 theConverters().getReachable(*it, only_viewable, false);
2499 result.insert(result.end(), r.begin(), r.end());
2505 vector<string> Buffer::backends() const
2508 if (params().baseClass()->isTeXClassAvailable()) {
2509 v.push_back(bufferFormat());
2510 // FIXME: Don't hardcode format names here, but use a flag
2511 if (v.back() == "latex")
2512 v.push_back("pdflatex");
2514 v.push_back("text");
2520 bool Buffer::readFileHelper(FileName const & s)
2522 // File information about normal file
2524 docstring const file = makeDisplayPath(s.absFilename(), 50);
2525 docstring text = bformat(_("The specified document\n%1$s"
2526 "\ncould not be read."), file);
2527 Alert::error(_("Could not read document"), text);
2531 // Check if emergency save file exists and is newer.
2532 FileName const e(s.absFilename() + ".emergency");
2534 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2535 docstring const file = makeDisplayPath(s.absFilename(), 20);
2536 docstring const text =
2537 bformat(_("An emergency save of the document "
2539 "Recover emergency save?"), file);
2540 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2541 _("&Recover"), _("&Load Original"),
2545 // the file is not saved if we load the emergency file.
2555 // Now check if autosave file is newer.
2556 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2558 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2559 docstring const file = makeDisplayPath(s.absFilename(), 20);
2560 docstring const text =
2561 bformat(_("The backup of the document "
2562 "%1$s is newer.\n\nLoad the "
2563 "backup instead?"), file);
2564 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2565 _("&Load backup"), _("Load &original"),
2569 // the file is not saved if we load the autosave file.
2573 // Here we delete the autosave
2584 bool Buffer::loadLyXFile(FileName const & s)
2586 if (s.isReadableFile()) {
2587 if (readFileHelper(s)) {
2588 lyxvc().file_found_hook(s);
2589 if (!s.isWritable())
2594 docstring const file = makeDisplayPath(s.absFilename(), 20);
2595 // Here we probably should run
2596 if (LyXVC::file_not_found_hook(s)) {
2597 docstring const text =
2598 bformat(_("Do you want to retrieve the document"
2599 " %1$s from version control?"), file);
2600 int const ret = Alert::prompt(_("Retrieve from version control?"),
2601 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2604 // How can we know _how_ to do the checkout?
2605 // With the current VC support it has to be,
2606 // a RCS file since CVS do not have special ,v files.
2608 return loadLyXFile(s);
2616 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2618 TeXErrors::Errors::const_iterator cit = terr.begin();
2619 TeXErrors::Errors::const_iterator end = terr.end();
2621 for (; cit != end; ++cit) {
2624 int errorRow = cit->error_in_line;
2625 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2631 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2632 } while (found && id_start == id_end && pos_start == pos_end);
2634 errorList.push_back(ErrorItem(cit->error_desc,
2635 cit->error_text, id_start, pos_start, pos_end));