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>
110 using namespace lyx::support;
114 namespace Alert = frontend::Alert;
115 namespace os = support::os;
119 // Do not remove the comment below, so we get merge conflict in
120 // independent branches. Instead add your own.
121 int const LYX_FORMAT = 345; // jamatos: xml elements
123 typedef map<string, bool> DepClean;
124 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
128 class BufferSet : public std::set<Buffer const *> {};
133 Impl(Buffer & parent, FileName const & file, bool readonly);
147 mutable TexRow texrow;
148 Buffer const * parent_buffer;
150 /// need to regenerate .tex?
154 mutable bool lyx_clean;
156 /// is autosave needed?
157 mutable bool bak_clean;
159 /// is this a unnamed file (New...)?
165 /// name of the file the buffer is associated with.
168 /** Set to true only when the file is fully loaded.
169 * Used to prevent the premature generation of previews
170 * and by the citation inset.
172 bool file_fully_loaded;
175 mutable TocBackend toc_backend;
178 typedef pair<DocIterator, MacroData> ScopeMacro;
179 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
180 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
181 /// map from the macro name to the position map,
182 /// which maps the macro definition position to the scope and the MacroData.
183 NamePositionScopeMacroMap macros;
186 /// positions of child buffers in the buffer
187 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
188 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
189 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
190 /// position of children buffers in this buffer
191 BufferPositionMap children_positions;
192 /// map from children inclusion positions to their scope and their buffer
193 PositionScopeBufferMap position_to_children;
195 /// Container for all sort of Buffer dependant errors.
196 map<string, ErrorList> errorLists;
198 /// timestamp and checksum used to test if the file has been externally
199 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
201 unsigned long checksum_;
204 frontend::WorkAreaManager * wa_;
209 /// A cache for the bibfiles (including bibfiles of loaded child
210 /// documents), needed for appropriate update of natbib labels.
211 mutable support::FileNameList bibfilesCache_;
213 // FIXME The caching mechanism could be improved. At present, we have a
214 // cache for each Buffer, that caches all the bibliography info for that
215 // Buffer. A more efficient solution would be to have a global cache per
216 // file, and then to construct the Buffer's bibinfo from that.
217 /// A cache for bibliography info
218 mutable BiblioInfo bibinfo_;
219 /// whether the bibinfo cache is valid
220 bool bibinfoCacheValid_;
221 /// Cache of timestamps of .bib files
222 map<FileName, time_t> bibfileStatus_;
224 mutable RefCache ref_cache_;
226 /// our Text that should be wrapped in an InsetText
231 /// Creates the per buffer temporary directory
232 static FileName createBufferTmpDir()
235 // We are in our own directory. Why bother to mangle name?
236 // In fact I wrote this code to circumvent a problematic behaviour
237 // (bug?) of EMX mkstemp().
238 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
239 convert<string>(count++));
241 if (!tmpfl.createDirectory(0777)) {
242 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
243 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
244 from_utf8(tmpfl.absFilename())));
250 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
251 : parent_buffer(0), lyx_clean(true), bak_clean(true), unnamed(false),
252 read_only(readonly_), filename(file), file_fully_loaded(false),
253 toc_backend(&parent), macro_lock(false), timestamp_(0),
254 checksum_(0), wa_(0), undo_(parent), bibinfoCacheValid_(false)
256 temppath = createBufferTmpDir();
257 lyxvc.setBuffer(&parent);
259 wa_ = new frontend::WorkAreaManager;
263 Buffer::Buffer(string const & file, bool readonly)
264 : d(new Impl(*this, FileName(file), readonly)), gui_(0)
266 LYXERR(Debug::INFO, "Buffer::Buffer()");
268 d->inset = new InsetText(*this);
269 d->inset->setAutoBreakRows(true);
270 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
276 LYXERR(Debug::INFO, "Buffer::~Buffer()");
277 // here the buffer should take care that it is
278 // saved properly, before it goes into the void.
280 // GuiView already destroyed
283 if (d->unnamed && d->filename.extension() == "internal") {
284 // No need to do additional cleanups for internal buffer.
289 // loop over children
290 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
291 Impl::BufferPositionMap::iterator end = d->children_positions.end();
292 for (; it != end; ++it)
293 theBufferList().releaseChild(this, const_cast<Buffer *>(it->first));
295 // clear references to children in macro tables
296 d->children_positions.clear();
297 d->position_to_children.clear();
299 if (!d->temppath.destroyDirectory()) {
300 Alert::warning(_("Could not remove temporary directory"),
301 bformat(_("Could not remove the temporary directory %1$s"),
302 from_utf8(d->temppath.absFilename())));
305 // Remove any previewed LaTeX snippets associated with this buffer.
306 thePreviews().removeLoader(*this);
312 void Buffer::changed() const
319 frontend::WorkAreaManager & Buffer::workAreaManager() const
321 LASSERT(d->wa_, /**/);
326 Text & Buffer::text() const
328 return d->inset->text();
332 Inset & Buffer::inset() const
338 BufferParams & Buffer::params()
344 BufferParams const & Buffer::params() const
350 ParagraphList & Buffer::paragraphs()
352 return text().paragraphs();
356 ParagraphList const & Buffer::paragraphs() const
358 return text().paragraphs();
362 LyXVC & Buffer::lyxvc()
368 LyXVC const & Buffer::lyxvc() const
374 string const Buffer::temppath() const
376 return d->temppath.absFilename();
380 TexRow & Buffer::texrow()
386 TexRow const & Buffer::texrow() const
392 TocBackend & Buffer::tocBackend() const
394 return d->toc_backend;
398 Undo & Buffer::undo()
404 string Buffer::latexName(bool const no_path) const
406 FileName latex_name = makeLatexName(d->filename);
407 return no_path ? latex_name.onlyFileName()
408 : latex_name.absFilename();
412 string Buffer::logName(LogType * type) const
414 string const filename = latexName(false);
416 if (filename.empty()) {
422 string const path = temppath();
424 FileName const fname(addName(temppath(),
425 onlyFilename(changeExtension(filename,
427 FileName const bname(
428 addName(path, onlyFilename(
429 changeExtension(filename,
430 formats.extension("literate") + ".out"))));
432 // If no Latex log or Build log is newer, show Build log
434 if (bname.exists() &&
435 (!fname.exists() || fname.lastModified() < bname.lastModified())) {
436 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
439 return bname.absFilename();
441 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
444 return fname.absFilename();
448 void Buffer::setReadonly(bool const flag)
450 if (d->read_only != flag) {
457 void Buffer::setFileName(string const & newfile)
459 d->filename = makeAbsPath(newfile);
460 setReadonly(d->filename.isReadOnly());
465 int Buffer::readHeader(Lexer & lex)
467 int unknown_tokens = 0;
469 int begin_header_line = -1;
471 // Initialize parameters that may be/go lacking in header:
472 params().branchlist().clear();
473 params().preamble.erase();
474 params().options.erase();
475 params().master.erase();
476 params().float_placement.erase();
477 params().paperwidth.erase();
478 params().paperheight.erase();
479 params().leftmargin.erase();
480 params().rightmargin.erase();
481 params().topmargin.erase();
482 params().bottommargin.erase();
483 params().headheight.erase();
484 params().headsep.erase();
485 params().footskip.erase();
486 params().columnsep.erase();
487 params().fontsCJK.erase();
488 params().listings_params.clear();
489 params().clearLayoutModules();
490 params().clearRemovedModules();
491 params().pdfoptions().clear();
493 for (int i = 0; i < 4; ++i) {
494 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
495 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
498 ErrorList & errorList = d->errorLists["Parse"];
507 if (token == "\\end_header")
511 if (token == "\\begin_header") {
512 begin_header_line = line;
516 LYXERR(Debug::PARSER, "Handling document header token: `"
519 string unknown = params().readToken(lex, token, d->filename.onlyPath());
520 if (!unknown.empty()) {
521 if (unknown[0] != '\\' && token == "\\textclass") {
522 Alert::warning(_("Unknown document class"),
523 bformat(_("Using the default document class, because the "
524 "class %1$s is unknown."), from_utf8(unknown)));
527 docstring const s = bformat(_("Unknown token: "
531 errorList.push_back(ErrorItem(_("Document header error"),
536 if (begin_header_line) {
537 docstring const s = _("\\begin_header is missing");
538 errorList.push_back(ErrorItem(_("Document header error"),
542 params().makeDocumentClass();
544 return unknown_tokens;
549 // changed to be public and have one parameter
550 // Returns false if "\end_document" is not read (Asger)
551 bool Buffer::readDocument(Lexer & lex)
553 ErrorList & errorList = d->errorLists["Parse"];
556 if (!lex.checkFor("\\begin_document")) {
557 docstring const s = _("\\begin_document is missing");
558 errorList.push_back(ErrorItem(_("Document header error"),
562 // we are reading in a brand new document
563 LASSERT(paragraphs().empty(), /**/);
567 if (params().outputChanges) {
568 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
569 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
570 LaTeXFeatures::isAvailable("xcolor");
572 if (!dvipost && !xcolorsoul) {
573 Alert::warning(_("Changes not shown in LaTeX output"),
574 _("Changes will not be highlighted in LaTeX output, "
575 "because neither dvipost nor xcolor/soul are installed.\n"
576 "Please install these packages or redefine "
577 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
578 } else if (!xcolorsoul) {
579 Alert::warning(_("Changes not shown in LaTeX output"),
580 _("Changes will not be highlighted in LaTeX output "
581 "when using pdflatex, because xcolor and soul are not installed.\n"
582 "Please install both packages or redefine "
583 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
587 if (!params().master.empty()) {
588 FileName const master_file = makeAbsPath(params().master,
589 onlyPath(absFileName()));
590 if (isLyXFilename(master_file.absFilename())) {
591 Buffer * master = checkAndLoadLyXFile(master_file);
592 d->parent_buffer = master;
597 bool const res = text().read(*this, lex, errorList, d->inset);
600 updateMacroInstances();
605 // needed to insert the selection
606 void Buffer::insertStringAsLines(ParagraphList & pars,
607 pit_type & pit, pos_type & pos,
608 Font const & fn, docstring const & str, bool autobreakrows)
612 // insert the string, don't insert doublespace
613 bool space_inserted = true;
614 for (docstring::const_iterator cit = str.begin();
615 cit != str.end(); ++cit) {
616 Paragraph & par = pars[pit];
618 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
619 breakParagraph(params(), pars, pit, pos,
620 par.layout().isEnvironment());
623 space_inserted = true;
627 // do not insert consecutive spaces if !free_spacing
628 } else if ((*cit == ' ' || *cit == '\t') &&
629 space_inserted && !par.isFreeSpacing()) {
631 } else if (*cit == '\t') {
632 if (!par.isFreeSpacing()) {
633 // tabs are like spaces here
634 par.insertChar(pos, ' ', font, params().trackChanges);
636 space_inserted = true;
638 par.insertChar(pos, *cit, font, params().trackChanges);
640 space_inserted = true;
642 } else if (!isPrintable(*cit)) {
643 // Ignore unprintables
646 // just insert the character
647 par.insertChar(pos, *cit, font, params().trackChanges);
649 space_inserted = (*cit == ' ');
656 bool Buffer::readString(string const & s)
658 params().compressed = false;
660 // remove dummy empty par
661 paragraphs().clear();
665 FileName const name = FileName::tempName("Buffer_readString");
666 switch (readFile(lex, name, true)) {
670 // We need to call lyx2lyx, so write the input to a file
671 ofstream os(name.toFilesystemEncoding().c_str());
674 return readFile(name);
684 bool Buffer::readFile(FileName const & filename)
686 FileName fname(filename);
688 // remove dummy empty par
689 paragraphs().clear();
692 if (readFile(lex, fname) != success)
699 bool Buffer::isFullyLoaded() const
701 return d->file_fully_loaded;
705 void Buffer::setFullyLoaded(bool value)
707 d->file_fully_loaded = value;
711 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
714 LASSERT(!filename.empty(), /**/);
716 // the first (non-comment) token _must_ be...
717 if (!lex.checkFor("\\lyxformat")) {
718 Alert::error(_("Document format failure"),
719 bformat(_("%1$s is not a readable LyX document."),
720 from_utf8(filename.absFilename())));
726 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
727 // if present remove ".," from string.
728 size_t dot = tmp_format.find_first_of(".,");
729 //lyxerr << " dot found at " << dot << endl;
730 if (dot != string::npos)
731 tmp_format.erase(dot, 1);
732 int const file_format = convert<int>(tmp_format);
733 //lyxerr << "format: " << file_format << endl;
735 // save timestamp and checksum of the original disk file, making sure
736 // to not overwrite them with those of the file created in the tempdir
737 // when it has to be converted to the current format.
739 // Save the timestamp and checksum of disk file. If filename is an
740 // emergency file, save the timestamp and checksum of the original lyx file
741 // because isExternallyModified will check for this file. (BUG4193)
742 string diskfile = filename.absFilename();
743 if (suffixIs(diskfile, ".emergency"))
744 diskfile = diskfile.substr(0, diskfile.size() - 10);
745 saveCheckSum(FileName(diskfile));
748 if (file_format != LYX_FORMAT) {
751 // lyx2lyx would fail
754 FileName const tmpfile = FileName::tempName("Buffer_readFile");
755 if (tmpfile.empty()) {
756 Alert::error(_("Conversion failed"),
757 bformat(_("%1$s is from a different"
758 " version of LyX, but a temporary"
759 " file for converting it could"
761 from_utf8(filename.absFilename())));
764 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
765 if (lyx2lyx.empty()) {
766 Alert::error(_("Conversion script not found"),
767 bformat(_("%1$s is from a different"
768 " version of LyX, but the"
769 " conversion script lyx2lyx"
770 " could not be found."),
771 from_utf8(filename.absFilename())));
774 ostringstream command;
775 command << os::python()
776 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
777 << " -t " << convert<string>(LYX_FORMAT)
778 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
779 << ' ' << quoteName(filename.toFilesystemEncoding());
780 string const command_str = command.str();
782 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
784 cmd_ret const ret = runCommand(command_str);
785 if (ret.first != 0) {
786 Alert::error(_("Conversion script failed"),
787 bformat(_("%1$s is from a different version"
788 " of LyX, but the lyx2lyx script"
789 " failed to convert it."),
790 from_utf8(filename.absFilename())));
793 bool const ret = readFile(tmpfile);
794 // Do stuff with tmpfile name and buffer name here.
795 return ret ? success : failure;
800 if (readDocument(lex)) {
801 Alert::error(_("Document format failure"),
802 bformat(_("%1$s ended unexpectedly, which means"
803 " that it is probably corrupted."),
804 from_utf8(filename.absFilename())));
807 d->file_fully_loaded = true;
812 // Should probably be moved to somewhere else: BufferView? LyXView?
813 bool Buffer::save() const
815 // We don't need autosaves in the immediate future. (Asger)
816 resetAutosaveTimers();
818 string const encodedFilename = d->filename.toFilesystemEncoding();
821 bool madeBackup = false;
823 // make a backup if the file already exists
824 if (lyxrc.make_backup && fileName().exists()) {
825 backupName = FileName(absFileName() + '~');
826 if (!lyxrc.backupdir_path.empty()) {
827 string const mangledName =
828 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
829 backupName = FileName(addName(lyxrc.backupdir_path,
832 if (fileName().copyTo(backupName)) {
835 Alert::error(_("Backup failure"),
836 bformat(_("Cannot create backup file %1$s.\n"
837 "Please check whether the directory exists and is writeable."),
838 from_utf8(backupName.absFilename())));
839 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
843 // ask if the disk file has been externally modified (use checksum method)
844 if (fileName().exists() && isExternallyModified(checksum_method)) {
845 docstring const file = makeDisplayPath(absFileName(), 20);
846 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
847 "you want to overwrite this file?"), file);
848 int const ret = Alert::prompt(_("Overwrite modified file?"),
849 text, 1, 1, _("&Overwrite"), _("&Cancel"));
854 if (writeFile(d->filename)) {
858 // Saving failed, so backup is not backup
860 backupName.moveTo(d->filename);
866 bool Buffer::writeFile(FileName const & fname) const
868 if (d->read_only && fname == d->filename)
873 docstring const str = bformat(_("Saving document %1$s..."),
874 makeDisplayPath(fname.absFilename()));
877 if (params().compressed) {
878 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
879 retval = ofs && write(ofs);
881 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
882 retval = ofs && write(ofs);
886 message(str + _(" could not write file!"));
890 removeAutosaveFile(d->filename.absFilename());
892 saveCheckSum(d->filename);
893 message(str + _(" done."));
899 bool Buffer::write(ostream & ofs) const
902 // Use the standard "C" locale for file output.
903 ofs.imbue(locale::classic());
906 // The top of the file should not be written by params().
908 // write out a comment in the top of the file
909 ofs << "#LyX " << lyx_version
910 << " created this file. For more info see http://www.lyx.org/\n"
911 << "\\lyxformat " << LYX_FORMAT << "\n"
912 << "\\begin_document\n";
914 /// For each author, set 'used' to true if there is a change
915 /// by this author in the document; otherwise set it to 'false'.
916 AuthorList::Authors::const_iterator a_it = params().authors().begin();
917 AuthorList::Authors::const_iterator a_end = params().authors().end();
918 for (; a_it != a_end; ++a_it)
919 a_it->second.setUsed(false);
921 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
922 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
923 for ( ; it != end; ++it)
924 it->checkAuthors(params().authors());
926 // now write out the buffer parameters.
927 ofs << "\\begin_header\n";
928 params().writeFile(ofs);
929 ofs << "\\end_header\n";
932 ofs << "\n\\begin_body\n";
933 text().write(*this, ofs);
934 ofs << "\n\\end_body\n";
936 // Write marker that shows file is complete
937 ofs << "\\end_document" << endl;
939 // Shouldn't really be needed....
942 // how to check if close went ok?
943 // Following is an attempt... (BE 20001011)
945 // good() returns false if any error occured, including some
947 // bad() returns true if something bad happened in the buffer,
948 // which should include file system full errors.
953 lyxerr << "File was not closed properly." << endl;
960 bool Buffer::makeLaTeXFile(FileName const & fname,
961 string const & original_path,
962 OutputParams const & runparams,
963 bool output_preamble, bool output_body) const
965 string const encoding = runparams.encoding->iconvName();
966 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
969 try { ofs.reset(encoding); }
970 catch (iconv_codecvt_facet_exception & e) {
971 lyxerr << "Caught iconv exception: " << e.what() << endl;
972 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
973 "verify that the support software for your encoding (%1$s) is "
974 "properly installed"), from_ascii(encoding)));
977 if (!openFileWrite(ofs, fname))
980 //TexStream ts(ofs.rdbuf(), &texrow());
981 ErrorList & errorList = d->errorLists["Export"];
983 bool failed_export = false;
986 writeLaTeXSource(ofs, original_path,
987 runparams, output_preamble, output_body);
989 catch (EncodingException & e) {
990 odocstringstream ods;
991 ods.put(e.failed_char);
993 oss << "0x" << hex << e.failed_char << dec;
994 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
995 " (code point %2$s)"),
996 ods.str(), from_utf8(oss.str()));
997 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
998 "representable in the chosen encoding.\n"
999 "Changing the document encoding to utf8 could help."),
1000 e.par_id, e.pos, e.pos + 1));
1001 failed_export = true;
1003 catch (iconv_codecvt_facet_exception & e) {
1004 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1005 _(e.what()), -1, 0, 0));
1006 failed_export = true;
1008 catch (exception const & e) {
1009 errorList.push_back(ErrorItem(_("conversion failed"),
1010 _(e.what()), -1, 0, 0));
1011 failed_export = true;
1014 lyxerr << "Caught some really weird exception..." << endl;
1020 failed_export = true;
1021 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1025 return !failed_export;
1029 void Buffer::writeLaTeXSource(odocstream & os,
1030 string const & original_path,
1031 OutputParams const & runparams_in,
1032 bool const output_preamble, bool const output_body) const
1034 // The child documents, if any, shall be already loaded at this point.
1036 OutputParams runparams = runparams_in;
1038 // Classify the unicode characters appearing in math insets
1039 Encodings::initUnicodeMath(*this);
1041 // validate the buffer.
1042 LYXERR(Debug::LATEX, " Validating buffer...");
1043 LaTeXFeatures features(*this, params(), runparams);
1045 LYXERR(Debug::LATEX, " Buffer validation done.");
1047 // The starting paragraph of the coming rows is the
1048 // first paragraph of the document. (Asger)
1049 if (output_preamble && runparams.nice) {
1050 os << "%% LyX " << lyx_version << " created this file. "
1051 "For more info, see http://www.lyx.org/.\n"
1052 "%% Do not edit unless you really know what "
1054 d->texrow.newline();
1055 d->texrow.newline();
1057 LYXERR(Debug::INFO, "lyx document header finished");
1059 // Don't move this behind the parent_buffer=0 code below,
1060 // because then the macros will not get the right "redefinition"
1061 // flag as they don't see the parent macros which are output before.
1064 // fold macros if possible, still with parent buffer as the
1065 // macros will be put in the prefix anyway.
1066 updateMacroInstances();
1068 // There are a few differences between nice LaTeX and usual files:
1069 // usual is \batchmode and has a
1070 // special input@path to allow the including of figures
1071 // with either \input or \includegraphics (what figinsets do).
1072 // input@path is set when the actual parameter
1073 // original_path is set. This is done for usual tex-file, but not
1074 // for nice-latex-file. (Matthias 250696)
1075 // Note that input@path is only needed for something the user does
1076 // in the preamble, included .tex files or ERT, files included by
1077 // LyX work without it.
1078 if (output_preamble) {
1079 if (!runparams.nice) {
1080 // code for usual, NOT nice-latex-file
1081 os << "\\batchmode\n"; // changed
1082 // from \nonstopmode
1083 d->texrow.newline();
1085 if (!original_path.empty()) {
1087 // We don't know the encoding of inputpath
1088 docstring const inputpath = from_utf8(latex_path(original_path));
1089 os << "\\makeatletter\n"
1090 << "\\def\\input@path{{"
1091 << inputpath << "/}}\n"
1092 << "\\makeatother\n";
1093 d->texrow.newline();
1094 d->texrow.newline();
1095 d->texrow.newline();
1098 // get parent macros (if this buffer has a parent) which will be
1099 // written at the document begin further down.
1100 MacroSet parentMacros;
1101 listParentMacros(parentMacros, features);
1103 // Write the preamble
1104 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1106 runparams.use_japanese = features.isRequired("japanese");
1112 os << "\\begin{document}\n";
1113 d->texrow.newline();
1115 // output the parent macros
1116 MacroSet::iterator it = parentMacros.begin();
1117 MacroSet::iterator end = parentMacros.end();
1118 for (; it != end; ++it)
1119 (*it)->write(os, true);
1120 } // output_preamble
1122 d->texrow.start(paragraphs().begin()->id(), 0);
1124 LYXERR(Debug::INFO, "preamble finished, now the body.");
1126 // if we are doing a real file with body, even if this is the
1127 // child of some other buffer, let's cut the link here.
1128 // This happens for example if only a child document is printed.
1129 Buffer const * save_parent = 0;
1130 if (output_preamble) {
1131 save_parent = d->parent_buffer;
1132 d->parent_buffer = 0;
1136 latexParagraphs(*this, text(), os, d->texrow, runparams);
1138 // Restore the parenthood if needed
1139 if (output_preamble)
1140 d->parent_buffer = save_parent;
1142 // add this just in case after all the paragraphs
1144 d->texrow.newline();
1146 if (output_preamble) {
1147 os << "\\end{document}\n";
1148 d->texrow.newline();
1149 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1151 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1153 runparams_in.encoding = runparams.encoding;
1155 // Just to be sure. (Asger)
1156 d->texrow.newline();
1158 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1159 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1163 bool Buffer::isLatex() const
1165 return params().documentClass().outputType() == LATEX;
1169 bool Buffer::isLiterate() const
1171 return params().documentClass().outputType() == LITERATE;
1175 bool Buffer::isDocBook() const
1177 return params().documentClass().outputType() == DOCBOOK;
1181 void Buffer::makeDocBookFile(FileName const & fname,
1182 OutputParams const & runparams,
1183 bool const body_only) const
1185 LYXERR(Debug::LATEX, "makeDocBookFile...");
1188 if (!openFileWrite(ofs, fname))
1191 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1195 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1199 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1200 OutputParams const & runparams,
1201 bool const only_body) const
1203 LaTeXFeatures features(*this, params(), runparams);
1208 DocumentClass const & tclass = params().documentClass();
1209 string const top_element = tclass.latexname();
1212 if (runparams.flavor == OutputParams::XML)
1213 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1216 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1219 if (! tclass.class_header().empty())
1220 os << from_ascii(tclass.class_header());
1221 else if (runparams.flavor == OutputParams::XML)
1222 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1223 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1225 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1227 docstring preamble = from_utf8(params().preamble);
1228 if (runparams.flavor != OutputParams::XML ) {
1229 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1230 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1231 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1232 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1235 string const name = runparams.nice
1236 ? changeExtension(absFileName(), ".sgml") : fname;
1237 preamble += features.getIncludedFiles(name);
1238 preamble += features.getLyXSGMLEntities();
1240 if (!preamble.empty()) {
1241 os << "\n [ " << preamble << " ]";
1246 string top = top_element;
1248 if (runparams.flavor == OutputParams::XML)
1249 top += params().language->code();
1251 top += params().language->code().substr(0, 2);
1254 if (!params().options.empty()) {
1256 top += params().options;
1259 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1260 << " file was created by LyX " << lyx_version
1261 << "\n See http://www.lyx.org/ for more information -->\n";
1263 params().documentClass().counters().reset();
1267 sgml::openTag(os, top);
1269 docbookParagraphs(paragraphs(), *this, os, runparams);
1270 sgml::closeTag(os, top_element);
1274 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1275 // Other flags: -wall -v0 -x
1276 int Buffer::runChktex()
1280 // get LaTeX-Filename
1281 FileName const path(temppath());
1282 string const name = addName(path.absFilename(), latexName());
1283 string const org_path = filePath();
1285 PathChanger p(path); // path to LaTeX file
1286 message(_("Running chktex..."));
1288 // Generate the LaTeX file if neccessary
1289 OutputParams runparams(¶ms().encoding());
1290 runparams.flavor = OutputParams::LATEX;
1291 runparams.nice = false;
1292 makeLaTeXFile(FileName(name), org_path, runparams);
1295 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1296 int const res = chktex.run(terr); // run chktex
1299 Alert::error(_("chktex failure"),
1300 _("Could not run chktex successfully."));
1301 } else if (res > 0) {
1302 ErrorList & errlist = d->errorLists["ChkTeX"];
1304 bufferErrors(terr, errlist);
1315 void Buffer::validate(LaTeXFeatures & features) const
1317 params().validate(features);
1321 for_each(paragraphs().begin(), paragraphs().end(),
1322 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1324 if (lyxerr.debugging(Debug::LATEX)) {
1325 features.showStruct();
1330 void Buffer::getLabelList(vector<docstring> & list) const
1332 // If this is a child document, use the parent's list instead.
1333 if (d->parent_buffer) {
1334 d->parent_buffer->getLabelList(list);
1339 Toc & toc = d->toc_backend.toc("label");
1340 TocIterator toc_it = toc.begin();
1341 TocIterator end = toc.end();
1342 for (; toc_it != end; ++toc_it) {
1343 if (toc_it->depth() == 0)
1344 list.push_back(toc_it->str());
1349 void Buffer::updateBibfilesCache() const
1351 // If this is a child document, use the parent's cache instead.
1352 if (d->parent_buffer) {
1353 d->parent_buffer->updateBibfilesCache();
1357 d->bibfilesCache_.clear();
1358 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1359 if (it->lyxCode() == BIBTEX_CODE) {
1360 InsetBibtex const & inset =
1361 static_cast<InsetBibtex const &>(*it);
1362 support::FileNameList const bibfiles = inset.getBibFiles();
1363 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1366 } else if (it->lyxCode() == INCLUDE_CODE) {
1367 InsetInclude & inset =
1368 static_cast<InsetInclude &>(*it);
1369 inset.updateBibfilesCache();
1370 support::FileNameList const & bibfiles =
1371 inset.getBibfilesCache(*this);
1372 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1377 // the bibinfo cache is now invalid
1378 d->bibinfoCacheValid_ = false;
1382 void Buffer::invalidateBibinfoCache()
1384 d->bibinfoCacheValid_ = false;
1388 support::FileNameList const & Buffer::getBibfilesCache() const
1390 // If this is a child document, use the parent's cache instead.
1391 if (d->parent_buffer)
1392 return d->parent_buffer->getBibfilesCache();
1394 // We update the cache when first used instead of at loading time.
1395 if (d->bibfilesCache_.empty())
1396 const_cast<Buffer *>(this)->updateBibfilesCache();
1398 return d->bibfilesCache_;
1402 BiblioInfo const & Buffer::masterBibInfo() const
1404 // if this is a child document and the parent is already loaded
1405 // use the parent's list instead [ale990412]
1406 Buffer const * const tmp = masterBuffer();
1409 return tmp->masterBibInfo();
1410 return localBibInfo();
1414 BiblioInfo const & Buffer::localBibInfo() const
1416 if (d->bibinfoCacheValid_) {
1417 support::FileNameList const & bibfilesCache = getBibfilesCache();
1418 // compare the cached timestamps with the actual ones.
1419 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1420 support::FileNameList::const_iterator en = bibfilesCache.end();
1421 for (; ei != en; ++ ei) {
1422 time_t lastw = ei->lastModified();
1423 if (lastw != d->bibfileStatus_[*ei]) {
1424 d->bibinfoCacheValid_ = false;
1425 d->bibfileStatus_[*ei] = lastw;
1431 if (!d->bibinfoCacheValid_) {
1432 d->bibinfo_.clear();
1433 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1434 it->fillWithBibKeys(d->bibinfo_, it);
1435 d->bibinfoCacheValid_ = true;
1441 bool Buffer::isDepClean(string const & name) const
1443 DepClean::const_iterator const it = d->dep_clean.find(name);
1444 if (it == d->dep_clean.end())
1450 void Buffer::markDepClean(string const & name)
1452 d->dep_clean[name] = true;
1456 bool Buffer::dispatch(string const & command, bool * result)
1458 return dispatch(lyxaction.lookupFunc(command), result);
1462 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1464 bool dispatched = true;
1466 switch (func.action) {
1467 case LFUN_BUFFER_EXPORT: {
1468 bool const tmp = doExport(to_utf8(func.argument()), false);
1474 case LFUN_BRANCH_ACTIVATE:
1475 case LFUN_BRANCH_DEACTIVATE: {
1476 BranchList & branchList = params().branchlist();
1477 docstring const branchName = func.argument();
1478 Branch * branch = branchList.find(branchName);
1480 LYXERR0("Branch " << branchName << " does not exist.");
1482 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1494 void Buffer::changeLanguage(Language const * from, Language const * to)
1496 LASSERT(from, /**/);
1499 for_each(par_iterator_begin(),
1501 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1505 bool Buffer::isMultiLingual() const
1507 ParConstIterator end = par_iterator_end();
1508 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1509 if (it->isMultiLingual(params()))
1516 DocIterator Buffer::getParFromID(int const id) const
1518 Buffer * buf = const_cast<Buffer *>(this);
1520 // John says this is called with id == -1 from undo
1521 lyxerr << "getParFromID(), id: " << id << endl;
1522 return doc_iterator_end(buf);
1525 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
1526 if (it.paragraph().id() == id)
1529 return doc_iterator_end(buf);
1533 bool Buffer::hasParWithID(int const id) const
1535 return !getParFromID(id).atEnd();
1539 ParIterator Buffer::par_iterator_begin()
1541 return ParIterator(doc_iterator_begin(this));
1545 ParIterator Buffer::par_iterator_end()
1547 return ParIterator(doc_iterator_end(this));
1551 ParConstIterator Buffer::par_iterator_begin() const
1553 return ParConstIterator(doc_iterator_begin(this));
1557 ParConstIterator Buffer::par_iterator_end() const
1559 return ParConstIterator(doc_iterator_end(this));
1563 Language const * Buffer::language() const
1565 return params().language;
1569 docstring const Buffer::B_(string const & l10n) const
1571 return params().B_(l10n);
1575 bool Buffer::isClean() const
1577 return d->lyx_clean;
1581 bool Buffer::isBakClean() const
1583 return d->bak_clean;
1587 bool Buffer::isExternallyModified(CheckMethod method) const
1589 LASSERT(d->filename.exists(), /**/);
1590 // if method == timestamp, check timestamp before checksum
1591 return (method == checksum_method
1592 || d->timestamp_ != d->filename.lastModified())
1593 && d->checksum_ != d->filename.checksum();
1597 void Buffer::saveCheckSum(FileName const & file) const
1599 if (file.exists()) {
1600 d->timestamp_ = file.lastModified();
1601 d->checksum_ = file.checksum();
1603 // in the case of save to a new file.
1610 void Buffer::markClean() const
1612 if (!d->lyx_clean) {
1613 d->lyx_clean = true;
1616 // if the .lyx file has been saved, we don't need an
1618 d->bak_clean = true;
1622 void Buffer::markBakClean() const
1624 d->bak_clean = true;
1628 void Buffer::setUnnamed(bool flag)
1634 bool Buffer::isUnnamed() const
1640 // FIXME: this function should be moved to buffer_pimpl.C
1641 void Buffer::markDirty()
1644 d->lyx_clean = false;
1647 d->bak_clean = false;
1649 DepClean::iterator it = d->dep_clean.begin();
1650 DepClean::const_iterator const end = d->dep_clean.end();
1652 for (; it != end; ++it)
1657 FileName Buffer::fileName() const
1663 string Buffer::absFileName() const
1665 return d->filename.absFilename();
1669 string Buffer::filePath() const
1671 return d->filename.onlyPath().absFilename() + "/";
1675 bool Buffer::isReadonly() const
1677 return d->read_only;
1681 void Buffer::setParent(Buffer const * buffer)
1683 // Avoids recursive include.
1684 d->parent_buffer = buffer == this ? 0 : buffer;
1689 Buffer const * Buffer::parent() const
1691 return d->parent_buffer;
1695 void Buffer::collectRelatives(BufferSet & bufs) const
1699 parent()->collectRelatives(bufs);
1701 // loop over children
1702 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
1703 Impl::BufferPositionMap::iterator end = d->children_positions.end();
1704 for (; it != end; ++it)
1705 bufs.insert(const_cast<Buffer *>(it->first));
1709 std::vector<Buffer const *> Buffer::allRelatives() const
1712 collectRelatives(bufs);
1713 BufferSet::iterator it = bufs.begin();
1714 std::vector<Buffer const *> ret;
1715 for (; it != bufs.end(); ++it)
1721 Buffer const * Buffer::masterBuffer() const
1723 if (!d->parent_buffer)
1726 return d->parent_buffer->masterBuffer();
1730 bool Buffer::isChild(Buffer * child) const
1732 return d->children_positions.find(child) != d->children_positions.end();
1736 DocIterator Buffer::firstChildPosition(Buffer const * child)
1738 Impl::BufferPositionMap::iterator it;
1739 it = d->children_positions.find(child);
1740 if (it == d->children_positions.end())
1741 return DocIterator(this);
1746 template<typename M>
1747 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
1752 typename M::iterator it = m.lower_bound(x);
1753 if (it == m.begin())
1761 MacroData const * Buffer::getBufferMacro(docstring const & name,
1762 DocIterator const & pos) const
1764 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
1766 // if paragraphs have no macro context set, pos will be empty
1770 // we haven't found anything yet
1771 DocIterator bestPos = par_iterator_begin();
1772 MacroData const * bestData = 0;
1774 // find macro definitions for name
1775 Impl::NamePositionScopeMacroMap::iterator nameIt
1776 = d->macros.find(name);
1777 if (nameIt != d->macros.end()) {
1778 // find last definition in front of pos or at pos itself
1779 Impl::PositionScopeMacroMap::const_iterator it
1780 = greatest_below(nameIt->second, pos);
1781 if (it != nameIt->second.end()) {
1783 // scope ends behind pos?
1784 if (pos < it->second.first) {
1785 // Looks good, remember this. If there
1786 // is no external macro behind this,
1787 // we found the right one already.
1788 bestPos = it->first;
1789 bestData = &it->second.second;
1793 // try previous macro if there is one
1794 if (it == nameIt->second.begin())
1801 // find macros in included files
1802 Impl::PositionScopeBufferMap::const_iterator it
1803 = greatest_below(d->position_to_children, pos);
1804 if (it == d->position_to_children.end())
1805 // no children before
1809 // do we know something better (i.e. later) already?
1810 if (it->first < bestPos )
1813 // scope ends behind pos?
1814 if (pos < it->second.first) {
1815 // look for macro in external file
1816 d->macro_lock = true;
1817 MacroData const * data
1818 = it->second.second->getMacro(name, false);
1819 d->macro_lock = false;
1821 bestPos = it->first;
1827 // try previous file if there is one
1828 if (it == d->position_to_children.begin())
1833 // return the best macro we have found
1838 MacroData const * Buffer::getMacro(docstring const & name,
1839 DocIterator const & pos, bool global) const
1844 // query buffer macros
1845 MacroData const * data = getBufferMacro(name, pos);
1849 // If there is a master buffer, query that
1850 if (d->parent_buffer) {
1851 d->macro_lock = true;
1852 MacroData const * macro = d->parent_buffer->getMacro(
1853 name, *this, false);
1854 d->macro_lock = false;
1860 data = MacroTable::globalMacros().get(name);
1869 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
1871 // set scope end behind the last paragraph
1872 DocIterator scope = par_iterator_begin();
1873 scope.pit() = scope.lastpit() + 1;
1875 return getMacro(name, scope, global);
1879 MacroData const * Buffer::getMacro(docstring const & name,
1880 Buffer const & child, bool global) const
1882 // look where the child buffer is included first
1883 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
1884 if (it == d->children_positions.end())
1887 // check for macros at the inclusion position
1888 return getMacro(name, it->second, global);
1892 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
1894 pit_type lastpit = it.lastpit();
1896 // look for macros in each paragraph
1897 while (it.pit() <= lastpit) {
1898 Paragraph & par = it.paragraph();
1900 // iterate over the insets of the current paragraph
1901 InsetList const & insets = par.insetList();
1902 InsetList::const_iterator iit = insets.begin();
1903 InsetList::const_iterator end = insets.end();
1904 for (; iit != end; ++iit) {
1905 it.pos() = iit->pos;
1907 // is it a nested text inset?
1908 if (iit->inset->asInsetText()) {
1909 // Inset needs its own scope?
1910 InsetText const * itext
1911 = iit->inset->asInsetText();
1912 bool newScope = itext->isMacroScope();
1914 // scope which ends just behind the inset
1915 DocIterator insetScope = it;
1918 // collect macros in inset
1919 it.push_back(CursorSlice(*iit->inset));
1920 updateMacros(it, newScope ? insetScope : scope);
1925 // is it an external file?
1926 if (iit->inset->lyxCode() == INCLUDE_CODE) {
1927 // get buffer of external file
1928 InsetCommand const & inset
1929 = static_cast<InsetCommand const &>(*iit->inset);
1930 InsetCommandParams const & ip = inset.params();
1931 d->macro_lock = true;
1932 Buffer * child = loadIfNeeded(*this, ip);
1933 d->macro_lock = false;
1937 // register its position, but only when it is
1938 // included first in the buffer
1939 if (d->children_positions.find(child)
1940 == d->children_positions.end())
1941 d->children_positions[child] = it;
1943 // register child with its scope
1944 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
1948 if (iit->inset->lyxCode() != MATHMACRO_CODE)
1952 MathMacroTemplate & macroTemplate
1953 = static_cast<MathMacroTemplate &>(*iit->inset);
1954 MacroContext mc(*this, it);
1955 macroTemplate.updateToContext(mc);
1958 bool valid = macroTemplate.validMacro();
1959 // FIXME: Should be fixNameAndCheckIfValid() in fact,
1960 // then the BufferView's cursor will be invalid in
1961 // some cases which leads to crashes.
1966 d->macros[macroTemplate.name()][it] =
1967 Impl::ScopeMacro(scope, MacroData(*this, it));
1977 void Buffer::updateMacros() const
1982 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
1984 // start with empty table
1986 d->children_positions.clear();
1987 d->position_to_children.clear();
1989 // Iterate over buffer, starting with first paragraph
1990 // The scope must be bigger than any lookup DocIterator
1991 // later. For the global lookup, lastpit+1 is used, hence
1992 // we use lastpit+2 here.
1993 DocIterator it = par_iterator_begin();
1994 DocIterator outerScope = it;
1995 outerScope.pit() = outerScope.lastpit() + 2;
1996 updateMacros(it, outerScope);
2000 void Buffer::updateMacroInstances() const
2002 LYXERR(Debug::MACROS, "updateMacroInstances for "
2003 << d->filename.onlyFileName());
2004 DocIterator it = doc_iterator_begin(this);
2005 DocIterator end = doc_iterator_end(this);
2006 for (; it != end; it.forwardPos()) {
2007 // look for MathData cells in InsetMathNest insets
2008 Inset * inset = it.nextInset();
2012 InsetMath * minset = inset->asInsetMath();
2016 // update macro in all cells of the InsetMathNest
2017 DocIterator::idx_type n = minset->nargs();
2018 MacroContext mc = MacroContext(*this, it);
2019 for (DocIterator::idx_type i = 0; i < n; ++i) {
2020 MathData & data = minset->cell(i);
2021 data.updateMacros(0, mc);
2027 void Buffer::listMacroNames(MacroNameSet & macros) const
2032 d->macro_lock = true;
2034 // loop over macro names
2035 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2036 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2037 for (; nameIt != nameEnd; ++nameIt)
2038 macros.insert(nameIt->first);
2040 // loop over children
2041 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2042 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2043 for (; it != end; ++it)
2044 it->first->listMacroNames(macros);
2047 if (d->parent_buffer)
2048 d->parent_buffer->listMacroNames(macros);
2050 d->macro_lock = false;
2054 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2056 if (!d->parent_buffer)
2060 d->parent_buffer->listMacroNames(names);
2063 MacroNameSet::iterator it = names.begin();
2064 MacroNameSet::iterator end = names.end();
2065 for (; it != end; ++it) {
2067 MacroData const * data =
2068 d->parent_buffer->getMacro(*it, *this, false);
2070 macros.insert(data);
2072 // we cannot access the original MathMacroTemplate anymore
2073 // here to calls validate method. So we do its work here manually.
2074 // FIXME: somehow make the template accessible here.
2075 if (data->optionals() > 0)
2076 features.require("xargs");
2082 Buffer::References & Buffer::references(docstring const & label)
2084 if (d->parent_buffer)
2085 return const_cast<Buffer *>(masterBuffer())->references(label);
2087 RefCache::iterator it = d->ref_cache_.find(label);
2088 if (it != d->ref_cache_.end())
2089 return it->second.second;
2091 static InsetLabel const * dummy_il = 0;
2092 static References const dummy_refs;
2093 it = d->ref_cache_.insert(
2094 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2095 return it->second.second;
2099 Buffer::References const & Buffer::references(docstring const & label) const
2101 return const_cast<Buffer *>(this)->references(label);
2105 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2107 masterBuffer()->d->ref_cache_[label].first = il;
2111 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2113 return masterBuffer()->d->ref_cache_[label].first;
2117 void Buffer::clearReferenceCache() const
2119 if (!d->parent_buffer)
2120 d->ref_cache_.clear();
2124 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2127 //FIXME: This does not work for child documents yet.
2128 LASSERT(code == CITE_CODE, /**/);
2129 // Check if the label 'from' appears more than once
2130 vector<docstring> labels;
2132 BiblioInfo const & keys = masterBibInfo();
2133 BiblioInfo::const_iterator bit = keys.begin();
2134 BiblioInfo::const_iterator bend = keys.end();
2136 for (; bit != bend; ++bit)
2138 labels.push_back(bit->first);
2141 if (count(labels.begin(), labels.end(), from) > 1)
2144 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2145 if (it->lyxCode() == code) {
2146 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2147 docstring const oldValue = inset.getParam(paramName);
2148 if (oldValue == from)
2149 inset.setParam(paramName, to);
2155 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2156 pit_type par_end, bool full_source) const
2158 OutputParams runparams(¶ms().encoding());
2159 runparams.nice = true;
2160 runparams.flavor = OutputParams::LATEX;
2161 runparams.linelen = lyxrc.plaintext_linelen;
2162 // No side effect of file copying and image conversion
2163 runparams.dryrun = true;
2167 os << "% " << _("Preview source code") << "\n\n";
2168 d->texrow.newline();
2169 d->texrow.newline();
2171 writeDocBookSource(os, absFileName(), runparams, false);
2173 // latex or literate
2174 writeLaTeXSource(os, string(), runparams, true, true);
2176 runparams.par_begin = par_begin;
2177 runparams.par_end = par_end;
2178 if (par_begin + 1 == par_end) {
2180 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2184 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2185 convert<docstring>(par_begin),
2186 convert<docstring>(par_end - 1))
2189 d->texrow.newline();
2190 d->texrow.newline();
2191 // output paragraphs
2193 docbookParagraphs(paragraphs(), *this, os, runparams);
2195 // latex or literate
2196 latexParagraphs(*this, text(), os, d->texrow, runparams);
2201 ErrorList & Buffer::errorList(string const & type) const
2203 static ErrorList emptyErrorList;
2204 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2205 if (I == d->errorLists.end())
2206 return emptyErrorList;
2212 void Buffer::updateTocItem(std::string const & type,
2213 DocIterator const & dit) const
2216 gui_->updateTocItem(type, dit);
2220 void Buffer::structureChanged() const
2223 gui_->structureChanged();
2227 void Buffer::errors(string const & err) const
2234 void Buffer::message(docstring const & msg) const
2241 void Buffer::setBusy(bool on) const
2248 void Buffer::setReadOnly(bool on) const
2251 d->wa_->setReadOnly(on);
2255 void Buffer::updateTitles() const
2258 d->wa_->updateTitles();
2262 void Buffer::resetAutosaveTimers() const
2265 gui_->resetAutosaveTimers();
2269 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2278 class AutoSaveBuffer : public ForkedProcess {
2281 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2282 : buffer_(buffer), fname_(fname) {}
2284 virtual boost::shared_ptr<ForkedProcess> clone() const
2286 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2291 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2292 from_utf8(fname_.absFilename())));
2293 return run(DontWait);
2297 virtual int generateChild();
2299 Buffer const & buffer_;
2304 int AutoSaveBuffer::generateChild()
2306 // tmp_ret will be located (usually) in /tmp
2307 // will that be a problem?
2308 // Note that this calls ForkedCalls::fork(), so it's
2309 // ok cross-platform.
2310 pid_t const pid = fork();
2311 // If you want to debug the autosave
2312 // you should set pid to -1, and comment out the fork.
2313 if (pid != 0 && pid != -1)
2316 // pid = -1 signifies that lyx was unable
2317 // to fork. But we will do the save
2319 bool failed = false;
2320 FileName const tmp_ret = FileName::tempName("lyxauto");
2321 if (!tmp_ret.empty()) {
2322 buffer_.writeFile(tmp_ret);
2323 // assume successful write of tmp_ret
2324 if (!tmp_ret.moveTo(fname_))
2330 // failed to write/rename tmp_ret so try writing direct
2331 if (!buffer_.writeFile(fname_)) {
2332 // It is dangerous to do this in the child,
2333 // but safe in the parent, so...
2334 if (pid == -1) // emit message signal.
2335 buffer_.message(_("Autosave failed!"));
2339 if (pid == 0) // we are the child so...
2348 // Perfect target for a thread...
2349 void Buffer::autoSave() const
2351 if (isBakClean() || isReadonly()) {
2352 // We don't save now, but we'll try again later
2353 resetAutosaveTimers();
2357 // emit message signal.
2358 message(_("Autosaving current document..."));
2360 // create autosave filename
2361 string fname = filePath();
2363 fname += d->filename.onlyFileName();
2366 AutoSaveBuffer autosave(*this, FileName(fname));
2370 resetAutosaveTimers();
2374 string Buffer::bufferFormat() const
2380 if (params().encoding().package() == Encoding::japanese)
2386 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2387 string & result_file) const
2389 string backend_format;
2390 OutputParams runparams(¶ms().encoding());
2391 runparams.flavor = OutputParams::LATEX;
2392 runparams.linelen = lyxrc.plaintext_linelen;
2393 vector<string> backs = backends();
2394 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2395 // Get shortest path to format
2396 Graph::EdgePath path;
2397 for (vector<string>::const_iterator it = backs.begin();
2398 it != backs.end(); ++it) {
2399 Graph::EdgePath p = theConverters().getPath(*it, format);
2400 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2401 backend_format = *it;
2406 runparams.flavor = theConverters().getFlavor(path);
2408 Alert::error(_("Couldn't export file"),
2409 bformat(_("No information for exporting the format %1$s."),
2410 formats.prettyName(format)));
2414 backend_format = format;
2415 // FIXME: Don't hardcode format names here, but use a flag
2416 if (backend_format == "pdflatex")
2417 runparams.flavor = OutputParams::PDFLATEX;
2420 string filename = latexName(false);
2421 filename = addName(temppath(), filename);
2422 filename = changeExtension(filename,
2423 formats.extension(backend_format));
2426 updateMacroInstances();
2428 // Plain text backend
2429 if (backend_format == "text")
2430 writePlaintextFile(*this, FileName(filename), runparams);
2432 else if (backend_format == "lyx")
2433 writeFile(FileName(filename));
2435 else if (isDocBook()) {
2436 runparams.nice = !put_in_tempdir;
2437 makeDocBookFile(FileName(filename), runparams);
2440 else if (backend_format == format) {
2441 runparams.nice = true;
2442 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2444 } else if (!lyxrc.tex_allows_spaces
2445 && contains(filePath(), ' ')) {
2446 Alert::error(_("File name error"),
2447 _("The directory path to the document cannot contain spaces."));
2450 runparams.nice = false;
2451 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2455 string const error_type = (format == "program")
2456 ? "Build" : bufferFormat();
2457 ErrorList & error_list = d->errorLists[error_type];
2458 string const ext = formats.extension(format);
2459 FileName const tmp_result_file(changeExtension(filename, ext));
2460 bool const success = theConverters().convert(this, FileName(filename),
2461 tmp_result_file, FileName(absFileName()), backend_format, format,
2463 // Emit the signal to show the error list.
2464 if (format != backend_format)
2469 if (put_in_tempdir) {
2470 result_file = tmp_result_file.absFilename();
2474 result_file = changeExtension(absFileName(), ext);
2475 // We need to copy referenced files (e. g. included graphics
2476 // if format == "dvi") to the result dir.
2477 vector<ExportedFile> const files =
2478 runparams.exportdata->externalFiles(format);
2479 string const dest = onlyPath(result_file);
2480 CopyStatus status = SUCCESS;
2481 for (vector<ExportedFile>::const_iterator it = files.begin();
2482 it != files.end() && status != CANCEL; ++it) {
2483 string const fmt = formats.getFormatFromFile(it->sourceName);
2484 status = copyFile(fmt, it->sourceName,
2485 makeAbsPath(it->exportName, dest),
2486 it->exportName, status == FORCE);
2488 if (status == CANCEL) {
2489 message(_("Document export cancelled."));
2490 } else if (tmp_result_file.exists()) {
2491 // Finally copy the main file
2492 status = copyFile(format, tmp_result_file,
2493 FileName(result_file), result_file,
2495 message(bformat(_("Document exported as %1$s "
2497 formats.prettyName(format),
2498 makeDisplayPath(result_file)));
2500 // This must be a dummy converter like fax (bug 1888)
2501 message(bformat(_("Document exported as %1$s"),
2502 formats.prettyName(format)));
2509 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2512 return doExport(format, put_in_tempdir, result_file);
2516 bool Buffer::preview(string const & format) const
2519 if (!doExport(format, true, result_file))
2521 return formats.view(*this, FileName(result_file), format);
2525 bool Buffer::isExportable(string const & format) const
2527 vector<string> backs = backends();
2528 for (vector<string>::const_iterator it = backs.begin();
2529 it != backs.end(); ++it)
2530 if (theConverters().isReachable(*it, format))
2536 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2538 vector<string> backs = backends();
2539 vector<Format const *> result =
2540 theConverters().getReachable(backs[0], only_viewable, true);
2541 for (vector<string>::const_iterator it = backs.begin() + 1;
2542 it != backs.end(); ++it) {
2543 vector<Format const *> r =
2544 theConverters().getReachable(*it, only_viewable, false);
2545 result.insert(result.end(), r.begin(), r.end());
2551 vector<string> Buffer::backends() const
2554 if (params().baseClass()->isTeXClassAvailable()) {
2555 v.push_back(bufferFormat());
2556 // FIXME: Don't hardcode format names here, but use a flag
2557 if (v.back() == "latex")
2558 v.push_back("pdflatex");
2560 v.push_back("text");
2566 bool Buffer::readFileHelper(FileName const & s)
2568 // File information about normal file
2570 docstring const file = makeDisplayPath(s.absFilename(), 50);
2571 docstring text = bformat(_("The specified document\n%1$s"
2572 "\ncould not be read."), file);
2573 Alert::error(_("Could not read document"), text);
2577 // Check if emergency save file exists and is newer.
2578 FileName const e(s.absFilename() + ".emergency");
2580 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2581 docstring const file = makeDisplayPath(s.absFilename(), 20);
2582 docstring const text =
2583 bformat(_("An emergency save of the document "
2585 "Recover emergency save?"), file);
2586 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2587 _("&Recover"), _("&Load Original"),
2591 // the file is not saved if we load the emergency file.
2601 // Now check if autosave file is newer.
2602 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2604 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2605 docstring const file = makeDisplayPath(s.absFilename(), 20);
2606 docstring const text =
2607 bformat(_("The backup of the document "
2608 "%1$s is newer.\n\nLoad the "
2609 "backup instead?"), file);
2610 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2611 _("&Load backup"), _("Load &original"),
2615 // the file is not saved if we load the autosave file.
2619 // Here we delete the autosave
2630 bool Buffer::loadLyXFile(FileName const & s)
2632 if (s.isReadableFile()) {
2633 if (readFileHelper(s)) {
2634 lyxvc().file_found_hook(s);
2635 if (!s.isWritable())
2640 docstring const file = makeDisplayPath(s.absFilename(), 20);
2641 // Here we probably should run
2642 if (LyXVC::file_not_found_hook(s)) {
2643 docstring const text =
2644 bformat(_("Do you want to retrieve the document"
2645 " %1$s from version control?"), file);
2646 int const ret = Alert::prompt(_("Retrieve from version control?"),
2647 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2650 // How can we know _how_ to do the checkout?
2651 // With the current VC support it has to be,
2652 // a RCS file since CVS do not have special ,v files.
2654 return loadLyXFile(s);
2662 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2664 TeXErrors::Errors::const_iterator cit = terr.begin();
2665 TeXErrors::Errors::const_iterator end = terr.end();
2667 for (; cit != end; ++cit) {
2670 int errorRow = cit->error_in_line;
2671 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2677 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2678 } while (found && id_start == id_end && pos_start == pos_end);
2680 errorList.push_back(ErrorItem(cit->error_desc,
2681 cit->error_text, id_start, pos_start, pos_end));
2686 // FIXME: buf should should be const because updateLabels() modifies
2687 // the contents of the paragraphs.
2688 void Buffer::updateLabels(bool childonly) const
2690 // Use the master text class also for child documents
2691 Buffer const * const master = masterBuffer();
2692 DocumentClass const & textclass = master->params().documentClass();
2694 // keep the buffers to be children in this set. If the call from the
2695 // master comes back we can see which of them were actually seen (i.e.
2696 // via an InsetInclude). The remaining ones in the set need still be updated.
2697 static std::set<Buffer const *> bufToUpdate;
2699 // If this is a child document start with the master
2700 if (master != this) {
2701 bufToUpdate.insert(this);
2702 master->updateLabels(false);
2704 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
2705 if (bufToUpdate.find(this) == bufToUpdate.end())
2709 // start over the counters in the master
2710 textclass.counters().reset();
2713 // update will be done below for this buffer
2714 bufToUpdate.erase(this);
2716 // update all caches
2717 clearReferenceCache();
2718 inset().setBuffer(const_cast<Buffer &>(*this));
2721 Buffer & cbuf = const_cast<Buffer &>(*this);
2723 LASSERT(!text().paragraphs().empty(), /**/);
2726 ParIterator parit = cbuf.par_iterator_begin();
2727 updateLabels(parit);
2730 // TocBackend update will be done later.
2733 cbuf.tocBackend().update();
2735 cbuf.structureChanged();
2739 static depth_type getDepth(DocIterator const & it)
2741 depth_type depth = 0;
2742 for (size_t i = 0 ; i < it.depth() ; ++i)
2743 if (!it[i].inset().inMathed())
2744 depth += it[i].paragraph().getDepth() + 1;
2745 // remove 1 since the outer inset does not count
2749 static depth_type getItemDepth(ParIterator const & it)
2751 Paragraph const & par = *it;
2752 LabelType const labeltype = par.layout().labeltype;
2754 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
2757 // this will hold the lowest depth encountered up to now.
2758 depth_type min_depth = getDepth(it);
2759 ParIterator prev_it = it;
2762 --prev_it.top().pit();
2764 // start of nested inset: go to outer par
2766 if (prev_it.empty()) {
2767 // start of document: nothing to do
2772 // We search for the first paragraph with same label
2773 // that is not more deeply nested.
2774 Paragraph & prev_par = *prev_it;
2775 depth_type const prev_depth = getDepth(prev_it);
2776 if (labeltype == prev_par.layout().labeltype) {
2777 if (prev_depth < min_depth)
2778 return prev_par.itemdepth + 1;
2779 if (prev_depth == min_depth)
2780 return prev_par.itemdepth;
2782 min_depth = min(min_depth, prev_depth);
2783 // small optimization: if we are at depth 0, we won't
2784 // find anything else
2785 if (prev_depth == 0)
2791 static bool needEnumCounterReset(ParIterator const & it)
2793 Paragraph const & par = *it;
2794 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
2795 depth_type const cur_depth = par.getDepth();
2796 ParIterator prev_it = it;
2797 while (prev_it.pit()) {
2798 --prev_it.top().pit();
2799 Paragraph const & prev_par = *prev_it;
2800 if (prev_par.getDepth() <= cur_depth)
2801 return prev_par.layout().labeltype != LABEL_ENUMERATE;
2803 // start of nested inset: reset
2808 // set the label of a paragraph. This includes the counters.
2809 static void setLabel(Buffer const & buf, ParIterator & it)
2811 BufferParams const & bp = buf.masterBuffer()->params();
2812 DocumentClass const & textclass = bp.documentClass();
2813 Paragraph & par = it.paragraph();
2814 Layout const & layout = par.layout();
2815 Counters & counters = textclass.counters();
2817 if (par.params().startOfAppendix()) {
2818 // FIXME: only the counter corresponding to toplevel
2819 // sectionning should be reset
2821 counters.appendix(true);
2823 par.params().appendix(counters.appendix());
2825 // Compute the item depth of the paragraph
2826 par.itemdepth = getItemDepth(it);
2828 if (layout.margintype == MARGIN_MANUAL) {
2829 if (par.params().labelWidthString().empty())
2830 par.params().labelWidthString(par.translateIfPossible(layout.labelstring(), bp));
2832 par.params().labelWidthString(docstring());
2835 switch(layout.labeltype) {
2837 if (layout.toclevel <= bp.secnumdepth
2838 && (layout.latextype != LATEX_ENVIRONMENT
2839 || isFirstInSequence(it.pit(), it.plist()))) {
2840 counters.step(layout.counter);
2841 par.params().labelString(
2842 par.expandLabel(layout, bp));
2844 par.params().labelString(docstring());
2847 case LABEL_ITEMIZE: {
2848 // At some point of time we should do something more
2849 // clever here, like:
2850 // par.params().labelString(
2851 // bp.user_defined_bullet(par.itemdepth).getText());
2852 // for now, use a simple hardcoded label
2853 docstring itemlabel;
2854 switch (par.itemdepth) {
2856 itemlabel = char_type(0x2022);
2859 itemlabel = char_type(0x2013);
2862 itemlabel = char_type(0x2217);
2865 itemlabel = char_type(0x2219); // or 0x00b7
2868 par.params().labelString(itemlabel);
2872 case LABEL_ENUMERATE: {
2873 // FIXME: Yes I know this is a really, really! bad solution
2875 docstring enumcounter = from_ascii("enum");
2877 switch (par.itemdepth) {
2886 enumcounter += "iv";
2889 // not a valid enumdepth...
2893 // Maybe we have to reset the enumeration counter.
2894 if (needEnumCounterReset(it))
2895 counters.reset(enumcounter);
2897 counters.step(enumcounter);
2901 switch (par.itemdepth) {
2903 format = N_("\\arabic{enumi}.");
2906 format = N_("(\\alph{enumii})");
2909 format = N_("\\roman{enumiii}.");
2912 format = N_("\\Alph{enumiv}.");
2915 // not a valid enumdepth...
2919 par.params().labelString(counters.counterLabel(
2920 par.translateIfPossible(from_ascii(format), bp)));
2925 case LABEL_SENSITIVE: {
2926 string const & type = counters.current_float();
2927 docstring full_label;
2929 full_label = buf.B_("Senseless!!! ");
2931 docstring name = buf.B_(textclass.floats().getType(type).name());
2932 if (counters.hasCounter(from_utf8(type))) {
2933 counters.step(from_utf8(type));
2934 full_label = bformat(from_ascii("%1$s %2$s:"),
2936 counters.theCounter(from_utf8(type)));
2938 full_label = bformat(from_ascii("%1$s #:"), name);
2940 par.params().labelString(full_label);
2944 case LABEL_NO_LABEL:
2945 par.params().labelString(docstring());
2949 case LABEL_TOP_ENVIRONMENT:
2950 case LABEL_CENTERED_TOP_ENVIRONMENT:
2953 par.params().labelString(
2954 par.translateIfPossible(layout.labelstring(), bp));
2960 void Buffer::updateLabels(ParIterator & parit) const
2962 LASSERT(parit.pit() == 0, /**/);
2964 // set the position of the text in the buffer to be able
2965 // to resolve macros in it. This has nothing to do with
2966 // labels, but by putting it here we avoid implementing
2967 // a whole bunch of traversal routines just for this call.
2968 parit.text()->setMacrocontextPosition(parit);
2970 depth_type maxdepth = 0;
2971 pit_type const lastpit = parit.lastpit();
2972 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
2973 // reduce depth if necessary
2974 parit->params().depth(min(parit->params().depth(), maxdepth));
2975 maxdepth = parit->getMaxDepthAfter();
2977 // set the counter for this paragraph
2978 setLabel(*this, parit);
2981 InsetList::const_iterator iit = parit->insetList().begin();
2982 InsetList::const_iterator end = parit->insetList().end();
2983 for (; iit != end; ++iit) {
2984 parit.pos() = iit->pos;
2985 iit->inset->updateLabels(parit);