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 & Buffer::texrow()
383 TexRow const & Buffer::texrow() const
389 TocBackend & Buffer::tocBackend() const
391 return d->toc_backend;
395 Undo & Buffer::undo()
401 string Buffer::latexName(bool const no_path) const
403 FileName latex_name = makeLatexName(d->filename);
404 return no_path ? latex_name.onlyFileName()
405 : latex_name.absFilename();
409 string Buffer::logName(LogType * type) const
411 string const filename = latexName(false);
413 if (filename.empty()) {
419 string const path = temppath();
421 FileName const fname(addName(temppath(),
422 onlyFilename(changeExtension(filename,
424 FileName const bname(
425 addName(path, onlyFilename(
426 changeExtension(filename,
427 formats.extension("literate") + ".out"))));
429 // If no Latex log or Build log is newer, show Build log
431 if (bname.exists() &&
432 (!fname.exists() || fname.lastModified() < bname.lastModified())) {
433 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
436 return bname.absFilename();
438 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
441 return fname.absFilename();
445 void Buffer::setReadonly(bool const flag)
447 if (d->read_only != flag) {
454 void Buffer::setFileName(string const & newfile)
456 d->filename = makeAbsPath(newfile);
457 setReadonly(d->filename.isReadOnly());
462 int Buffer::readHeader(Lexer & lex)
464 int unknown_tokens = 0;
466 int begin_header_line = -1;
468 // Initialize parameters that may be/go lacking in header:
469 params().branchlist().clear();
470 params().preamble.erase();
471 params().options.erase();
472 params().master.erase();
473 params().float_placement.erase();
474 params().paperwidth.erase();
475 params().paperheight.erase();
476 params().leftmargin.erase();
477 params().rightmargin.erase();
478 params().topmargin.erase();
479 params().bottommargin.erase();
480 params().headheight.erase();
481 params().headsep.erase();
482 params().footskip.erase();
483 params().columnsep.erase();
484 params().fontsCJK.erase();
485 params().listings_params.clear();
486 params().clearLayoutModules();
487 params().clearRemovedModules();
488 params().pdfoptions().clear();
490 for (int i = 0; i < 4; ++i) {
491 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
492 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
495 ErrorList & errorList = d->errorLists["Parse"];
504 if (token == "\\end_header")
508 if (token == "\\begin_header") {
509 begin_header_line = line;
513 LYXERR(Debug::PARSER, "Handling document header token: `"
516 string unknown = params().readToken(lex, token, d->filename.onlyPath());
517 if (!unknown.empty()) {
518 if (unknown[0] != '\\' && token == "\\textclass") {
519 Alert::warning(_("Unknown document class"),
520 bformat(_("Using the default document class, because the "
521 "class %1$s is unknown."), from_utf8(unknown)));
524 docstring const s = bformat(_("Unknown token: "
528 errorList.push_back(ErrorItem(_("Document header error"),
533 if (begin_header_line) {
534 docstring const s = _("\\begin_header is missing");
535 errorList.push_back(ErrorItem(_("Document header error"),
539 params().makeDocumentClass();
541 return unknown_tokens;
546 // changed to be public and have one parameter
547 // Returns false if "\end_document" is not read (Asger)
548 bool Buffer::readDocument(Lexer & lex)
550 ErrorList & errorList = d->errorLists["Parse"];
553 if (!lex.checkFor("\\begin_document")) {
554 docstring const s = _("\\begin_document is missing");
555 errorList.push_back(ErrorItem(_("Document header error"),
559 // we are reading in a brand new document
560 LASSERT(paragraphs().empty(), /**/);
564 if (params().outputChanges) {
565 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
566 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
567 LaTeXFeatures::isAvailable("xcolor");
569 if (!dvipost && !xcolorsoul) {
570 Alert::warning(_("Changes not shown in LaTeX output"),
571 _("Changes will not be highlighted in LaTeX output, "
572 "because neither dvipost nor xcolor/soul are installed.\n"
573 "Please install these packages or redefine "
574 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
575 } else if (!xcolorsoul) {
576 Alert::warning(_("Changes not shown in LaTeX output"),
577 _("Changes will not be highlighted in LaTeX output "
578 "when using pdflatex, because xcolor and soul are not installed.\n"
579 "Please install both packages or redefine "
580 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
584 if (!params().master.empty()) {
585 FileName const master_file = makeAbsPath(params().master,
586 onlyPath(absFileName()));
587 if (isLyXFilename(master_file.absFilename())) {
588 Buffer * master = checkAndLoadLyXFile(master_file);
589 d->parent_buffer = master;
594 bool const res = text().read(*this, lex, errorList, d->inset);
597 updateMacroInstances();
602 // needed to insert the selection
603 void Buffer::insertStringAsLines(ParagraphList & pars,
604 pit_type & pit, pos_type & pos,
605 Font const & fn, docstring const & str, bool autobreakrows)
609 // insert the string, don't insert doublespace
610 bool space_inserted = true;
611 for (docstring::const_iterator cit = str.begin();
612 cit != str.end(); ++cit) {
613 Paragraph & par = pars[pit];
615 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
616 breakParagraph(params(), pars, pit, pos,
617 par.layout().isEnvironment());
620 space_inserted = true;
624 // do not insert consecutive spaces if !free_spacing
625 } else if ((*cit == ' ' || *cit == '\t') &&
626 space_inserted && !par.isFreeSpacing()) {
628 } else if (*cit == '\t') {
629 if (!par.isFreeSpacing()) {
630 // tabs are like spaces here
631 par.insertChar(pos, ' ', font, params().trackChanges);
633 space_inserted = true;
635 par.insertChar(pos, *cit, font, params().trackChanges);
637 space_inserted = true;
639 } else if (!isPrintable(*cit)) {
640 // Ignore unprintables
643 // just insert the character
644 par.insertChar(pos, *cit, font, params().trackChanges);
646 space_inserted = (*cit == ' ');
653 bool Buffer::readString(string const & s)
655 params().compressed = false;
657 // remove dummy empty par
658 paragraphs().clear();
662 FileName const name = FileName::tempName("Buffer_readString");
663 switch (readFile(lex, name, true)) {
667 // We need to call lyx2lyx, so write the input to a file
668 ofstream os(name.toFilesystemEncoding().c_str());
671 return readFile(name);
681 bool Buffer::readFile(FileName const & filename)
683 FileName fname(filename);
685 // remove dummy empty par
686 paragraphs().clear();
689 if (readFile(lex, fname) != success)
696 bool Buffer::isFullyLoaded() const
698 return d->file_fully_loaded;
702 void Buffer::setFullyLoaded(bool value)
704 d->file_fully_loaded = value;
708 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
711 LASSERT(!filename.empty(), /**/);
713 // the first (non-comment) token _must_ be...
714 if (!lex.checkFor("\\lyxformat")) {
715 Alert::error(_("Document format failure"),
716 bformat(_("%1$s is not a readable LyX document."),
717 from_utf8(filename.absFilename())));
723 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
724 // if present remove ".," from string.
725 size_t dot = tmp_format.find_first_of(".,");
726 //lyxerr << " dot found at " << dot << endl;
727 if (dot != string::npos)
728 tmp_format.erase(dot, 1);
729 int const file_format = convert<int>(tmp_format);
730 //lyxerr << "format: " << file_format << endl;
732 // save timestamp and checksum of the original disk file, making sure
733 // to not overwrite them with those of the file created in the tempdir
734 // when it has to be converted to the current format.
736 // Save the timestamp and checksum of disk file. If filename is an
737 // emergency file, save the timestamp and checksum of the original lyx file
738 // because isExternallyModified will check for this file. (BUG4193)
739 string diskfile = filename.absFilename();
740 if (suffixIs(diskfile, ".emergency"))
741 diskfile = diskfile.substr(0, diskfile.size() - 10);
742 saveCheckSum(FileName(diskfile));
745 if (file_format != LYX_FORMAT) {
748 // lyx2lyx would fail
751 FileName const tmpfile = FileName::tempName("Buffer_readFile");
752 if (tmpfile.empty()) {
753 Alert::error(_("Conversion failed"),
754 bformat(_("%1$s is from a different"
755 " version of LyX, but a temporary"
756 " file for converting it could"
758 from_utf8(filename.absFilename())));
761 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
762 if (lyx2lyx.empty()) {
763 Alert::error(_("Conversion script not found"),
764 bformat(_("%1$s is from a different"
765 " version of LyX, but the"
766 " conversion script lyx2lyx"
767 " could not be found."),
768 from_utf8(filename.absFilename())));
771 ostringstream command;
772 command << os::python()
773 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
774 << " -t " << convert<string>(LYX_FORMAT)
775 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
776 << ' ' << quoteName(filename.toFilesystemEncoding());
777 string const command_str = command.str();
779 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
781 cmd_ret const ret = runCommand(command_str);
782 if (ret.first != 0) {
783 Alert::error(_("Conversion script failed"),
784 bformat(_("%1$s is from a different version"
785 " of LyX, but the lyx2lyx script"
786 " failed to convert it."),
787 from_utf8(filename.absFilename())));
790 bool const ret = readFile(tmpfile);
791 // Do stuff with tmpfile name and buffer name here.
792 return ret ? success : failure;
797 if (readDocument(lex)) {
798 Alert::error(_("Document format failure"),
799 bformat(_("%1$s ended unexpectedly, which means"
800 " that it is probably corrupted."),
801 from_utf8(filename.absFilename())));
804 d->file_fully_loaded = true;
809 // Should probably be moved to somewhere else: BufferView? LyXView?
810 bool Buffer::save() const
812 // We don't need autosaves in the immediate future. (Asger)
813 resetAutosaveTimers();
815 string const encodedFilename = d->filename.toFilesystemEncoding();
818 bool madeBackup = false;
820 // make a backup if the file already exists
821 if (lyxrc.make_backup && fileName().exists()) {
822 backupName = FileName(absFileName() + '~');
823 if (!lyxrc.backupdir_path.empty()) {
824 string const mangledName =
825 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
826 backupName = FileName(addName(lyxrc.backupdir_path,
829 if (fileName().copyTo(backupName)) {
832 Alert::error(_("Backup failure"),
833 bformat(_("Cannot create backup file %1$s.\n"
834 "Please check whether the directory exists and is writeable."),
835 from_utf8(backupName.absFilename())));
836 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
840 // ask if the disk file has been externally modified (use checksum method)
841 if (fileName().exists() && isExternallyModified(checksum_method)) {
842 docstring const file = makeDisplayPath(absFileName(), 20);
843 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
844 "you want to overwrite this file?"), file);
845 int const ret = Alert::prompt(_("Overwrite modified file?"),
846 text, 1, 1, _("&Overwrite"), _("&Cancel"));
851 if (writeFile(d->filename)) {
855 // Saving failed, so backup is not backup
857 backupName.moveTo(d->filename);
863 bool Buffer::writeFile(FileName const & fname) const
865 if (d->read_only && fname == d->filename)
870 docstring const str = bformat(_("Saving document %1$s..."),
871 makeDisplayPath(fname.absFilename()));
874 if (params().compressed) {
875 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
876 retval = ofs && write(ofs);
878 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
879 retval = ofs && write(ofs);
883 message(str + _(" could not write file!"));
887 removeAutosaveFile(d->filename.absFilename());
889 saveCheckSum(d->filename);
890 message(str + _(" done."));
896 bool Buffer::write(ostream & ofs) const
899 // Use the standard "C" locale for file output.
900 ofs.imbue(locale::classic());
903 // The top of the file should not be written by params().
905 // write out a comment in the top of the file
906 ofs << "#LyX " << lyx_version
907 << " created this file. For more info see http://www.lyx.org/\n"
908 << "\\lyxformat " << LYX_FORMAT << "\n"
909 << "\\begin_document\n";
911 /// For each author, set 'used' to true if there is a change
912 /// by this author in the document; otherwise set it to 'false'.
913 AuthorList::Authors::const_iterator a_it = params().authors().begin();
914 AuthorList::Authors::const_iterator a_end = params().authors().end();
915 for (; a_it != a_end; ++a_it)
916 a_it->second.setUsed(false);
918 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
919 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
920 for ( ; it != end; ++it)
921 it->checkAuthors(params().authors());
923 // now write out the buffer parameters.
924 ofs << "\\begin_header\n";
925 params().writeFile(ofs);
926 ofs << "\\end_header\n";
929 ofs << "\n\\begin_body\n";
930 text().write(*this, ofs);
931 ofs << "\n\\end_body\n";
933 // Write marker that shows file is complete
934 ofs << "\\end_document" << endl;
936 // Shouldn't really be needed....
939 // how to check if close went ok?
940 // Following is an attempt... (BE 20001011)
942 // good() returns false if any error occured, including some
944 // bad() returns true if something bad happened in the buffer,
945 // which should include file system full errors.
950 lyxerr << "File was not closed properly." << endl;
957 bool Buffer::makeLaTeXFile(FileName const & fname,
958 string const & original_path,
959 OutputParams const & runparams,
960 bool output_preamble, bool output_body) const
962 string const encoding = runparams.encoding->iconvName();
963 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
966 try { ofs.reset(encoding); }
967 catch (iconv_codecvt_facet_exception & e) {
968 lyxerr << "Caught iconv exception: " << e.what() << endl;
969 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
970 "verify that the support software for your encoding (%1$s) is "
971 "properly installed"), from_ascii(encoding)));
974 if (!openFileWrite(ofs, fname))
977 //TexStream ts(ofs.rdbuf(), &texrow());
978 ErrorList & errorList = d->errorLists["Export"];
980 bool failed_export = false;
983 writeLaTeXSource(ofs, original_path,
984 runparams, output_preamble, output_body);
986 catch (EncodingException & e) {
987 odocstringstream ods;
988 ods.put(e.failed_char);
990 oss << "0x" << hex << e.failed_char << dec;
991 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
992 " (code point %2$s)"),
993 ods.str(), from_utf8(oss.str()));
994 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
995 "representable in the chosen encoding.\n"
996 "Changing the document encoding to utf8 could help."),
997 e.par_id, e.pos, e.pos + 1));
998 failed_export = true;
1000 catch (iconv_codecvt_facet_exception & e) {
1001 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1002 _(e.what()), -1, 0, 0));
1003 failed_export = true;
1005 catch (exception const & e) {
1006 errorList.push_back(ErrorItem(_("conversion failed"),
1007 _(e.what()), -1, 0, 0));
1008 failed_export = true;
1011 lyxerr << "Caught some really weird exception..." << endl;
1017 failed_export = true;
1018 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1022 return !failed_export;
1026 void Buffer::writeLaTeXSource(odocstream & os,
1027 string const & original_path,
1028 OutputParams const & runparams_in,
1029 bool const output_preamble, bool const output_body) const
1031 // The child documents, if any, shall be already loaded at this point.
1033 OutputParams runparams = runparams_in;
1035 // Classify the unicode characters appearing in math insets
1036 Encodings::initUnicodeMath(*this);
1038 // validate the buffer.
1039 LYXERR(Debug::LATEX, " Validating buffer...");
1040 LaTeXFeatures features(*this, params(), runparams);
1042 LYXERR(Debug::LATEX, " Buffer validation done.");
1044 // The starting paragraph of the coming rows is the
1045 // first paragraph of the document. (Asger)
1046 if (output_preamble && runparams.nice) {
1047 os << "%% LyX " << lyx_version << " created this file. "
1048 "For more info, see http://www.lyx.org/.\n"
1049 "%% Do not edit unless you really know what "
1051 d->texrow.newline();
1052 d->texrow.newline();
1054 LYXERR(Debug::INFO, "lyx document header finished");
1056 // Don't move this behind the parent_buffer=0 code below,
1057 // because then the macros will not get the right "redefinition"
1058 // flag as they don't see the parent macros which are output before.
1061 // fold macros if possible, still with parent buffer as the
1062 // macros will be put in the prefix anyway.
1063 updateMacroInstances();
1065 // There are a few differences between nice LaTeX and usual files:
1066 // usual is \batchmode and has a
1067 // special input@path to allow the including of figures
1068 // with either \input or \includegraphics (what figinsets do).
1069 // input@path is set when the actual parameter
1070 // original_path is set. This is done for usual tex-file, but not
1071 // for nice-latex-file. (Matthias 250696)
1072 // Note that input@path is only needed for something the user does
1073 // in the preamble, included .tex files or ERT, files included by
1074 // LyX work without it.
1075 if (output_preamble) {
1076 if (!runparams.nice) {
1077 // code for usual, NOT nice-latex-file
1078 os << "\\batchmode\n"; // changed
1079 // from \nonstopmode
1080 d->texrow.newline();
1082 if (!original_path.empty()) {
1084 // We don't know the encoding of inputpath
1085 docstring const inputpath = from_utf8(latex_path(original_path));
1086 os << "\\makeatletter\n"
1087 << "\\def\\input@path{{"
1088 << inputpath << "/}}\n"
1089 << "\\makeatother\n";
1090 d->texrow.newline();
1091 d->texrow.newline();
1092 d->texrow.newline();
1095 // get parent macros (if this buffer has a parent) which will be
1096 // written at the document begin further down.
1097 MacroSet parentMacros;
1098 listParentMacros(parentMacros, features);
1100 // Write the preamble
1101 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1103 runparams.use_japanese = features.isRequired("japanese");
1109 os << "\\begin{document}\n";
1110 d->texrow.newline();
1112 // output the parent macros
1113 MacroSet::iterator it = parentMacros.begin();
1114 MacroSet::iterator end = parentMacros.end();
1115 for (; it != end; ++it)
1116 (*it)->write(os, true);
1117 } // output_preamble
1119 d->texrow.start(paragraphs().begin()->id(), 0);
1121 LYXERR(Debug::INFO, "preamble finished, now the body.");
1123 // if we are doing a real file with body, even if this is the
1124 // child of some other buffer, let's cut the link here.
1125 // This happens for example if only a child document is printed.
1126 Buffer const * save_parent = 0;
1127 if (output_preamble) {
1128 save_parent = d->parent_buffer;
1129 d->parent_buffer = 0;
1133 latexParagraphs(*this, text(), os, d->texrow, runparams);
1135 // Restore the parenthood if needed
1136 if (output_preamble)
1137 d->parent_buffer = save_parent;
1139 // add this just in case after all the paragraphs
1141 d->texrow.newline();
1143 if (output_preamble) {
1144 os << "\\end{document}\n";
1145 d->texrow.newline();
1146 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1148 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1150 runparams_in.encoding = runparams.encoding;
1152 // Just to be sure. (Asger)
1153 d->texrow.newline();
1155 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1156 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1160 bool Buffer::isLatex() const
1162 return params().documentClass().outputType() == LATEX;
1166 bool Buffer::isLiterate() const
1168 return params().documentClass().outputType() == LITERATE;
1172 bool Buffer::isDocBook() const
1174 return params().documentClass().outputType() == DOCBOOK;
1178 void Buffer::makeDocBookFile(FileName const & fname,
1179 OutputParams const & runparams,
1180 bool const body_only) const
1182 LYXERR(Debug::LATEX, "makeDocBookFile...");
1185 if (!openFileWrite(ofs, fname))
1188 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1192 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1196 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1197 OutputParams const & runparams,
1198 bool const only_body) const
1200 LaTeXFeatures features(*this, params(), runparams);
1205 DocumentClass const & tclass = params().documentClass();
1206 string const top_element = tclass.latexname();
1209 if (runparams.flavor == OutputParams::XML)
1210 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1213 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1216 if (! tclass.class_header().empty())
1217 os << from_ascii(tclass.class_header());
1218 else if (runparams.flavor == OutputParams::XML)
1219 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1220 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1222 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1224 docstring preamble = from_utf8(params().preamble);
1225 if (runparams.flavor != OutputParams::XML ) {
1226 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1227 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1228 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1229 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1232 string const name = runparams.nice
1233 ? changeExtension(absFileName(), ".sgml") : fname;
1234 preamble += features.getIncludedFiles(name);
1235 preamble += features.getLyXSGMLEntities();
1237 if (!preamble.empty()) {
1238 os << "\n [ " << preamble << " ]";
1243 string top = top_element;
1245 if (runparams.flavor == OutputParams::XML)
1246 top += params().language->code();
1248 top += params().language->code().substr(0, 2);
1251 if (!params().options.empty()) {
1253 top += params().options;
1256 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1257 << " file was created by LyX " << lyx_version
1258 << "\n See http://www.lyx.org/ for more information -->\n";
1260 params().documentClass().counters().reset();
1264 sgml::openTag(os, top);
1266 docbookParagraphs(paragraphs(), *this, os, runparams);
1267 sgml::closeTag(os, top_element);
1271 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1272 // Other flags: -wall -v0 -x
1273 int Buffer::runChktex()
1277 // get LaTeX-Filename
1278 FileName const path(temppath());
1279 string const name = addName(path.absFilename(), latexName());
1280 string const org_path = filePath();
1282 PathChanger p(path); // path to LaTeX file
1283 message(_("Running chktex..."));
1285 // Generate the LaTeX file if neccessary
1286 OutputParams runparams(¶ms().encoding());
1287 runparams.flavor = OutputParams::LATEX;
1288 runparams.nice = false;
1289 makeLaTeXFile(FileName(name), org_path, runparams);
1292 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1293 int const res = chktex.run(terr); // run chktex
1296 Alert::error(_("chktex failure"),
1297 _("Could not run chktex successfully."));
1298 } else if (res > 0) {
1299 ErrorList & errlist = d->errorLists["ChkTeX"];
1301 bufferErrors(terr, errlist);
1312 void Buffer::validate(LaTeXFeatures & features) const
1314 params().validate(features);
1318 for_each(paragraphs().begin(), paragraphs().end(),
1319 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1321 if (lyxerr.debugging(Debug::LATEX)) {
1322 features.showStruct();
1327 void Buffer::getLabelList(vector<docstring> & list) const
1329 // If this is a child document, use the parent's list instead.
1330 if (d->parent_buffer) {
1331 d->parent_buffer->getLabelList(list);
1336 Toc & toc = d->toc_backend.toc("label");
1337 TocIterator toc_it = toc.begin();
1338 TocIterator end = toc.end();
1339 for (; toc_it != end; ++toc_it) {
1340 if (toc_it->depth() == 0)
1341 list.push_back(toc_it->str());
1346 void Buffer::updateBibfilesCache() const
1348 // If this is a child document, use the parent's cache instead.
1349 if (d->parent_buffer) {
1350 d->parent_buffer->updateBibfilesCache();
1354 d->bibfilesCache_.clear();
1355 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1356 if (it->lyxCode() == BIBTEX_CODE) {
1357 InsetBibtex const & inset =
1358 static_cast<InsetBibtex const &>(*it);
1359 support::FileNameList const bibfiles = inset.getBibFiles();
1360 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1363 } else if (it->lyxCode() == INCLUDE_CODE) {
1364 InsetInclude & inset =
1365 static_cast<InsetInclude &>(*it);
1366 inset.updateBibfilesCache();
1367 support::FileNameList const & bibfiles =
1368 inset.getBibfilesCache(*this);
1369 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1374 // the bibinfo cache is now invalid
1375 d->bibinfoCacheValid_ = false;
1379 void Buffer::invalidateBibinfoCache()
1381 d->bibinfoCacheValid_ = false;
1385 support::FileNameList const & Buffer::getBibfilesCache() const
1387 // If this is a child document, use the parent's cache instead.
1388 if (d->parent_buffer)
1389 return d->parent_buffer->getBibfilesCache();
1391 // We update the cache when first used instead of at loading time.
1392 if (d->bibfilesCache_.empty())
1393 const_cast<Buffer *>(this)->updateBibfilesCache();
1395 return d->bibfilesCache_;
1399 BiblioInfo const & Buffer::masterBibInfo() const
1401 // if this is a child document and the parent is already loaded
1402 // use the parent's list instead [ale990412]
1403 Buffer const * const tmp = masterBuffer();
1406 return tmp->masterBibInfo();
1407 return localBibInfo();
1411 BiblioInfo const & Buffer::localBibInfo() const
1413 if (d->bibinfoCacheValid_) {
1414 support::FileNameList const & bibfilesCache = getBibfilesCache();
1415 // compare the cached timestamps with the actual ones.
1416 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1417 support::FileNameList::const_iterator en = bibfilesCache.end();
1418 for (; ei != en; ++ ei) {
1419 time_t lastw = ei->lastModified();
1420 if (lastw != d->bibfileStatus_[*ei]) {
1421 d->bibinfoCacheValid_ = false;
1422 d->bibfileStatus_[*ei] = lastw;
1428 if (!d->bibinfoCacheValid_) {
1429 d->bibinfo_.clear();
1430 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1431 it->fillWithBibKeys(d->bibinfo_, it);
1432 d->bibinfoCacheValid_ = true;
1438 bool Buffer::isDepClean(string const & name) const
1440 DepClean::const_iterator const it = d->dep_clean.find(name);
1441 if (it == d->dep_clean.end())
1447 void Buffer::markDepClean(string const & name)
1449 d->dep_clean[name] = true;
1453 bool Buffer::dispatch(string const & command, bool * result)
1455 return dispatch(lyxaction.lookupFunc(command), result);
1459 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1461 bool dispatched = true;
1463 switch (func.action) {
1464 case LFUN_BUFFER_EXPORT: {
1465 bool const tmp = doExport(to_utf8(func.argument()), false);
1471 case LFUN_BRANCH_ACTIVATE:
1472 case LFUN_BRANCH_DEACTIVATE: {
1473 BranchList & branchList = params().branchlist();
1474 docstring const branchName = func.argument();
1475 Branch * branch = branchList.find(branchName);
1477 LYXERR0("Branch " << branchName << " does not exist.");
1479 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1491 void Buffer::changeLanguage(Language const * from, Language const * to)
1493 LASSERT(from, /**/);
1496 for_each(par_iterator_begin(),
1498 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1502 bool Buffer::isMultiLingual() const
1504 ParConstIterator end = par_iterator_end();
1505 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1506 if (it->isMultiLingual(params()))
1513 DocIterator Buffer::getParFromID(int const id) const
1516 // John says this is called with id == -1 from undo
1517 lyxerr << "getParFromID(), id: " << id << endl;
1518 return doc_iterator_end(inset());
1521 for (DocIterator it = doc_iterator_begin(inset()); !it.atEnd(); it.forwardPar())
1522 if (it.paragraph().id() == id)
1525 return doc_iterator_end(inset());
1529 bool Buffer::hasParWithID(int const id) const
1531 return !getParFromID(id).atEnd();
1535 ParIterator Buffer::par_iterator_begin()
1537 return ParIterator(doc_iterator_begin(inset()));
1541 ParIterator Buffer::par_iterator_end()
1543 return ParIterator(doc_iterator_end(inset()));
1547 ParConstIterator Buffer::par_iterator_begin() const
1549 return lyx::par_const_iterator_begin(inset());
1553 ParConstIterator Buffer::par_iterator_end() const
1555 return lyx::par_const_iterator_end(inset());
1559 Language const * Buffer::language() const
1561 return params().language;
1565 docstring const Buffer::B_(string const & l10n) const
1567 return params().B_(l10n);
1571 bool Buffer::isClean() const
1573 return d->lyx_clean;
1577 bool Buffer::isBakClean() const
1579 return d->bak_clean;
1583 bool Buffer::isExternallyModified(CheckMethod method) const
1585 LASSERT(d->filename.exists(), /**/);
1586 // if method == timestamp, check timestamp before checksum
1587 return (method == checksum_method
1588 || d->timestamp_ != d->filename.lastModified())
1589 && d->checksum_ != d->filename.checksum();
1593 void Buffer::saveCheckSum(FileName const & file) const
1595 if (file.exists()) {
1596 d->timestamp_ = file.lastModified();
1597 d->checksum_ = file.checksum();
1599 // in the case of save to a new file.
1606 void Buffer::markClean() const
1608 if (!d->lyx_clean) {
1609 d->lyx_clean = true;
1612 // if the .lyx file has been saved, we don't need an
1614 d->bak_clean = true;
1618 void Buffer::markBakClean() const
1620 d->bak_clean = true;
1624 void Buffer::setUnnamed(bool flag)
1630 bool Buffer::isUnnamed() const
1636 // FIXME: this function should be moved to buffer_pimpl.C
1637 void Buffer::markDirty()
1640 d->lyx_clean = false;
1643 d->bak_clean = false;
1645 DepClean::iterator it = d->dep_clean.begin();
1646 DepClean::const_iterator const end = d->dep_clean.end();
1648 for (; it != end; ++it)
1653 FileName Buffer::fileName() const
1659 string Buffer::absFileName() const
1661 return d->filename.absFilename();
1665 string Buffer::filePath() const
1667 return d->filename.onlyPath().absFilename() + "/";
1671 bool Buffer::isReadonly() const
1673 return d->read_only;
1677 void Buffer::setParent(Buffer const * buffer)
1679 // Avoids recursive include.
1680 d->parent_buffer = buffer == this ? 0 : buffer;
1685 Buffer const * Buffer::parent()
1687 return d->parent_buffer;
1691 Buffer const * Buffer::masterBuffer() const
1693 if (!d->parent_buffer)
1696 return d->parent_buffer->masterBuffer();
1700 bool Buffer::isChild(Buffer * child) const
1702 return d->children_positions.find(child) != d->children_positions.end();
1706 template<typename M>
1707 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
1712 typename M::iterator it = m.lower_bound(x);
1713 if (it == m.begin())
1721 MacroData const * Buffer::getBufferMacro(docstring const & name,
1722 DocIterator const & pos) const
1724 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
1726 // if paragraphs have no macro context set, pos will be empty
1730 // we haven't found anything yet
1731 DocIterator bestPos = par_iterator_begin();
1732 MacroData const * bestData = 0;
1734 // find macro definitions for name
1735 Impl::NamePositionScopeMacroMap::iterator nameIt
1736 = d->macros.find(name);
1737 if (nameIt != d->macros.end()) {
1738 // find last definition in front of pos or at pos itself
1739 Impl::PositionScopeMacroMap::const_iterator it
1740 = greatest_below(nameIt->second, pos);
1741 if (it != nameIt->second.end()) {
1743 // scope ends behind pos?
1744 if (pos < it->second.first) {
1745 // Looks good, remember this. If there
1746 // is no external macro behind this,
1747 // we found the right one already.
1748 bestPos = it->first;
1749 bestData = &it->second.second;
1753 // try previous macro if there is one
1754 if (it == nameIt->second.begin())
1761 // find macros in included files
1762 Impl::PositionScopeBufferMap::const_iterator it
1763 = greatest_below(d->position_to_children, pos);
1764 if (it == d->position_to_children.end())
1765 // no children before
1769 // do we know something better (i.e. later) already?
1770 if (it->first < bestPos )
1773 // scope ends behind pos?
1774 if (pos < it->second.first) {
1775 // look for macro in external file
1776 d->macro_lock = true;
1777 MacroData const * data
1778 = it->second.second->getMacro(name, false);
1779 d->macro_lock = false;
1781 bestPos = it->first;
1787 // try previous file if there is one
1788 if (it == d->position_to_children.begin())
1793 // return the best macro we have found
1798 MacroData const * Buffer::getMacro(docstring const & name,
1799 DocIterator const & pos, bool global) const
1804 // query buffer macros
1805 MacroData const * data = getBufferMacro(name, pos);
1809 // If there is a master buffer, query that
1810 if (d->parent_buffer) {
1811 d->macro_lock = true;
1812 MacroData const * macro = d->parent_buffer->getMacro(
1813 name, *this, false);
1814 d->macro_lock = false;
1820 data = MacroTable::globalMacros().get(name);
1829 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
1831 // set scope end behind the last paragraph
1832 DocIterator scope = par_iterator_begin();
1833 scope.pit() = scope.lastpit() + 1;
1835 return getMacro(name, scope, global);
1839 MacroData const * Buffer::getMacro(docstring const & name,
1840 Buffer const & child, bool global) const
1842 // look where the child buffer is included first
1843 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
1844 if (it == d->children_positions.end())
1847 // check for macros at the inclusion position
1848 return getMacro(name, it->second, global);
1852 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
1854 pit_type lastpit = it.lastpit();
1856 // look for macros in each paragraph
1857 while (it.pit() <= lastpit) {
1858 Paragraph & par = it.paragraph();
1860 // iterate over the insets of the current paragraph
1861 InsetList const & insets = par.insetList();
1862 InsetList::const_iterator iit = insets.begin();
1863 InsetList::const_iterator end = insets.end();
1864 for (; iit != end; ++iit) {
1865 it.pos() = iit->pos;
1867 // is it a nested text inset?
1868 if (iit->inset->asInsetText()) {
1869 // Inset needs its own scope?
1870 InsetText const * itext
1871 = iit->inset->asInsetText();
1872 bool newScope = itext->isMacroScope();
1874 // scope which ends just behind the inset
1875 DocIterator insetScope = it;
1878 // collect macros in inset
1879 it.push_back(CursorSlice(*iit->inset));
1880 updateMacros(it, newScope ? insetScope : scope);
1885 // is it an external file?
1886 if (iit->inset->lyxCode() == INCLUDE_CODE) {
1887 // get buffer of external file
1888 InsetCommand const & inset
1889 = static_cast<InsetCommand const &>(*iit->inset);
1890 InsetCommandParams const & ip = inset.params();
1891 d->macro_lock = true;
1892 Buffer * child = loadIfNeeded(*this, ip);
1893 d->macro_lock = false;
1897 // register its position, but only when it is
1898 // included first in the buffer
1899 if (d->children_positions.find(child)
1900 == d->children_positions.end())
1901 d->children_positions[child] = it;
1903 // register child with its scope
1904 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
1908 if (iit->inset->lyxCode() != MATHMACRO_CODE)
1912 MathMacroTemplate & macroTemplate
1913 = static_cast<MathMacroTemplate &>(*iit->inset);
1914 MacroContext mc(*this, it);
1915 macroTemplate.updateToContext(mc);
1918 bool valid = macroTemplate.validMacro();
1919 // FIXME: Should be fixNameAndCheckIfValid() in fact,
1920 // then the BufferView's cursor will be invalid in
1921 // some cases which leads to crashes.
1926 d->macros[macroTemplate.name()][it] =
1927 Impl::ScopeMacro(scope, MacroData(*this, it));
1937 void Buffer::updateMacros() const
1942 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
1944 // start with empty table
1946 d->children_positions.clear();
1947 d->position_to_children.clear();
1949 // Iterate over buffer, starting with first paragraph
1950 // The scope must be bigger than any lookup DocIterator
1951 // later. For the global lookup, lastpit+1 is used, hence
1952 // we use lastpit+2 here.
1953 DocIterator it = par_iterator_begin();
1954 DocIterator outerScope = it;
1955 outerScope.pit() = outerScope.lastpit() + 2;
1956 updateMacros(it, outerScope);
1960 void Buffer::updateMacroInstances() const
1962 LYXERR(Debug::MACROS, "updateMacroInstances for "
1963 << d->filename.onlyFileName());
1964 DocIterator it = doc_iterator_begin(inset());
1965 DocIterator end = doc_iterator_end(inset());
1966 for (; it != end; it.forwardPos()) {
1967 // look for MathData cells in InsetMathNest insets
1968 Inset * inset = it.nextInset();
1972 InsetMath * minset = inset->asInsetMath();
1976 // update macro in all cells of the InsetMathNest
1977 DocIterator::idx_type n = minset->nargs();
1978 MacroContext mc = MacroContext(*this, it);
1979 for (DocIterator::idx_type i = 0; i < n; ++i) {
1980 MathData & data = minset->cell(i);
1981 data.updateMacros(0, mc);
1987 void Buffer::listMacroNames(MacroNameSet & macros) const
1992 d->macro_lock = true;
1994 // loop over macro names
1995 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
1996 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
1997 for (; nameIt != nameEnd; ++nameIt)
1998 macros.insert(nameIt->first);
2000 // loop over children
2001 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2002 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2003 for (; it != end; ++it)
2004 it->first->listMacroNames(macros);
2007 if (d->parent_buffer)
2008 d->parent_buffer->listMacroNames(macros);
2010 d->macro_lock = false;
2014 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2016 if (!d->parent_buffer)
2020 d->parent_buffer->listMacroNames(names);
2023 MacroNameSet::iterator it = names.begin();
2024 MacroNameSet::iterator end = names.end();
2025 for (; it != end; ++it) {
2027 MacroData const * data =
2028 d->parent_buffer->getMacro(*it, *this, false);
2030 macros.insert(data);
2032 // we cannot access the original MathMacroTemplate anymore
2033 // here to calls validate method. So we do its work here manually.
2034 // FIXME: somehow make the template accessible here.
2035 if (data->optionals() > 0)
2036 features.require("xargs");
2042 Buffer::References & Buffer::references(docstring const & label)
2044 if (d->parent_buffer)
2045 return const_cast<Buffer *>(masterBuffer())->references(label);
2047 RefCache::iterator it = d->ref_cache_.find(label);
2048 if (it != d->ref_cache_.end())
2049 return it->second.second;
2051 static InsetLabel const * dummy_il = 0;
2052 static References const dummy_refs;
2053 it = d->ref_cache_.insert(
2054 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2055 return it->second.second;
2059 Buffer::References const & Buffer::references(docstring const & label) const
2061 return const_cast<Buffer *>(this)->references(label);
2065 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2067 masterBuffer()->d->ref_cache_[label].first = il;
2071 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2073 return masterBuffer()->d->ref_cache_[label].first;
2077 void Buffer::clearReferenceCache() const
2079 if (!d->parent_buffer)
2080 d->ref_cache_.clear();
2084 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2087 //FIXME: This does not work for child documents yet.
2088 LASSERT(code == CITE_CODE, /**/);
2089 // Check if the label 'from' appears more than once
2090 vector<docstring> labels;
2092 BiblioInfo const & keys = masterBibInfo();
2093 BiblioInfo::const_iterator bit = keys.begin();
2094 BiblioInfo::const_iterator bend = keys.end();
2096 for (; bit != bend; ++bit)
2098 labels.push_back(bit->first);
2101 if (count(labels.begin(), labels.end(), from) > 1)
2104 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2105 if (it->lyxCode() == code) {
2106 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2107 docstring const oldValue = inset.getParam(paramName);
2108 if (oldValue == from)
2109 inset.setParam(paramName, to);
2115 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2116 pit_type par_end, bool full_source) const
2118 OutputParams runparams(¶ms().encoding());
2119 runparams.nice = true;
2120 runparams.flavor = OutputParams::LATEX;
2121 runparams.linelen = lyxrc.plaintext_linelen;
2122 // No side effect of file copying and image conversion
2123 runparams.dryrun = true;
2127 os << "% " << _("Preview source code") << "\n\n";
2128 d->texrow.newline();
2129 d->texrow.newline();
2131 writeDocBookSource(os, absFileName(), runparams, false);
2133 // latex or literate
2134 writeLaTeXSource(os, string(), runparams, true, true);
2136 runparams.par_begin = par_begin;
2137 runparams.par_end = par_end;
2138 if (par_begin + 1 == par_end) {
2140 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2144 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2145 convert<docstring>(par_begin),
2146 convert<docstring>(par_end - 1))
2149 d->texrow.newline();
2150 d->texrow.newline();
2151 // output paragraphs
2153 docbookParagraphs(paragraphs(), *this, os, runparams);
2155 // latex or literate
2156 latexParagraphs(*this, text(), os, d->texrow, runparams);
2161 ErrorList & Buffer::errorList(string const & type) const
2163 static ErrorList emptyErrorList;
2164 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2165 if (I == d->errorLists.end())
2166 return emptyErrorList;
2172 void Buffer::updateTocItem(std::string const & type,
2173 DocIterator const & dit) const
2176 gui_->updateTocItem(type, dit);
2180 void Buffer::structureChanged() const
2183 gui_->structureChanged();
2187 void Buffer::errors(string const & err) const
2194 void Buffer::message(docstring const & msg) const
2201 void Buffer::setBusy(bool on) const
2208 void Buffer::setReadOnly(bool on) const
2211 d->wa_->setReadOnly(on);
2215 void Buffer::updateTitles() const
2218 d->wa_->updateTitles();
2222 void Buffer::resetAutosaveTimers() const
2225 gui_->resetAutosaveTimers();
2229 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2238 class AutoSaveBuffer : public ForkedProcess {
2241 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2242 : buffer_(buffer), fname_(fname) {}
2244 virtual boost::shared_ptr<ForkedProcess> clone() const
2246 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2251 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2252 from_utf8(fname_.absFilename())));
2253 return run(DontWait);
2257 virtual int generateChild();
2259 Buffer const & buffer_;
2264 int AutoSaveBuffer::generateChild()
2266 // tmp_ret will be located (usually) in /tmp
2267 // will that be a problem?
2268 // Note that this calls ForkedCalls::fork(), so it's
2269 // ok cross-platform.
2270 pid_t const pid = fork();
2271 // If you want to debug the autosave
2272 // you should set pid to -1, and comment out the fork.
2273 if (pid != 0 && pid != -1)
2276 // pid = -1 signifies that lyx was unable
2277 // to fork. But we will do the save
2279 bool failed = false;
2280 FileName const tmp_ret = FileName::tempName("lyxauto");
2281 if (!tmp_ret.empty()) {
2282 buffer_.writeFile(tmp_ret);
2283 // assume successful write of tmp_ret
2284 if (!tmp_ret.moveTo(fname_))
2290 // failed to write/rename tmp_ret so try writing direct
2291 if (!buffer_.writeFile(fname_)) {
2292 // It is dangerous to do this in the child,
2293 // but safe in the parent, so...
2294 if (pid == -1) // emit message signal.
2295 buffer_.message(_("Autosave failed!"));
2299 if (pid == 0) // we are the child so...
2308 // Perfect target for a thread...
2309 void Buffer::autoSave() const
2311 if (isBakClean() || isReadonly()) {
2312 // We don't save now, but we'll try again later
2313 resetAutosaveTimers();
2317 // emit message signal.
2318 message(_("Autosaving current document..."));
2320 // create autosave filename
2321 string fname = filePath();
2323 fname += d->filename.onlyFileName();
2326 AutoSaveBuffer autosave(*this, FileName(fname));
2330 resetAutosaveTimers();
2334 string Buffer::bufferFormat() const
2340 if (params().encoding().package() == Encoding::japanese)
2346 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2347 string & result_file) const
2349 string backend_format;
2350 OutputParams runparams(¶ms().encoding());
2351 runparams.flavor = OutputParams::LATEX;
2352 runparams.linelen = lyxrc.plaintext_linelen;
2353 vector<string> backs = backends();
2354 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2355 // Get shortest path to format
2356 Graph::EdgePath path;
2357 for (vector<string>::const_iterator it = backs.begin();
2358 it != backs.end(); ++it) {
2359 Graph::EdgePath p = theConverters().getPath(*it, format);
2360 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2361 backend_format = *it;
2366 runparams.flavor = theConverters().getFlavor(path);
2368 Alert::error(_("Couldn't export file"),
2369 bformat(_("No information for exporting the format %1$s."),
2370 formats.prettyName(format)));
2374 backend_format = format;
2375 // FIXME: Don't hardcode format names here, but use a flag
2376 if (backend_format == "pdflatex")
2377 runparams.flavor = OutputParams::PDFLATEX;
2380 string filename = latexName(false);
2381 filename = addName(temppath(), filename);
2382 filename = changeExtension(filename,
2383 formats.extension(backend_format));
2386 updateMacroInstances();
2388 // Plain text backend
2389 if (backend_format == "text")
2390 writePlaintextFile(*this, FileName(filename), runparams);
2392 else if (backend_format == "lyx")
2393 writeFile(FileName(filename));
2395 else if (isDocBook()) {
2396 runparams.nice = !put_in_tempdir;
2397 makeDocBookFile(FileName(filename), runparams);
2400 else if (backend_format == format) {
2401 runparams.nice = true;
2402 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2404 } else if (!lyxrc.tex_allows_spaces
2405 && contains(filePath(), ' ')) {
2406 Alert::error(_("File name error"),
2407 _("The directory path to the document cannot contain spaces."));
2410 runparams.nice = false;
2411 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2415 string const error_type = (format == "program")
2416 ? "Build" : bufferFormat();
2417 ErrorList & error_list = d->errorLists[error_type];
2418 string const ext = formats.extension(format);
2419 FileName const tmp_result_file(changeExtension(filename, ext));
2420 bool const success = theConverters().convert(this, FileName(filename),
2421 tmp_result_file, FileName(absFileName()), backend_format, format,
2423 // Emit the signal to show the error list.
2424 if (format != backend_format)
2429 if (put_in_tempdir) {
2430 result_file = tmp_result_file.absFilename();
2434 result_file = changeExtension(absFileName(), ext);
2435 // We need to copy referenced files (e. g. included graphics
2436 // if format == "dvi") to the result dir.
2437 vector<ExportedFile> const files =
2438 runparams.exportdata->externalFiles(format);
2439 string const dest = onlyPath(result_file);
2440 CopyStatus status = SUCCESS;
2441 for (vector<ExportedFile>::const_iterator it = files.begin();
2442 it != files.end() && status != CANCEL; ++it) {
2443 string const fmt = formats.getFormatFromFile(it->sourceName);
2444 status = copyFile(fmt, it->sourceName,
2445 makeAbsPath(it->exportName, dest),
2446 it->exportName, status == FORCE);
2448 if (status == CANCEL) {
2449 message(_("Document export cancelled."));
2450 } else if (tmp_result_file.exists()) {
2451 // Finally copy the main file
2452 status = copyFile(format, tmp_result_file,
2453 FileName(result_file), result_file,
2455 message(bformat(_("Document exported as %1$s "
2457 formats.prettyName(format),
2458 makeDisplayPath(result_file)));
2460 // This must be a dummy converter like fax (bug 1888)
2461 message(bformat(_("Document exported as %1$s"),
2462 formats.prettyName(format)));
2469 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2472 return doExport(format, put_in_tempdir, result_file);
2476 bool Buffer::preview(string const & format) const
2479 if (!doExport(format, true, result_file))
2481 return formats.view(*this, FileName(result_file), format);
2485 bool Buffer::isExportable(string const & format) const
2487 vector<string> backs = backends();
2488 for (vector<string>::const_iterator it = backs.begin();
2489 it != backs.end(); ++it)
2490 if (theConverters().isReachable(*it, format))
2496 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2498 vector<string> backs = backends();
2499 vector<Format const *> result =
2500 theConverters().getReachable(backs[0], only_viewable, true);
2501 for (vector<string>::const_iterator it = backs.begin() + 1;
2502 it != backs.end(); ++it) {
2503 vector<Format const *> r =
2504 theConverters().getReachable(*it, only_viewable, false);
2505 result.insert(result.end(), r.begin(), r.end());
2511 vector<string> Buffer::backends() const
2514 if (params().baseClass()->isTeXClassAvailable()) {
2515 v.push_back(bufferFormat());
2516 // FIXME: Don't hardcode format names here, but use a flag
2517 if (v.back() == "latex")
2518 v.push_back("pdflatex");
2520 v.push_back("text");
2526 bool Buffer::readFileHelper(FileName const & s)
2528 // File information about normal file
2530 docstring const file = makeDisplayPath(s.absFilename(), 50);
2531 docstring text = bformat(_("The specified document\n%1$s"
2532 "\ncould not be read."), file);
2533 Alert::error(_("Could not read document"), text);
2537 // Check if emergency save file exists and is newer.
2538 FileName const e(s.absFilename() + ".emergency");
2540 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2541 docstring const file = makeDisplayPath(s.absFilename(), 20);
2542 docstring const text =
2543 bformat(_("An emergency save of the document "
2545 "Recover emergency save?"), file);
2546 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2547 _("&Recover"), _("&Load Original"),
2551 // the file is not saved if we load the emergency file.
2561 // Now check if autosave file is newer.
2562 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2564 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2565 docstring const file = makeDisplayPath(s.absFilename(), 20);
2566 docstring const text =
2567 bformat(_("The backup of the document "
2568 "%1$s is newer.\n\nLoad the "
2569 "backup instead?"), file);
2570 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2571 _("&Load backup"), _("Load &original"),
2575 // the file is not saved if we load the autosave file.
2579 // Here we delete the autosave
2590 bool Buffer::loadLyXFile(FileName const & s)
2592 if (s.isReadableFile()) {
2593 if (readFileHelper(s)) {
2594 lyxvc().file_found_hook(s);
2595 if (!s.isWritable())
2600 docstring const file = makeDisplayPath(s.absFilename(), 20);
2601 // Here we probably should run
2602 if (LyXVC::file_not_found_hook(s)) {
2603 docstring const text =
2604 bformat(_("Do you want to retrieve the document"
2605 " %1$s from version control?"), file);
2606 int const ret = Alert::prompt(_("Retrieve from version control?"),
2607 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2610 // How can we know _how_ to do the checkout?
2611 // With the current VC support it has to be,
2612 // a RCS file since CVS do not have special ,v files.
2614 return loadLyXFile(s);
2622 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2624 TeXErrors::Errors::const_iterator cit = terr.begin();
2625 TeXErrors::Errors::const_iterator end = terr.end();
2627 for (; cit != end; ++cit) {
2630 int errorRow = cit->error_in_line;
2631 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2637 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2638 } while (found && id_start == id_end && pos_start == pos_end);
2640 errorList.push_back(ErrorItem(cit->error_desc,
2641 cit->error_text, id_start, pos_start, pos_end));
2646 // FIXME: buf should should be const because updateLabels() modifies
2647 // the contents of the paragraphs.
2648 void Buffer::updateLabels(bool childonly) const
2650 // Use the master text class also for child documents
2651 Buffer const * const master = masterBuffer();
2652 DocumentClass const & textclass = master->params().documentClass();
2654 // keep the buffers to be children in this set. If the call from the
2655 // master comes back we can see which of them were actually seen (i.e.
2656 // via an InsetInclude). The remaining ones in the set need still be updated.
2657 static std::set<Buffer const *> bufToUpdate;
2659 // If this is a child document start with the master
2660 if (master != this) {
2661 bufToUpdate.insert(this);
2662 master->updateLabels(false);
2664 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
2665 if (bufToUpdate.find(this) == bufToUpdate.end())
2669 // start over the counters in the master
2670 textclass.counters().reset();
2673 // update will be done below for this buffer
2674 bufToUpdate.erase(this);
2676 // update all caches
2677 clearReferenceCache();
2678 inset().setBuffer(const_cast<Buffer &>(*this));
2681 Buffer & cbuf = const_cast<Buffer &>(*this);
2683 LASSERT(!text().paragraphs().empty(), /**/);
2686 ParIterator parit = cbuf.par_iterator_begin();
2687 lyx::updateLabels(*this, parit);
2690 // TocBackend update will be done later.
2693 cbuf.tocBackend().update();
2695 cbuf.structureChanged();