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 int const LYX_FORMAT = 339; //rgh: removed modules
120 typedef map<string, bool> DepClean;
121 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
128 Impl(Buffer & parent, FileName const & file, bool readonly);
141 mutable TexRow texrow;
142 Buffer const * parent_buffer;
144 /// need to regenerate .tex?
148 mutable bool lyx_clean;
150 /// is autosave needed?
151 mutable bool bak_clean;
153 /// is this a unnamed file (New...)?
159 /// name of the file the buffer is associated with.
162 /** Set to true only when the file is fully loaded.
163 * Used to prevent the premature generation of previews
164 * and by the citation inset.
166 bool file_fully_loaded;
169 mutable TocBackend toc_backend;
172 typedef pair<DocIterator, MacroData> ScopeMacro;
173 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
174 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
175 /// map from the macro name to the position map,
176 /// which maps the macro definition position to the scope and the MacroData.
177 NamePositionScopeMacroMap macros;
180 /// positions of child buffers in the buffer
181 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
182 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
183 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
184 /// position of children buffers in this buffer
185 BufferPositionMap children_positions;
186 /// map from children inclusion positions to their scope and their buffer
187 PositionScopeBufferMap position_to_children;
189 /// Container for all sort of Buffer dependant errors.
190 map<string, ErrorList> errorLists;
192 /// timestamp and checksum used to test if the file has been externally
193 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
195 unsigned long checksum_;
198 frontend::WorkAreaManager * wa_;
203 /// A cache for the bibfiles (including bibfiles of loaded child
204 /// documents), needed for appropriate update of natbib labels.
205 mutable support::FileNameList bibfilesCache_;
207 // FIXME The caching mechanism could be improved. At present, we have a
208 // cache for each Buffer, that caches all the bibliography info for that
209 // Buffer. A more efficient solution would be to have a global cache per
210 // file, and then to construct the Buffer's bibinfo from that.
211 /// A cache for bibliography info
212 mutable BiblioInfo bibinfo_;
213 /// whether the bibinfo cache is valid
214 bool bibinfoCacheValid_;
215 /// Cache of timestamps of .bib files
216 map<FileName, time_t> bibfileStatus_;
218 mutable RefCache ref_cache_;
220 /// our Text that should be wrapped in an InsetText
225 /// Creates the per buffer temporary directory
226 static FileName createBufferTmpDir()
229 // We are in our own directory. Why bother to mangle name?
230 // In fact I wrote this code to circumvent a problematic behaviour
231 // (bug?) of EMX mkstemp().
232 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
233 convert<string>(count++));
235 if (!tmpfl.createDirectory(0777)) {
236 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
237 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
238 from_utf8(tmpfl.absFilename())));
244 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
245 : parent_buffer(0), lyx_clean(true), bak_clean(true), unnamed(false),
246 read_only(readonly_), filename(file), file_fully_loaded(false),
247 toc_backend(&parent), macro_lock(false), timestamp_(0),
248 checksum_(0), wa_(0), undo_(parent), bibinfoCacheValid_(false),
251 temppath = createBufferTmpDir();
252 lyxvc.setBuffer(&parent);
254 wa_ = new frontend::WorkAreaManager;
258 Buffer::Buffer(string const & file, bool readonly)
259 : d(new Impl(*this, FileName(file), readonly)), gui_(0)
261 LYXERR(Debug::INFO, "Buffer::Buffer()");
263 d->inset.setBuffer(*this);
264 d->inset.initParagraphs(*this);
265 d->inset.setAutoBreakRows(true);
266 d->inset.getText(0)->setMacrocontextPosition(par_iterator_begin());
272 LYXERR(Debug::INFO, "Buffer::~Buffer()");
273 // here the buffer should take care that it is
274 // saved properly, before it goes into the void.
276 // GuiView already destroyed
280 // loop over children
281 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
282 Impl::BufferPositionMap::iterator end = d->children_positions.end();
283 for (; it != end; ++it)
284 theBufferList().releaseChild(this, const_cast<Buffer *>(it->first));
286 // clear references to children in macro tables
287 d->children_positions.clear();
288 d->position_to_children.clear();
290 if (!d->temppath.destroyDirectory()) {
291 Alert::warning(_("Could not remove temporary directory"),
292 bformat(_("Could not remove the temporary directory %1$s"),
293 from_utf8(d->temppath.absFilename())));
296 // Remove any previewed LaTeX snippets associated with this buffer.
297 thePreviews().removeLoader(*this);
303 void Buffer::changed() const
310 frontend::WorkAreaManager & Buffer::workAreaManager() const
312 LASSERT(d->wa_, /**/);
317 Text & Buffer::text() const
319 return const_cast<Text &>(d->inset.text_);
323 Inset & Buffer::inset() const
325 return const_cast<InsetText &>(d->inset);
329 BufferParams & Buffer::params()
335 BufferParams const & Buffer::params() const
341 ParagraphList & Buffer::paragraphs()
343 return text().paragraphs();
347 ParagraphList const & Buffer::paragraphs() const
349 return text().paragraphs();
353 LyXVC & Buffer::lyxvc()
359 LyXVC const & Buffer::lyxvc() const
365 string const Buffer::temppath() const
367 return d->temppath.absFilename();
371 TexRow const & Buffer::texrow() const
377 TocBackend & Buffer::tocBackend() const
379 return d->toc_backend;
383 Undo & Buffer::undo()
389 string Buffer::latexName(bool const no_path) const
391 FileName latex_name = makeLatexName(d->filename);
392 return no_path ? latex_name.onlyFileName()
393 : latex_name.absFilename();
397 string Buffer::logName(LogType * type) const
399 string const filename = latexName(false);
401 if (filename.empty()) {
407 string const path = temppath();
409 FileName const fname(addName(temppath(),
410 onlyFilename(changeExtension(filename,
412 FileName const bname(
413 addName(path, onlyFilename(
414 changeExtension(filename,
415 formats.extension("literate") + ".out"))));
417 // If no Latex log or Build log is newer, show Build log
419 if (bname.exists() &&
420 (!fname.exists() || fname.lastModified() < bname.lastModified())) {
421 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
424 return bname.absFilename();
426 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
429 return fname.absFilename();
433 void Buffer::setReadonly(bool const flag)
435 if (d->read_only != flag) {
442 void Buffer::setFileName(string const & newfile)
444 d->filename = makeAbsPath(newfile);
445 setReadonly(d->filename.isReadOnly());
450 int Buffer::readHeader(Lexer & lex)
452 int unknown_tokens = 0;
454 int begin_header_line = -1;
456 // Initialize parameters that may be/go lacking in header:
457 params().branchlist().clear();
458 params().preamble.erase();
459 params().options.erase();
460 params().master.erase();
461 params().float_placement.erase();
462 params().paperwidth.erase();
463 params().paperheight.erase();
464 params().leftmargin.erase();
465 params().rightmargin.erase();
466 params().topmargin.erase();
467 params().bottommargin.erase();
468 params().headheight.erase();
469 params().headsep.erase();
470 params().footskip.erase();
471 params().columnsep.erase();
472 params().fontsCJK.erase();
473 params().listings_params.clear();
474 params().clearLayoutModules();
475 params().clearRemovedModules();
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());
505 if (!unknown.empty()) {
506 if (unknown[0] != '\\' && token == "\\textclass") {
507 Alert::warning(_("Unknown document class"),
508 bformat(_("Using the default document class, because the "
509 "class %1$s is unknown."), from_utf8(unknown)));
512 docstring const s = bformat(_("Unknown token: "
516 errorList.push_back(ErrorItem(_("Document header error"),
521 if (begin_header_line) {
522 docstring const s = _("\\begin_header is missing");
523 errorList.push_back(ErrorItem(_("Document header error"),
527 params().makeDocumentClass();
529 return unknown_tokens;
534 // changed to be public and have one parameter
535 // Returns false if "\end_document" is not read (Asger)
536 bool Buffer::readDocument(Lexer & lex)
538 ErrorList & errorList = d->errorLists["Parse"];
541 if (!lex.checkFor("\\begin_document")) {
542 docstring const s = _("\\begin_document is missing");
543 errorList.push_back(ErrorItem(_("Document header error"),
547 // we are reading in a brand new document
548 LASSERT(paragraphs().empty(), /**/);
552 if (params().outputChanges) {
553 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
554 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
555 LaTeXFeatures::isAvailable("xcolor");
557 if (!dvipost && !xcolorsoul) {
558 Alert::warning(_("Changes not shown in LaTeX output"),
559 _("Changes will not be highlighted in LaTeX output, "
560 "because neither dvipost nor xcolor/soul are installed.\n"
561 "Please install these packages or redefine "
562 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
563 } else if (!xcolorsoul) {
564 Alert::warning(_("Changes not shown in LaTeX output"),
565 _("Changes will not be highlighted in LaTeX output "
566 "when using pdflatex, because xcolor and soul are not installed.\n"
567 "Please install both packages or redefine "
568 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
572 if (!params().master.empty()) {
573 FileName const master_file = makeAbsPath(params().master,
574 onlyPath(absFileName()));
575 if (isLyXFilename(master_file.absFilename())) {
576 Buffer * master = checkAndLoadLyXFile(master_file);
577 d->parent_buffer = master;
582 bool const res = text().read(*this, lex, errorList, &(d->inset));
585 updateMacroInstances();
590 // needed to insert the selection
591 void Buffer::insertStringAsLines(ParagraphList & pars,
592 pit_type & pit, pos_type & pos,
593 Font const & fn, docstring const & str, bool autobreakrows)
597 // insert the string, don't insert doublespace
598 bool space_inserted = true;
599 for (docstring::const_iterator cit = str.begin();
600 cit != str.end(); ++cit) {
601 Paragraph & par = pars[pit];
603 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
604 breakParagraph(params(), pars, pit, pos,
605 par.layout().isEnvironment());
608 space_inserted = true;
612 // do not insert consecutive spaces if !free_spacing
613 } else if ((*cit == ' ' || *cit == '\t') &&
614 space_inserted && !par.isFreeSpacing()) {
616 } else if (*cit == '\t') {
617 if (!par.isFreeSpacing()) {
618 // tabs are like spaces here
619 par.insertChar(pos, ' ', font, params().trackChanges);
621 space_inserted = true;
623 const pos_type n = 8 - pos % 8;
624 for (pos_type i = 0; i < n; ++i) {
625 par.insertChar(pos, ' ', font, params().trackChanges);
628 space_inserted = true;
630 } else if (!isPrintable(*cit)) {
631 // Ignore unprintables
634 // just insert the character
635 par.insertChar(pos, *cit, font, params().trackChanges);
637 space_inserted = (*cit == ' ');
644 bool Buffer::readString(string const & s)
646 params().compressed = false;
648 // remove dummy empty par
649 paragraphs().clear();
653 FileName const name = FileName::tempName("Buffer_readString");
654 switch (readFile(lex, name, true)) {
658 // We need to call lyx2lyx, so write the input to a file
659 ofstream os(name.toFilesystemEncoding().c_str());
662 return readFile(name);
672 bool Buffer::readFile(FileName const & filename)
674 FileName fname(filename);
676 // remove dummy empty par
677 paragraphs().clear();
680 if (readFile(lex, fname) != success)
687 bool Buffer::isFullyLoaded() const
689 return d->file_fully_loaded;
693 void Buffer::setFullyLoaded(bool value)
695 d->file_fully_loaded = value;
699 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
702 LASSERT(!filename.empty(), /**/);
704 // the first (non-comment) token _must_ be...
705 if (!lex.checkFor("\\lyxformat")) {
706 Alert::error(_("Document format failure"),
707 bformat(_("%1$s is not a readable LyX document."),
708 from_utf8(filename.absFilename())));
714 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
715 // if present remove ".," from string.
716 size_t dot = tmp_format.find_first_of(".,");
717 //lyxerr << " dot found at " << dot << endl;
718 if (dot != string::npos)
719 tmp_format.erase(dot, 1);
720 int const file_format = convert<int>(tmp_format);
721 //lyxerr << "format: " << file_format << endl;
723 // save timestamp and checksum of the original disk file, making sure
724 // to not overwrite them with those of the file created in the tempdir
725 // when it has to be converted to the current format.
727 // Save the timestamp and checksum of disk file. If filename is an
728 // emergency file, save the timestamp and checksum of the original lyx file
729 // because isExternallyModified will check for this file. (BUG4193)
730 string diskfile = filename.absFilename();
731 if (suffixIs(diskfile, ".emergency"))
732 diskfile = diskfile.substr(0, diskfile.size() - 10);
733 saveCheckSum(FileName(diskfile));
736 if (file_format != LYX_FORMAT) {
739 // lyx2lyx would fail
742 FileName const tmpfile = FileName::tempName("Buffer_readFile");
743 if (tmpfile.empty()) {
744 Alert::error(_("Conversion failed"),
745 bformat(_("%1$s is from a different"
746 " version of LyX, but a temporary"
747 " file for converting it could"
749 from_utf8(filename.absFilename())));
752 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
753 if (lyx2lyx.empty()) {
754 Alert::error(_("Conversion script not found"),
755 bformat(_("%1$s is from a different"
756 " version of LyX, but the"
757 " conversion script lyx2lyx"
758 " could not be found."),
759 from_utf8(filename.absFilename())));
762 ostringstream command;
763 command << os::python()
764 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
765 << " -t " << convert<string>(LYX_FORMAT)
766 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
767 << ' ' << quoteName(filename.toFilesystemEncoding());
768 string const command_str = command.str();
770 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
772 cmd_ret const ret = runCommand(command_str);
773 if (ret.first != 0) {
774 Alert::error(_("Conversion script failed"),
775 bformat(_("%1$s is from a different version"
776 " of LyX, but the lyx2lyx script"
777 " failed to convert it."),
778 from_utf8(filename.absFilename())));
781 bool const ret = readFile(tmpfile);
782 // Do stuff with tmpfile name and buffer name here.
783 return ret ? success : failure;
788 if (readDocument(lex)) {
789 Alert::error(_("Document format failure"),
790 bformat(_("%1$s ended unexpectedly, which means"
791 " that it is probably corrupted."),
792 from_utf8(filename.absFilename())));
795 d->file_fully_loaded = true;
800 // Should probably be moved to somewhere else: BufferView? LyXView?
801 bool Buffer::save() const
803 // We don't need autosaves in the immediate future. (Asger)
804 resetAutosaveTimers();
806 string const encodedFilename = d->filename.toFilesystemEncoding();
809 bool madeBackup = false;
811 // make a backup if the file already exists
812 if (lyxrc.make_backup && fileName().exists()) {
813 backupName = FileName(absFileName() + '~');
814 if (!lyxrc.backupdir_path.empty()) {
815 string const mangledName =
816 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
817 backupName = FileName(addName(lyxrc.backupdir_path,
820 if (fileName().copyTo(backupName)) {
823 Alert::error(_("Backup failure"),
824 bformat(_("Cannot create backup file %1$s.\n"
825 "Please check whether the directory exists and is writeable."),
826 from_utf8(backupName.absFilename())));
827 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
831 // ask if the disk file has been externally modified (use checksum method)
832 if (fileName().exists() && isExternallyModified(checksum_method)) {
833 docstring const file = makeDisplayPath(absFileName(), 20);
834 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
835 "you want to overwrite this file?"), file);
836 int const ret = Alert::prompt(_("Overwrite modified file?"),
837 text, 1, 1, _("&Overwrite"), _("&Cancel"));
842 if (writeFile(d->filename)) {
846 // Saving failed, so backup is not backup
848 backupName.moveTo(d->filename);
854 bool Buffer::writeFile(FileName const & fname) const
856 if (d->read_only && fname == d->filename)
861 docstring const str = bformat(_("Saving document %1$s..."),
862 makeDisplayPath(fname.absFilename()));
865 if (params().compressed) {
866 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
867 retval = ofs && write(ofs);
869 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
870 retval = ofs && write(ofs);
874 message(str + _(" could not write file!"));
878 removeAutosaveFile(d->filename.absFilename());
880 saveCheckSum(d->filename);
881 message(str + _(" done."));
887 bool Buffer::write(ostream & ofs) const
890 // Use the standard "C" locale for file output.
891 ofs.imbue(locale::classic());
894 // The top of the file should not be written by params().
896 // write out a comment in the top of the file
897 ofs << "#LyX " << lyx_version
898 << " created this file. For more info see http://www.lyx.org/\n"
899 << "\\lyxformat " << LYX_FORMAT << "\n"
900 << "\\begin_document\n";
902 /// For each author, set 'used' to true if there is a change
903 /// by this author in the document; otherwise set it to 'false'.
904 AuthorList::Authors::const_iterator a_it = params().authors().begin();
905 AuthorList::Authors::const_iterator a_end = params().authors().end();
906 for (; a_it != a_end; ++a_it)
907 a_it->second.setUsed(false);
909 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
910 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
911 for ( ; it != end; ++it)
912 it->checkAuthors(params().authors());
914 // now write out the buffer parameters.
915 ofs << "\\begin_header\n";
916 params().writeFile(ofs);
917 ofs << "\\end_header\n";
920 ofs << "\n\\begin_body\n";
921 text().write(*this, ofs);
922 ofs << "\n\\end_body\n";
924 // Write marker that shows file is complete
925 ofs << "\\end_document" << endl;
927 // Shouldn't really be needed....
930 // how to check if close went ok?
931 // Following is an attempt... (BE 20001011)
933 // good() returns false if any error occured, including some
935 // bad() returns true if something bad happened in the buffer,
936 // which should include file system full errors.
941 lyxerr << "File was not closed properly." << endl;
948 bool Buffer::makeLaTeXFile(FileName const & fname,
949 string const & original_path,
950 OutputParams const & runparams,
951 bool output_preamble, bool output_body) const
953 string const encoding = runparams.encoding->iconvName();
954 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
957 try { ofs.reset(encoding); }
958 catch (iconv_codecvt_facet_exception & e) {
959 lyxerr << "Caught iconv exception: " << e.what() << endl;
960 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
961 "verify that the support software for your encoding (%1$s) is "
962 "properly installed"), from_ascii(encoding)));
965 if (!openFileWrite(ofs, fname))
968 //TexStream ts(ofs.rdbuf(), &texrow());
969 ErrorList & errorList = d->errorLists["Export"];
971 bool failed_export = false;
974 writeLaTeXSource(ofs, original_path,
975 runparams, output_preamble, output_body);
977 catch (EncodingException & e) {
978 odocstringstream ods;
979 ods.put(e.failed_char);
981 oss << "0x" << hex << e.failed_char << dec;
982 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
983 " (code point %2$s)"),
984 ods.str(), from_utf8(oss.str()));
985 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
986 "representable in the chosen encoding.\n"
987 "Changing the document encoding to utf8 could help."),
988 e.par_id, e.pos, e.pos + 1));
989 failed_export = true;
991 catch (iconv_codecvt_facet_exception & e) {
992 errorList.push_back(ErrorItem(_("iconv conversion failed"),
993 _(e.what()), -1, 0, 0));
994 failed_export = true;
996 catch (exception const & e) {
997 errorList.push_back(ErrorItem(_("conversion failed"),
998 _(e.what()), -1, 0, 0));
999 failed_export = true;
1002 lyxerr << "Caught some really weird exception..." << endl;
1008 failed_export = true;
1009 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1013 return !failed_export;
1017 void Buffer::writeLaTeXSource(odocstream & os,
1018 string const & original_path,
1019 OutputParams const & runparams_in,
1020 bool const output_preamble, bool const output_body) const
1022 // The child documents, if any, shall be already loaded at this point.
1024 OutputParams runparams = runparams_in;
1026 // validate the buffer.
1027 LYXERR(Debug::LATEX, " Validating buffer...");
1028 LaTeXFeatures features(*this, params(), runparams);
1030 LYXERR(Debug::LATEX, " Buffer validation done.");
1032 // The starting paragraph of the coming rows is the
1033 // first paragraph of the document. (Asger)
1034 if (output_preamble && runparams.nice) {
1035 os << "%% LyX " << lyx_version << " created this file. "
1036 "For more info, see http://www.lyx.org/.\n"
1037 "%% Do not edit unless you really know what "
1039 d->texrow.newline();
1040 d->texrow.newline();
1042 LYXERR(Debug::INFO, "lyx document header finished");
1044 // Don't move this behind the parent_buffer=0 code below,
1045 // because then the macros will not get the right "redefinition"
1046 // flag as they don't see the parent macros which are output before.
1049 // fold macros if possible, still with parent buffer as the
1050 // macros will be put in the prefix anyway.
1051 updateMacroInstances();
1053 // There are a few differences between nice LaTeX and usual files:
1054 // usual is \batchmode and has a
1055 // special input@path to allow the including of figures
1056 // with either \input or \includegraphics (what figinsets do).
1057 // input@path is set when the actual parameter
1058 // original_path is set. This is done for usual tex-file, but not
1059 // for nice-latex-file. (Matthias 250696)
1060 // Note that input@path is only needed for something the user does
1061 // in the preamble, included .tex files or ERT, files included by
1062 // LyX work without it.
1063 if (output_preamble) {
1064 if (!runparams.nice) {
1065 // code for usual, NOT nice-latex-file
1066 os << "\\batchmode\n"; // changed
1067 // from \nonstopmode
1068 d->texrow.newline();
1070 if (!original_path.empty()) {
1072 // We don't know the encoding of inputpath
1073 docstring const inputpath = from_utf8(latex_path(original_path));
1074 os << "\\makeatletter\n"
1075 << "\\def\\input@path{{"
1076 << inputpath << "/}}\n"
1077 << "\\makeatother\n";
1078 d->texrow.newline();
1079 d->texrow.newline();
1080 d->texrow.newline();
1083 // get parent macros (if this buffer has a parent) which will be
1084 // written at the document begin further down.
1085 MacroSet parentMacros;
1086 listParentMacros(parentMacros, features);
1088 // Write the preamble
1089 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1095 os << "\\begin{document}\n";
1096 d->texrow.newline();
1098 // output the parent macros
1099 MacroSet::iterator it = parentMacros.begin();
1100 MacroSet::iterator end = parentMacros.end();
1101 for (; it != end; ++it)
1102 (*it)->write(os, true);
1103 } // output_preamble
1105 d->texrow.start(paragraphs().begin()->id(), 0);
1107 LYXERR(Debug::INFO, "preamble finished, now the body.");
1109 // if we are doing a real file with body, even if this is the
1110 // child of some other buffer, let's cut the link here.
1111 // This happens for example if only a child document is printed.
1112 Buffer const * save_parent = 0;
1113 if (output_preamble) {
1114 save_parent = d->parent_buffer;
1115 d->parent_buffer = 0;
1119 latexParagraphs(*this, text(), os, d->texrow, runparams);
1121 // Restore the parenthood if needed
1122 if (output_preamble)
1123 d->parent_buffer = save_parent;
1125 // add this just in case after all the paragraphs
1127 d->texrow.newline();
1129 if (output_preamble) {
1130 os << "\\end{document}\n";
1131 d->texrow.newline();
1132 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1134 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1136 runparams_in.encoding = runparams.encoding;
1138 // Just to be sure. (Asger)
1139 d->texrow.newline();
1141 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1142 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1146 bool Buffer::isLatex() const
1148 return params().documentClass().outputType() == LATEX;
1152 bool Buffer::isLiterate() const
1154 return params().documentClass().outputType() == LITERATE;
1158 bool Buffer::isDocBook() const
1160 return params().documentClass().outputType() == DOCBOOK;
1164 void Buffer::makeDocBookFile(FileName const & fname,
1165 OutputParams const & runparams,
1166 bool const body_only) const
1168 LYXERR(Debug::LATEX, "makeDocBookFile...");
1171 if (!openFileWrite(ofs, fname))
1174 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1178 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1182 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1183 OutputParams const & runparams,
1184 bool const only_body) const
1186 LaTeXFeatures features(*this, params(), runparams);
1191 DocumentClass const & tclass = params().documentClass();
1192 string const top_element = tclass.latexname();
1195 if (runparams.flavor == OutputParams::XML)
1196 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1199 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1202 if (! tclass.class_header().empty())
1203 os << from_ascii(tclass.class_header());
1204 else if (runparams.flavor == OutputParams::XML)
1205 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1206 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1208 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1210 docstring preamble = from_utf8(params().preamble);
1211 if (runparams.flavor != OutputParams::XML ) {
1212 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1213 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1214 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1215 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1218 string const name = runparams.nice
1219 ? changeExtension(absFileName(), ".sgml") : fname;
1220 preamble += features.getIncludedFiles(name);
1221 preamble += features.getLyXSGMLEntities();
1223 if (!preamble.empty()) {
1224 os << "\n [ " << preamble << " ]";
1229 string top = top_element;
1231 if (runparams.flavor == OutputParams::XML)
1232 top += params().language->code();
1234 top += params().language->code().substr(0,2);
1237 if (!params().options.empty()) {
1239 top += params().options;
1242 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1243 << " file was created by LyX " << lyx_version
1244 << "\n See http://www.lyx.org/ for more information -->\n";
1246 params().documentClass().counters().reset();
1250 sgml::openTag(os, top);
1252 docbookParagraphs(paragraphs(), *this, os, runparams);
1253 sgml::closeTag(os, top_element);
1257 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1258 // Other flags: -wall -v0 -x
1259 int Buffer::runChktex()
1263 // get LaTeX-Filename
1264 FileName const path(temppath());
1265 string const name = addName(path.absFilename(), latexName());
1266 string const org_path = filePath();
1268 PathChanger p(path); // path to LaTeX file
1269 message(_("Running chktex..."));
1271 // Generate the LaTeX file if neccessary
1272 OutputParams runparams(¶ms().encoding());
1273 runparams.flavor = OutputParams::LATEX;
1274 runparams.nice = false;
1275 makeLaTeXFile(FileName(name), org_path, runparams);
1278 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1279 int const res = chktex.run(terr); // run chktex
1282 Alert::error(_("chktex failure"),
1283 _("Could not run chktex successfully."));
1284 } else if (res > 0) {
1285 ErrorList & errlist = d->errorLists["ChkTeX"];
1287 bufferErrors(terr, errlist);
1298 void Buffer::validate(LaTeXFeatures & features) const
1300 params().validate(features);
1304 for_each(paragraphs().begin(), paragraphs().end(),
1305 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1307 if (lyxerr.debugging(Debug::LATEX)) {
1308 features.showStruct();
1313 void Buffer::getLabelList(vector<docstring> & list) const
1315 // If this is a child document, use the parent's list instead.
1316 if (d->parent_buffer) {
1317 d->parent_buffer->getLabelList(list);
1322 Toc & toc = d->toc_backend.toc("label");
1323 TocIterator toc_it = toc.begin();
1324 TocIterator end = toc.end();
1325 for (; toc_it != end; ++toc_it) {
1326 if (toc_it->depth() == 0)
1327 list.push_back(toc_it->str());
1332 void Buffer::updateBibfilesCache() const
1334 // If this is a child document, use the parent's cache instead.
1335 if (d->parent_buffer) {
1336 d->parent_buffer->updateBibfilesCache();
1340 d->bibfilesCache_.clear();
1341 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1342 if (it->lyxCode() == BIBTEX_CODE) {
1343 InsetBibtex const & inset =
1344 static_cast<InsetBibtex const &>(*it);
1345 support::FileNameList const bibfiles = inset.getBibFiles();
1346 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1349 } else if (it->lyxCode() == INCLUDE_CODE) {
1350 InsetInclude & inset =
1351 static_cast<InsetInclude &>(*it);
1352 inset.updateBibfilesCache();
1353 support::FileNameList const & bibfiles =
1354 inset.getBibfilesCache(*this);
1355 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1360 // the bibinfo cache is now invalid
1361 d->bibinfoCacheValid_ = false;
1365 void Buffer::invalidateBibinfoCache()
1367 d->bibinfoCacheValid_ = false;
1371 support::FileNameList const & Buffer::getBibfilesCache() const
1373 // If this is a child document, use the parent's cache instead.
1374 if (d->parent_buffer)
1375 return d->parent_buffer->getBibfilesCache();
1377 // We update the cache when first used instead of at loading time.
1378 if (d->bibfilesCache_.empty())
1379 const_cast<Buffer *>(this)->updateBibfilesCache();
1381 return d->bibfilesCache_;
1385 BiblioInfo const & Buffer::masterBibInfo() const
1387 // if this is a child document and the parent is already loaded
1388 // use the parent's list instead [ale990412]
1389 Buffer const * const tmp = masterBuffer();
1392 return tmp->masterBibInfo();
1393 return localBibInfo();
1397 BiblioInfo const & Buffer::localBibInfo() const
1399 if (d->bibinfoCacheValid_) {
1400 support::FileNameList const & bibfilesCache = getBibfilesCache();
1401 // compare the cached timestamps with the actual ones.
1402 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1403 support::FileNameList::const_iterator en = bibfilesCache.end();
1404 for (; ei != en; ++ ei) {
1405 time_t lastw = ei->lastModified();
1406 if (lastw != d->bibfileStatus_[*ei]) {
1407 d->bibinfoCacheValid_ = false;
1408 d->bibfileStatus_[*ei] = lastw;
1414 if (!d->bibinfoCacheValid_) {
1415 d->bibinfo_.clear();
1416 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1417 it->fillWithBibKeys(d->bibinfo_, it);
1418 d->bibinfoCacheValid_ = true;
1424 bool Buffer::isDepClean(string const & name) const
1426 DepClean::const_iterator const it = d->dep_clean.find(name);
1427 if (it == d->dep_clean.end())
1433 void Buffer::markDepClean(string const & name)
1435 d->dep_clean[name] = true;
1439 bool Buffer::dispatch(string const & command, bool * result)
1441 return dispatch(lyxaction.lookupFunc(command), result);
1445 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1447 bool dispatched = true;
1449 switch (func.action) {
1450 case LFUN_BUFFER_EXPORT: {
1451 bool const tmp = doExport(to_utf8(func.argument()), false);
1457 case LFUN_BRANCH_ACTIVATE:
1458 case LFUN_BRANCH_DEACTIVATE: {
1459 BranchList & branchList = params().branchlist();
1460 docstring const branchName = func.argument();
1461 Branch * branch = branchList.find(branchName);
1463 LYXERR0("Branch " << branchName << " does not exist.");
1465 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1477 void Buffer::changeLanguage(Language const * from, Language const * to)
1479 LASSERT(from, /**/);
1482 for_each(par_iterator_begin(),
1484 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1488 bool Buffer::isMultiLingual() const
1490 ParConstIterator end = par_iterator_end();
1491 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1492 if (it->isMultiLingual(params()))
1499 DocIterator Buffer::getParFromID(int const id) const
1502 // John says this is called with id == -1 from undo
1503 lyxerr << "getParFromID(), id: " << id << endl;
1504 return doc_iterator_end(inset());
1507 for (DocIterator it = doc_iterator_begin(inset()); !it.atEnd(); it.forwardPar())
1508 if (it.paragraph().id() == id)
1511 return doc_iterator_end(inset());
1515 bool Buffer::hasParWithID(int const id) const
1517 return !getParFromID(id).atEnd();
1521 ParIterator Buffer::par_iterator_begin()
1523 return ParIterator(doc_iterator_begin(inset()));
1527 ParIterator Buffer::par_iterator_end()
1529 return ParIterator(doc_iterator_end(inset()));
1533 ParConstIterator Buffer::par_iterator_begin() const
1535 return lyx::par_const_iterator_begin(inset());
1539 ParConstIterator Buffer::par_iterator_end() const
1541 return lyx::par_const_iterator_end(inset());
1545 Language const * Buffer::language() const
1547 return params().language;
1551 docstring const Buffer::B_(string const & l10n) const
1553 return params().B_(l10n);
1557 bool Buffer::isClean() const
1559 return d->lyx_clean;
1563 bool Buffer::isBakClean() const
1565 return d->bak_clean;
1569 bool Buffer::isExternallyModified(CheckMethod method) const
1571 LASSERT(d->filename.exists(), /**/);
1572 // if method == timestamp, check timestamp before checksum
1573 return (method == checksum_method
1574 || d->timestamp_ != d->filename.lastModified())
1575 && d->checksum_ != d->filename.checksum();
1579 void Buffer::saveCheckSum(FileName const & file) const
1581 if (file.exists()) {
1582 d->timestamp_ = file.lastModified();
1583 d->checksum_ = file.checksum();
1585 // in the case of save to a new file.
1592 void Buffer::markClean() const
1594 if (!d->lyx_clean) {
1595 d->lyx_clean = true;
1598 // if the .lyx file has been saved, we don't need an
1600 d->bak_clean = true;
1604 void Buffer::markBakClean() const
1606 d->bak_clean = true;
1610 void Buffer::setUnnamed(bool flag)
1616 bool Buffer::isUnnamed() const
1622 // FIXME: this function should be moved to buffer_pimpl.C
1623 void Buffer::markDirty()
1626 d->lyx_clean = false;
1629 d->bak_clean = false;
1631 DepClean::iterator it = d->dep_clean.begin();
1632 DepClean::const_iterator const end = d->dep_clean.end();
1634 for (; it != end; ++it)
1639 FileName Buffer::fileName() const
1645 string Buffer::absFileName() const
1647 return d->filename.absFilename();
1651 string Buffer::filePath() const
1653 return d->filename.onlyPath().absFilename() + "/";
1657 bool Buffer::isReadonly() const
1659 return d->read_only;
1663 void Buffer::setParent(Buffer const * buffer)
1665 // Avoids recursive include.
1666 d->parent_buffer = buffer == this ? 0 : buffer;
1671 Buffer const * Buffer::parent()
1673 return d->parent_buffer;
1677 Buffer const * Buffer::masterBuffer() const
1679 if (!d->parent_buffer)
1682 return d->parent_buffer->masterBuffer();
1686 bool Buffer::isChild(Buffer * child) const
1688 return d->children_positions.find(child) != d->children_positions.end();
1692 template<typename M>
1693 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
1698 typename M::iterator it = m.lower_bound(x);
1699 if (it == m.begin())
1707 MacroData const * Buffer::getBufferMacro(docstring const & name,
1708 DocIterator const & pos) const
1710 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
1712 // if paragraphs have no macro context set, pos will be empty
1716 // we haven't found anything yet
1717 DocIterator bestPos = par_iterator_begin();
1718 MacroData const * bestData = 0;
1720 // find macro definitions for name
1721 Impl::NamePositionScopeMacroMap::iterator nameIt
1722 = d->macros.find(name);
1723 if (nameIt != d->macros.end()) {
1724 // find last definition in front of pos or at pos itself
1725 Impl::PositionScopeMacroMap::const_iterator it
1726 = greatest_below(nameIt->second, pos);
1727 if (it != nameIt->second.end()) {
1729 // scope ends behind pos?
1730 if (pos < it->second.first) {
1731 // Looks good, remember this. If there
1732 // is no external macro behind this,
1733 // we found the right one already.
1734 bestPos = it->first;
1735 bestData = &it->second.second;
1739 // try previous macro if there is one
1740 if (it == nameIt->second.begin())
1747 // find macros in included files
1748 Impl::PositionScopeBufferMap::const_iterator it
1749 = greatest_below(d->position_to_children, pos);
1750 if (it == d->position_to_children.end())
1751 // no children before
1755 // do we know something better (i.e. later) already?
1756 if (it->first < bestPos )
1759 // scope ends behind pos?
1760 if (pos < it->second.first) {
1761 // look for macro in external file
1762 d->macro_lock = true;
1763 MacroData const * data
1764 = it->second.second->getMacro(name, false);
1765 d->macro_lock = false;
1767 bestPos = it->first;
1773 // try previous file if there is one
1774 if (it == d->position_to_children.begin())
1779 // return the best macro we have found
1784 MacroData const * Buffer::getMacro(docstring const & name,
1785 DocIterator const & pos, bool global) const
1790 // query buffer macros
1791 MacroData const * data = getBufferMacro(name, pos);
1795 // If there is a master buffer, query that
1796 if (d->parent_buffer) {
1797 d->macro_lock = true;
1798 MacroData const * macro = d->parent_buffer->getMacro(
1799 name, *this, false);
1800 d->macro_lock = false;
1806 data = MacroTable::globalMacros().get(name);
1815 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
1817 // set scope end behind the last paragraph
1818 DocIterator scope = par_iterator_begin();
1819 scope.pit() = scope.lastpit() + 1;
1821 return getMacro(name, scope, global);
1825 MacroData const * Buffer::getMacro(docstring const & name,
1826 Buffer const & child, bool global) const
1828 // look where the child buffer is included first
1829 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
1830 if (it == d->children_positions.end())
1833 // check for macros at the inclusion position
1834 return getMacro(name, it->second, global);
1838 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
1840 pit_type lastpit = it.lastpit();
1842 // look for macros in each paragraph
1843 while (it.pit() <= lastpit) {
1844 Paragraph & par = it.paragraph();
1846 // iterate over the insets of the current paragraph
1847 InsetList const & insets = par.insetList();
1848 InsetList::const_iterator iit = insets.begin();
1849 InsetList::const_iterator end = insets.end();
1850 for (; iit != end; ++iit) {
1851 it.pos() = iit->pos;
1853 // is it a nested text inset?
1854 if (iit->inset->asInsetText()) {
1855 // Inset needs its own scope?
1856 InsetText const * itext
1857 = iit->inset->asInsetText();
1858 bool newScope = itext->isMacroScope();
1860 // scope which ends just behind the inset
1861 DocIterator insetScope = it;
1864 // collect macros in inset
1865 it.push_back(CursorSlice(*iit->inset));
1866 updateMacros(it, newScope ? insetScope : scope);
1871 // is it an external file?
1872 if (iit->inset->lyxCode() == INCLUDE_CODE) {
1873 // get buffer of external file
1874 InsetCommand const & inset
1875 = static_cast<InsetCommand const &>(*iit->inset);
1876 InsetCommandParams const & ip = inset.params();
1877 d->macro_lock = true;
1878 Buffer * child = loadIfNeeded(*this, ip);
1879 d->macro_lock = false;
1883 // register its position, but only when it is
1884 // included first in the buffer
1885 if (d->children_positions.find(child)
1886 == d->children_positions.end())
1887 d->children_positions[child] = it;
1889 // register child with its scope
1890 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
1894 if (iit->inset->lyxCode() != MATHMACRO_CODE)
1898 MathMacroTemplate & macroTemplate
1899 = static_cast<MathMacroTemplate &>(*iit->inset);
1900 MacroContext mc(*this, it);
1901 macroTemplate.updateToContext(mc);
1904 bool valid = macroTemplate.validMacro();
1905 // FIXME: Should be fixNameAndCheckIfValid() in fact,
1906 // then the BufferView's cursor will be invalid in
1907 // some cases which leads to crashes.
1912 d->macros[macroTemplate.name()][it] =
1913 Impl::ScopeMacro(scope, MacroData(*this, it));
1923 void Buffer::updateMacros() const
1928 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
1930 // start with empty table
1932 d->children_positions.clear();
1933 d->position_to_children.clear();
1935 // Iterate over buffer, starting with first paragraph
1936 // The scope must be bigger than any lookup DocIterator
1937 // later. For the global lookup, lastpit+1 is used, hence
1938 // we use lastpit+2 here.
1939 DocIterator it = par_iterator_begin();
1940 DocIterator outerScope = it;
1941 outerScope.pit() = outerScope.lastpit() + 2;
1942 updateMacros(it, outerScope);
1946 void Buffer::updateMacroInstances() const
1948 LYXERR(Debug::MACROS, "updateMacroInstances for "
1949 << d->filename.onlyFileName());
1950 DocIterator it = doc_iterator_begin(inset());
1951 DocIterator end = doc_iterator_end(inset());
1952 for (; it != end; it.forwardPos()) {
1953 // look for MathData cells in InsetMathNest insets
1954 Inset * inset = it.nextInset();
1958 InsetMath * minset = inset->asInsetMath();
1962 // update macro in all cells of the InsetMathNest
1963 DocIterator::idx_type n = minset->nargs();
1964 MacroContext mc = MacroContext(*this, it);
1965 for (DocIterator::idx_type i = 0; i < n; ++i) {
1966 MathData & data = minset->cell(i);
1967 data.updateMacros(0, mc);
1973 void Buffer::listMacroNames(MacroNameSet & macros) const
1978 d->macro_lock = true;
1980 // loop over macro names
1981 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
1982 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
1983 for (; nameIt != nameEnd; ++nameIt)
1984 macros.insert(nameIt->first);
1986 // loop over children
1987 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
1988 Impl::BufferPositionMap::iterator end = d->children_positions.end();
1989 for (; it != end; ++it)
1990 it->first->listMacroNames(macros);
1993 if (d->parent_buffer)
1994 d->parent_buffer->listMacroNames(macros);
1996 d->macro_lock = false;
2000 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2002 if (!d->parent_buffer)
2006 d->parent_buffer->listMacroNames(names);
2009 MacroNameSet::iterator it = names.begin();
2010 MacroNameSet::iterator end = names.end();
2011 for (; it != end; ++it) {
2013 MacroData const * data =
2014 d->parent_buffer->getMacro(*it, *this, false);
2016 macros.insert(data);
2018 // we cannot access the original MathMacroTemplate anymore
2019 // here to calls validate method. So we do its work here manually.
2020 // FIXME: somehow make the template accessible here.
2021 if (data->optionals() > 0)
2022 features.require("xargs");
2028 Buffer::References & Buffer::references(docstring const & label)
2030 if (d->parent_buffer)
2031 return const_cast<Buffer *>(masterBuffer())->references(label);
2033 RefCache::iterator it = d->ref_cache_.find(label);
2034 if (it != d->ref_cache_.end())
2035 return it->second.second;
2037 static InsetLabel const * dummy_il = 0;
2038 static References const dummy_refs;
2039 it = d->ref_cache_.insert(
2040 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2041 return it->second.second;
2045 Buffer::References const & Buffer::references(docstring const & label) const
2047 return const_cast<Buffer *>(this)->references(label);
2051 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2053 masterBuffer()->d->ref_cache_[label].first = il;
2057 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2059 return masterBuffer()->d->ref_cache_[label].first;
2063 void Buffer::clearReferenceCache() const
2065 if (!d->parent_buffer)
2066 d->ref_cache_.clear();
2070 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2073 //FIXME: This does not work for child documents yet.
2074 LASSERT(code == CITE_CODE, /**/);
2075 // Check if the label 'from' appears more than once
2076 vector<docstring> labels;
2078 BiblioInfo const & keys = masterBibInfo();
2079 BiblioInfo::const_iterator bit = keys.begin();
2080 BiblioInfo::const_iterator bend = keys.end();
2082 for (; bit != bend; ++bit)
2084 labels.push_back(bit->first);
2087 if (count(labels.begin(), labels.end(), from) > 1)
2090 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2091 if (it->lyxCode() == code) {
2092 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2093 docstring const oldValue = inset.getParam(paramName);
2094 if (oldValue == from)
2095 inset.setParam(paramName, to);
2101 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2102 pit_type par_end, bool full_source)
2104 OutputParams runparams(¶ms().encoding());
2105 runparams.nice = true;
2106 runparams.flavor = OutputParams::LATEX;
2107 runparams.linelen = lyxrc.plaintext_linelen;
2108 // No side effect of file copying and image conversion
2109 runparams.dryrun = true;
2113 os << "% " << _("Preview source code") << "\n\n";
2114 d->texrow.newline();
2115 d->texrow.newline();
2117 writeLaTeXSource(os, filePath(), runparams, true, true);
2119 writeDocBookSource(os, absFileName(), runparams, false);
2121 runparams.par_begin = par_begin;
2122 runparams.par_end = par_end;
2123 if (par_begin + 1 == par_end) {
2125 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2129 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2130 convert<docstring>(par_begin),
2131 convert<docstring>(par_end - 1))
2134 d->texrow.newline();
2135 d->texrow.newline();
2136 // output paragraphs
2138 latexParagraphs(*this, text(), os, d->texrow, runparams);
2141 docbookParagraphs(paragraphs(), *this, os, runparams);
2146 ErrorList & Buffer::errorList(string const & type) const
2148 static ErrorList emptyErrorList;
2149 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2150 if (I == d->errorLists.end())
2151 return emptyErrorList;
2157 void Buffer::structureChanged() const
2160 gui_->structureChanged();
2164 void Buffer::errors(string const & err) const
2171 void Buffer::message(docstring const & msg) const
2178 void Buffer::setBusy(bool on) const
2185 void Buffer::setReadOnly(bool on) const
2188 d->wa_->setReadOnly(on);
2192 void Buffer::updateTitles() const
2195 d->wa_->updateTitles();
2199 void Buffer::resetAutosaveTimers() const
2202 gui_->resetAutosaveTimers();
2206 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2215 class AutoSaveBuffer : public ForkedProcess {
2218 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2219 : buffer_(buffer), fname_(fname) {}
2221 virtual boost::shared_ptr<ForkedProcess> clone() const
2223 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2228 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2229 from_utf8(fname_.absFilename())));
2230 return run(DontWait);
2234 virtual int generateChild();
2236 Buffer const & buffer_;
2241 int AutoSaveBuffer::generateChild()
2243 // tmp_ret will be located (usually) in /tmp
2244 // will that be a problem?
2245 // Note that this calls ForkedCalls::fork(), so it's
2246 // ok cross-platform.
2247 pid_t const pid = fork();
2248 // If you want to debug the autosave
2249 // you should set pid to -1, and comment out the fork.
2250 if (pid != 0 && pid != -1)
2253 // pid = -1 signifies that lyx was unable
2254 // to fork. But we will do the save
2256 bool failed = false;
2257 FileName const tmp_ret = FileName::tempName("lyxauto");
2258 if (!tmp_ret.empty()) {
2259 buffer_.writeFile(tmp_ret);
2260 // assume successful write of tmp_ret
2261 if (!tmp_ret.moveTo(fname_))
2267 // failed to write/rename tmp_ret so try writing direct
2268 if (!buffer_.writeFile(fname_)) {
2269 // It is dangerous to do this in the child,
2270 // but safe in the parent, so...
2271 if (pid == -1) // emit message signal.
2272 buffer_.message(_("Autosave failed!"));
2276 if (pid == 0) // we are the child so...
2285 // Perfect target for a thread...
2286 void Buffer::autoSave() const
2288 if (isBakClean() || isReadonly()) {
2289 // We don't save now, but we'll try again later
2290 resetAutosaveTimers();
2294 // emit message signal.
2295 message(_("Autosaving current document..."));
2297 // create autosave filename
2298 string fname = filePath();
2300 fname += d->filename.onlyFileName();
2303 AutoSaveBuffer autosave(*this, FileName(fname));
2307 resetAutosaveTimers();
2311 string Buffer::bufferFormat() const
2321 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2322 string & result_file) const
2324 string backend_format;
2325 OutputParams runparams(¶ms().encoding());
2326 runparams.flavor = OutputParams::LATEX;
2327 runparams.linelen = lyxrc.plaintext_linelen;
2328 vector<string> backs = backends();
2329 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2330 // Get shortest path to format
2331 Graph::EdgePath path;
2332 for (vector<string>::const_iterator it = backs.begin();
2333 it != backs.end(); ++it) {
2334 Graph::EdgePath p = theConverters().getPath(*it, format);
2335 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2336 backend_format = *it;
2341 runparams.flavor = theConverters().getFlavor(path);
2343 Alert::error(_("Couldn't export file"),
2344 bformat(_("No information for exporting the format %1$s."),
2345 formats.prettyName(format)));
2349 backend_format = format;
2350 // FIXME: Don't hardcode format names here, but use a flag
2351 if (backend_format == "pdflatex")
2352 runparams.flavor = OutputParams::PDFLATEX;
2355 string filename = latexName(false);
2356 filename = addName(temppath(), filename);
2357 filename = changeExtension(filename,
2358 formats.extension(backend_format));
2361 updateMacroInstances();
2363 // Plain text backend
2364 if (backend_format == "text")
2365 writePlaintextFile(*this, FileName(filename), runparams);
2367 else if (backend_format == "lyx")
2368 writeFile(FileName(filename));
2370 else if (isDocBook()) {
2371 runparams.nice = !put_in_tempdir;
2372 makeDocBookFile(FileName(filename), runparams);
2375 else if (backend_format == format) {
2376 runparams.nice = true;
2377 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2379 } else if (!lyxrc.tex_allows_spaces
2380 && contains(filePath(), ' ')) {
2381 Alert::error(_("File name error"),
2382 _("The directory path to the document cannot contain spaces."));
2385 runparams.nice = false;
2386 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2390 string const error_type = (format == "program")
2391 ? "Build" : bufferFormat();
2392 ErrorList & error_list = d->errorLists[error_type];
2393 string const ext = formats.extension(format);
2394 FileName const tmp_result_file(changeExtension(filename, ext));
2395 bool const success = theConverters().convert(this, FileName(filename),
2396 tmp_result_file, FileName(absFileName()), backend_format, format,
2398 // Emit the signal to show the error list.
2399 if (format != backend_format)
2404 if (put_in_tempdir) {
2405 result_file = tmp_result_file.absFilename();
2409 result_file = changeExtension(absFileName(), ext);
2410 // We need to copy referenced files (e. g. included graphics
2411 // if format == "dvi") to the result dir.
2412 vector<ExportedFile> const files =
2413 runparams.exportdata->externalFiles(format);
2414 string const dest = onlyPath(result_file);
2415 CopyStatus status = SUCCESS;
2416 for (vector<ExportedFile>::const_iterator it = files.begin();
2417 it != files.end() && status != CANCEL; ++it) {
2418 string const fmt = formats.getFormatFromFile(it->sourceName);
2419 status = copyFile(fmt, it->sourceName,
2420 makeAbsPath(it->exportName, dest),
2421 it->exportName, status == FORCE);
2423 if (status == CANCEL) {
2424 message(_("Document export cancelled."));
2425 } else if (tmp_result_file.exists()) {
2426 // Finally copy the main file
2427 status = copyFile(format, tmp_result_file,
2428 FileName(result_file), result_file,
2430 message(bformat(_("Document exported as %1$s "
2432 formats.prettyName(format),
2433 makeDisplayPath(result_file)));
2435 // This must be a dummy converter like fax (bug 1888)
2436 message(bformat(_("Document exported as %1$s"),
2437 formats.prettyName(format)));
2444 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2447 return doExport(format, put_in_tempdir, result_file);
2451 bool Buffer::preview(string const & format) const
2454 if (!doExport(format, true, result_file))
2456 return formats.view(*this, FileName(result_file), format);
2460 bool Buffer::isExportable(string const & format) const
2462 vector<string> backs = backends();
2463 for (vector<string>::const_iterator it = backs.begin();
2464 it != backs.end(); ++it)
2465 if (theConverters().isReachable(*it, format))
2471 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2473 vector<string> backs = backends();
2474 vector<Format const *> result =
2475 theConverters().getReachable(backs[0], only_viewable, true);
2476 for (vector<string>::const_iterator it = backs.begin() + 1;
2477 it != backs.end(); ++it) {
2478 vector<Format const *> r =
2479 theConverters().getReachable(*it, only_viewable, false);
2480 result.insert(result.end(), r.begin(), r.end());
2486 vector<string> Buffer::backends() const
2489 if (params().baseClass()->isTeXClassAvailable()) {
2490 v.push_back(bufferFormat());
2491 // FIXME: Don't hardcode format names here, but use a flag
2492 if (v.back() == "latex")
2493 v.push_back("pdflatex");
2495 v.push_back("text");
2501 bool Buffer::readFileHelper(FileName const & s)
2503 // File information about normal file
2505 docstring const file = makeDisplayPath(s.absFilename(), 50);
2506 docstring text = bformat(_("The specified document\n%1$s"
2507 "\ncould not be read."), file);
2508 Alert::error(_("Could not read document"), text);
2512 // Check if emergency save file exists and is newer.
2513 FileName const e(s.absFilename() + ".emergency");
2515 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2516 docstring const file = makeDisplayPath(s.absFilename(), 20);
2517 docstring const text =
2518 bformat(_("An emergency save of the document "
2520 "Recover emergency save?"), file);
2521 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2522 _("&Recover"), _("&Load Original"),
2526 // the file is not saved if we load the emergency file.
2536 // Now check if autosave file is newer.
2537 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2539 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2540 docstring const file = makeDisplayPath(s.absFilename(), 20);
2541 docstring const text =
2542 bformat(_("The backup of the document "
2543 "%1$s is newer.\n\nLoad the "
2544 "backup instead?"), file);
2545 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2546 _("&Load backup"), _("Load &original"),
2550 // the file is not saved if we load the autosave file.
2554 // Here we delete the autosave
2565 bool Buffer::loadLyXFile(FileName const & s)
2567 if (s.isReadableFile()) {
2568 if (readFileHelper(s)) {
2569 lyxvc().file_found_hook(s);
2570 if (!s.isWritable())
2575 docstring const file = makeDisplayPath(s.absFilename(), 20);
2576 // Here we probably should run
2577 if (LyXVC::file_not_found_hook(s)) {
2578 docstring const text =
2579 bformat(_("Do you want to retrieve the document"
2580 " %1$s from version control?"), file);
2581 int const ret = Alert::prompt(_("Retrieve from version control?"),
2582 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2585 // How can we know _how_ to do the checkout?
2586 // With the current VC support it has to be,
2587 // a RCS file since CVS do not have special ,v files.
2589 return loadLyXFile(s);
2597 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2599 TeXErrors::Errors::const_iterator cit = terr.begin();
2600 TeXErrors::Errors::const_iterator end = terr.end();
2602 for (; cit != end; ++cit) {
2605 int errorRow = cit->error_in_line;
2606 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2612 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2613 } while (found && id_start == id_end && pos_start == pos_end);
2615 errorList.push_back(ErrorItem(cit->error_desc,
2616 cit->error_text, id_start, pos_start, pos_end));