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>
109 using namespace std::tr1;
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;
131 Impl(Buffer & parent, FileName const & file, bool readonly);
145 mutable TexRow texrow;
146 Buffer const * parent_buffer;
148 /// need to regenerate .tex?
152 mutable bool lyx_clean;
154 /// is autosave needed?
155 mutable bool bak_clean;
157 /// is this a unnamed file (New...)?
163 /// name of the file the buffer is associated with.
166 /** Set to true only when the file is fully loaded.
167 * Used to prevent the premature generation of previews
168 * and by the citation inset.
170 bool file_fully_loaded;
173 mutable TocBackend toc_backend;
176 typedef pair<DocIterator, MacroData> ScopeMacro;
177 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
178 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
179 /// map from the macro name to the position map,
180 /// which maps the macro definition position to the scope and the MacroData.
181 NamePositionScopeMacroMap macros;
184 /// positions of child buffers in the buffer
185 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
186 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
187 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
188 /// position of children buffers in this buffer
189 BufferPositionMap children_positions;
190 /// map from children inclusion positions to their scope and their buffer
191 PositionScopeBufferMap position_to_children;
193 /// Container for all sort of Buffer dependant errors.
194 map<string, ErrorList> errorLists;
196 /// timestamp and checksum used to test if the file has been externally
197 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
199 unsigned long checksum_;
202 frontend::WorkAreaManager * wa_;
207 /// A cache for the bibfiles (including bibfiles of loaded child
208 /// documents), needed for appropriate update of natbib labels.
209 mutable support::FileNameList bibfilesCache_;
211 // FIXME The caching mechanism could be improved. At present, we have a
212 // cache for each Buffer, that caches all the bibliography info for that
213 // Buffer. A more efficient solution would be to have a global cache per
214 // file, and then to construct the Buffer's bibinfo from that.
215 /// A cache for bibliography info
216 mutable BiblioInfo bibinfo_;
217 /// whether the bibinfo cache is valid
218 bool bibinfoCacheValid_;
219 /// Cache of timestamps of .bib files
220 map<FileName, time_t> bibfileStatus_;
222 mutable RefCache ref_cache_;
224 /// our Text that should be wrapped in an InsetText
229 /// Creates the per buffer temporary directory
230 static FileName createBufferTmpDir()
233 // We are in our own directory. Why bother to mangle name?
234 // In fact I wrote this code to circumvent a problematic behaviour
235 // (bug?) of EMX mkstemp().
236 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
237 convert<string>(count++));
239 if (!tmpfl.createDirectory(0777)) {
240 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
241 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
242 from_utf8(tmpfl.absFilename())));
248 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
249 : parent_buffer(0), lyx_clean(true), bak_clean(true), unnamed(false),
250 read_only(readonly_), filename(file), file_fully_loaded(false),
251 toc_backend(&parent), macro_lock(false), timestamp_(0),
252 checksum_(0), wa_(0), undo_(parent), bibinfoCacheValid_(false)
254 temppath = createBufferTmpDir();
255 lyxvc.setBuffer(&parent);
257 wa_ = new frontend::WorkAreaManager;
261 Buffer::Buffer(string const & file, bool readonly)
262 : d(new Impl(*this, FileName(file), readonly)), gui_(0)
264 LYXERR(Debug::INFO, "Buffer::Buffer()");
266 d->inset = new InsetText(*this);
267 d->inset->setAutoBreakRows(true);
268 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
274 LYXERR(Debug::INFO, "Buffer::~Buffer()");
275 // here the buffer should take care that it is
276 // saved properly, before it goes into the void.
278 // GuiView already destroyed
281 if (d->unnamed && d->filename.extension() == "internal") {
282 // No need to do additional cleanups for internal buffer.
287 // loop over children
288 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
289 Impl::BufferPositionMap::iterator end = d->children_positions.end();
290 for (; it != end; ++it)
291 theBufferList().releaseChild(this, const_cast<Buffer *>(it->first));
293 // clear references to children in macro tables
294 d->children_positions.clear();
295 d->position_to_children.clear();
297 if (!d->temppath.destroyDirectory()) {
298 Alert::warning(_("Could not remove temporary directory"),
299 bformat(_("Could not remove the temporary directory %1$s"),
300 from_utf8(d->temppath.absFilename())));
303 // Remove any previewed LaTeX snippets associated with this buffer.
304 thePreviews().removeLoader(*this);
310 void Buffer::changed() const
317 frontend::WorkAreaManager & Buffer::workAreaManager() const
319 LASSERT(d->wa_, /**/);
324 Text & Buffer::text() const
326 return d->inset->text();
330 Inset & Buffer::inset() const
336 BufferParams & Buffer::params()
342 BufferParams const & Buffer::params() const
348 ParagraphList & Buffer::paragraphs()
350 return text().paragraphs();
354 ParagraphList const & Buffer::paragraphs() const
356 return text().paragraphs();
360 LyXVC & Buffer::lyxvc()
366 LyXVC const & Buffer::lyxvc() const
372 string const Buffer::temppath() const
374 return d->temppath.absFilename();
378 TexRow const & Buffer::texrow() const
384 TocBackend & Buffer::tocBackend() const
386 return d->toc_backend;
390 Undo & Buffer::undo()
396 string Buffer::latexName(bool const no_path) const
398 FileName latex_name = makeLatexName(d->filename);
399 return no_path ? latex_name.onlyFileName()
400 : latex_name.absFilename();
404 string Buffer::logName(LogType * type) const
406 string const filename = latexName(false);
408 if (filename.empty()) {
414 string const path = temppath();
416 FileName const fname(addName(temppath(),
417 onlyFilename(changeExtension(filename,
419 FileName const bname(
420 addName(path, onlyFilename(
421 changeExtension(filename,
422 formats.extension("literate") + ".out"))));
424 // If no Latex log or Build log is newer, show Build log
426 if (bname.exists() &&
427 (!fname.exists() || fname.lastModified() < bname.lastModified())) {
428 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
431 return bname.absFilename();
433 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
436 return fname.absFilename();
440 void Buffer::setReadonly(bool const flag)
442 if (d->read_only != flag) {
449 void Buffer::setFileName(string const & newfile)
451 d->filename = makeAbsPath(newfile);
452 setReadonly(d->filename.isReadOnly());
457 int Buffer::readHeader(Lexer & lex)
459 int unknown_tokens = 0;
461 int begin_header_line = -1;
463 // Initialize parameters that may be/go lacking in header:
464 params().branchlist().clear();
465 params().preamble.erase();
466 params().options.erase();
467 params().master.erase();
468 params().float_placement.erase();
469 params().paperwidth.erase();
470 params().paperheight.erase();
471 params().leftmargin.erase();
472 params().rightmargin.erase();
473 params().topmargin.erase();
474 params().bottommargin.erase();
475 params().headheight.erase();
476 params().headsep.erase();
477 params().footskip.erase();
478 params().columnsep.erase();
479 params().fontsCJK.erase();
480 params().listings_params.clear();
481 params().clearLayoutModules();
482 params().clearRemovedModules();
483 params().pdfoptions().clear();
485 for (int i = 0; i < 4; ++i) {
486 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
487 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
490 ErrorList & errorList = d->errorLists["Parse"];
499 if (token == "\\end_header")
503 if (token == "\\begin_header") {
504 begin_header_line = line;
508 LYXERR(Debug::PARSER, "Handling document header token: `"
511 string unknown = params().readToken(lex, token, d->filename.onlyPath());
512 if (!unknown.empty()) {
513 if (unknown[0] != '\\' && token == "\\textclass") {
514 Alert::warning(_("Unknown document class"),
515 bformat(_("Using the default document class, because the "
516 "class %1$s is unknown."), from_utf8(unknown)));
519 docstring const s = bformat(_("Unknown token: "
523 errorList.push_back(ErrorItem(_("Document header error"),
528 if (begin_header_line) {
529 docstring const s = _("\\begin_header is missing");
530 errorList.push_back(ErrorItem(_("Document header error"),
534 params().makeDocumentClass();
536 return unknown_tokens;
541 // changed to be public and have one parameter
542 // Returns false if "\end_document" is not read (Asger)
543 bool Buffer::readDocument(Lexer & lex)
545 ErrorList & errorList = d->errorLists["Parse"];
548 if (!lex.checkFor("\\begin_document")) {
549 docstring const s = _("\\begin_document is missing");
550 errorList.push_back(ErrorItem(_("Document header error"),
554 // we are reading in a brand new document
555 LASSERT(paragraphs().empty(), /**/);
559 if (params().outputChanges) {
560 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
561 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
562 LaTeXFeatures::isAvailable("xcolor");
564 if (!dvipost && !xcolorsoul) {
565 Alert::warning(_("Changes not shown in LaTeX output"),
566 _("Changes will not be highlighted in LaTeX output, "
567 "because neither dvipost nor xcolor/soul are installed.\n"
568 "Please install these packages or redefine "
569 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
570 } else if (!xcolorsoul) {
571 Alert::warning(_("Changes not shown in LaTeX output"),
572 _("Changes will not be highlighted in LaTeX output "
573 "when using pdflatex, because xcolor and soul are not installed.\n"
574 "Please install both packages or redefine "
575 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
579 if (!params().master.empty()) {
580 FileName const master_file = makeAbsPath(params().master,
581 onlyPath(absFileName()));
582 if (isLyXFilename(master_file.absFilename())) {
583 Buffer * master = checkAndLoadLyXFile(master_file);
584 d->parent_buffer = master;
589 bool const res = text().read(*this, lex, errorList, d->inset);
592 updateMacroInstances();
597 // needed to insert the selection
598 void Buffer::insertStringAsLines(ParagraphList & pars,
599 pit_type & pit, pos_type & pos,
600 Font const & fn, docstring const & str, bool autobreakrows)
604 // insert the string, don't insert doublespace
605 bool space_inserted = true;
606 for (docstring::const_iterator cit = str.begin();
607 cit != str.end(); ++cit) {
608 Paragraph & par = pars[pit];
610 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
611 breakParagraph(params(), pars, pit, pos,
612 par.layout().isEnvironment());
615 space_inserted = true;
619 // do not insert consecutive spaces if !free_spacing
620 } else if ((*cit == ' ' || *cit == '\t') &&
621 space_inserted && !par.isFreeSpacing()) {
623 } else if (*cit == '\t') {
624 if (!par.isFreeSpacing()) {
625 // tabs are like spaces here
626 par.insertChar(pos, ' ', font, params().trackChanges);
628 space_inserted = true;
630 par.insertChar(pos, *cit, font, params().trackChanges);
632 space_inserted = true;
634 } else if (!isPrintable(*cit)) {
635 // Ignore unprintables
638 // just insert the character
639 par.insertChar(pos, *cit, font, params().trackChanges);
641 space_inserted = (*cit == ' ');
648 bool Buffer::readString(string const & s)
650 params().compressed = false;
652 // remove dummy empty par
653 paragraphs().clear();
657 FileName const name = FileName::tempName("Buffer_readString");
658 switch (readFile(lex, name, true)) {
662 // We need to call lyx2lyx, so write the input to a file
663 ofstream os(name.toFilesystemEncoding().c_str());
666 return readFile(name);
676 bool Buffer::readFile(FileName const & filename)
678 FileName fname(filename);
680 // remove dummy empty par
681 paragraphs().clear();
684 if (readFile(lex, fname) != success)
691 bool Buffer::isFullyLoaded() const
693 return d->file_fully_loaded;
697 void Buffer::setFullyLoaded(bool value)
699 d->file_fully_loaded = value;
703 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
706 LASSERT(!filename.empty(), /**/);
708 // the first (non-comment) token _must_ be...
709 if (!lex.checkFor("\\lyxformat")) {
710 Alert::error(_("Document format failure"),
711 bformat(_("%1$s is not a readable LyX document."),
712 from_utf8(filename.absFilename())));
718 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
719 // if present remove ".," from string.
720 size_t dot = tmp_format.find_first_of(".,");
721 //lyxerr << " dot found at " << dot << endl;
722 if (dot != string::npos)
723 tmp_format.erase(dot, 1);
724 int const file_format = convert<int>(tmp_format);
725 //lyxerr << "format: " << file_format << endl;
727 // save timestamp and checksum of the original disk file, making sure
728 // to not overwrite them with those of the file created in the tempdir
729 // when it has to be converted to the current format.
731 // Save the timestamp and checksum of disk file. If filename is an
732 // emergency file, save the timestamp and checksum of the original lyx file
733 // because isExternallyModified will check for this file. (BUG4193)
734 string diskfile = filename.absFilename();
735 if (suffixIs(diskfile, ".emergency"))
736 diskfile = diskfile.substr(0, diskfile.size() - 10);
737 saveCheckSum(FileName(diskfile));
740 if (file_format != LYX_FORMAT) {
743 // lyx2lyx would fail
746 FileName const tmpfile = FileName::tempName("Buffer_readFile");
747 if (tmpfile.empty()) {
748 Alert::error(_("Conversion failed"),
749 bformat(_("%1$s is from a different"
750 " version of LyX, but a temporary"
751 " file for converting it could"
753 from_utf8(filename.absFilename())));
756 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
757 if (lyx2lyx.empty()) {
758 Alert::error(_("Conversion script not found"),
759 bformat(_("%1$s is from a different"
760 " version of LyX, but the"
761 " conversion script lyx2lyx"
762 " could not be found."),
763 from_utf8(filename.absFilename())));
766 ostringstream command;
767 command << os::python()
768 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
769 << " -t " << convert<string>(LYX_FORMAT)
770 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
771 << ' ' << quoteName(filename.toFilesystemEncoding());
772 string const command_str = command.str();
774 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
776 cmd_ret const ret = runCommand(command_str);
777 if (ret.first != 0) {
778 Alert::error(_("Conversion script failed"),
779 bformat(_("%1$s is from a different version"
780 " of LyX, but the lyx2lyx script"
781 " failed to convert it."),
782 from_utf8(filename.absFilename())));
785 bool const ret = readFile(tmpfile);
786 // Do stuff with tmpfile name and buffer name here.
787 return ret ? success : failure;
792 if (readDocument(lex)) {
793 Alert::error(_("Document format failure"),
794 bformat(_("%1$s ended unexpectedly, which means"
795 " that it is probably corrupted."),
796 from_utf8(filename.absFilename())));
799 d->file_fully_loaded = true;
804 // Should probably be moved to somewhere else: BufferView? LyXView?
805 bool Buffer::save() const
807 // We don't need autosaves in the immediate future. (Asger)
808 resetAutosaveTimers();
810 string const encodedFilename = d->filename.toFilesystemEncoding();
813 bool madeBackup = false;
815 // make a backup if the file already exists
816 if (lyxrc.make_backup && fileName().exists()) {
817 backupName = FileName(absFileName() + '~');
818 if (!lyxrc.backupdir_path.empty()) {
819 string const mangledName =
820 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
821 backupName = FileName(addName(lyxrc.backupdir_path,
824 if (fileName().copyTo(backupName)) {
827 Alert::error(_("Backup failure"),
828 bformat(_("Cannot create backup file %1$s.\n"
829 "Please check whether the directory exists and is writeable."),
830 from_utf8(backupName.absFilename())));
831 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
835 // ask if the disk file has been externally modified (use checksum method)
836 if (fileName().exists() && isExternallyModified(checksum_method)) {
837 docstring const file = makeDisplayPath(absFileName(), 20);
838 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
839 "you want to overwrite this file?"), file);
840 int const ret = Alert::prompt(_("Overwrite modified file?"),
841 text, 1, 1, _("&Overwrite"), _("&Cancel"));
846 if (writeFile(d->filename)) {
850 // Saving failed, so backup is not backup
852 backupName.moveTo(d->filename);
858 bool Buffer::writeFile(FileName const & fname) const
860 if (d->read_only && fname == d->filename)
865 docstring const str = bformat(_("Saving document %1$s..."),
866 makeDisplayPath(fname.absFilename()));
869 if (params().compressed) {
870 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
871 retval = ofs && write(ofs);
873 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
874 retval = ofs && write(ofs);
878 message(str + _(" could not write file!"));
882 removeAutosaveFile(d->filename.absFilename());
884 saveCheckSum(d->filename);
885 message(str + _(" done."));
891 bool Buffer::write(ostream & ofs) const
894 // Use the standard "C" locale for file output.
895 ofs.imbue(locale::classic());
898 // The top of the file should not be written by params().
900 // write out a comment in the top of the file
901 ofs << "#LyX " << lyx_version
902 << " created this file. For more info see http://www.lyx.org/\n"
903 << "\\lyxformat " << LYX_FORMAT << "\n"
904 << "\\begin_document\n";
906 /// For each author, set 'used' to true if there is a change
907 /// by this author in the document; otherwise set it to 'false'.
908 AuthorList::Authors::const_iterator a_it = params().authors().begin();
909 AuthorList::Authors::const_iterator a_end = params().authors().end();
910 for (; a_it != a_end; ++a_it)
911 a_it->second.setUsed(false);
913 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
914 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
915 for ( ; it != end; ++it)
916 it->checkAuthors(params().authors());
918 // now write out the buffer parameters.
919 ofs << "\\begin_header\n";
920 params().writeFile(ofs);
921 ofs << "\\end_header\n";
924 ofs << "\n\\begin_body\n";
925 text().write(*this, ofs);
926 ofs << "\n\\end_body\n";
928 // Write marker that shows file is complete
929 ofs << "\\end_document" << endl;
931 // Shouldn't really be needed....
934 // how to check if close went ok?
935 // Following is an attempt... (BE 20001011)
937 // good() returns false if any error occured, including some
939 // bad() returns true if something bad happened in the buffer,
940 // which should include file system full errors.
945 lyxerr << "File was not closed properly." << endl;
952 bool Buffer::makeLaTeXFile(FileName const & fname,
953 string const & original_path,
954 OutputParams const & runparams,
955 bool output_preamble, bool output_body) const
957 string const encoding = runparams.encoding->iconvName();
958 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
961 try { ofs.reset(encoding); }
962 catch (iconv_codecvt_facet_exception & e) {
963 lyxerr << "Caught iconv exception: " << e.what() << endl;
964 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
965 "verify that the support software for your encoding (%1$s) is "
966 "properly installed"), from_ascii(encoding)));
969 if (!openFileWrite(ofs, fname))
972 //TexStream ts(ofs.rdbuf(), &texrow());
973 ErrorList & errorList = d->errorLists["Export"];
975 bool failed_export = false;
978 writeLaTeXSource(ofs, original_path,
979 runparams, output_preamble, output_body);
981 catch (EncodingException & e) {
982 odocstringstream ods;
983 ods.put(e.failed_char);
985 oss << "0x" << hex << e.failed_char << dec;
986 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
987 " (code point %2$s)"),
988 ods.str(), from_utf8(oss.str()));
989 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
990 "representable in the chosen encoding.\n"
991 "Changing the document encoding to utf8 could help."),
992 e.par_id, e.pos, e.pos + 1));
993 failed_export = true;
995 catch (iconv_codecvt_facet_exception & e) {
996 errorList.push_back(ErrorItem(_("iconv conversion failed"),
997 _(e.what()), -1, 0, 0));
998 failed_export = true;
1000 catch (exception const & e) {
1001 errorList.push_back(ErrorItem(_("conversion failed"),
1002 _(e.what()), -1, 0, 0));
1003 failed_export = true;
1006 lyxerr << "Caught some really weird exception..." << endl;
1012 failed_export = true;
1013 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1017 return !failed_export;
1021 void Buffer::writeLaTeXSource(odocstream & os,
1022 string const & original_path,
1023 OutputParams const & runparams_in,
1024 bool const output_preamble, bool const output_body) const
1026 // The child documents, if any, shall be already loaded at this point.
1028 OutputParams runparams = runparams_in;
1030 // Classify the unicode characters appearing in math insets
1031 Encodings::initUnicodeMath(*this);
1033 // validate the buffer.
1034 LYXERR(Debug::LATEX, " Validating buffer...");
1035 LaTeXFeatures features(*this, params(), runparams);
1037 LYXERR(Debug::LATEX, " Buffer validation done.");
1039 // The starting paragraph of the coming rows is the
1040 // first paragraph of the document. (Asger)
1041 if (output_preamble && runparams.nice) {
1042 os << "%% LyX " << lyx_version << " created this file. "
1043 "For more info, see http://www.lyx.org/.\n"
1044 "%% Do not edit unless you really know what "
1046 d->texrow.newline();
1047 d->texrow.newline();
1049 LYXERR(Debug::INFO, "lyx document header finished");
1051 // Don't move this behind the parent_buffer=0 code below,
1052 // because then the macros will not get the right "redefinition"
1053 // flag as they don't see the parent macros which are output before.
1056 // fold macros if possible, still with parent buffer as the
1057 // macros will be put in the prefix anyway.
1058 updateMacroInstances();
1060 // There are a few differences between nice LaTeX and usual files:
1061 // usual is \batchmode and has a
1062 // special input@path to allow the including of figures
1063 // with either \input or \includegraphics (what figinsets do).
1064 // input@path is set when the actual parameter
1065 // original_path is set. This is done for usual tex-file, but not
1066 // for nice-latex-file. (Matthias 250696)
1067 // Note that input@path is only needed for something the user does
1068 // in the preamble, included .tex files or ERT, files included by
1069 // LyX work without it.
1070 if (output_preamble) {
1071 if (!runparams.nice) {
1072 // code for usual, NOT nice-latex-file
1073 os << "\\batchmode\n"; // changed
1074 // from \nonstopmode
1075 d->texrow.newline();
1077 if (!original_path.empty()) {
1079 // We don't know the encoding of inputpath
1080 docstring const inputpath = from_utf8(latex_path(original_path));
1081 os << "\\makeatletter\n"
1082 << "\\def\\input@path{{"
1083 << inputpath << "/}}\n"
1084 << "\\makeatother\n";
1085 d->texrow.newline();
1086 d->texrow.newline();
1087 d->texrow.newline();
1090 // get parent macros (if this buffer has a parent) which will be
1091 // written at the document begin further down.
1092 MacroSet parentMacros;
1093 listParentMacros(parentMacros, features);
1095 // Write the preamble
1096 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1098 runparams.use_japanese = features.isRequired("japanese");
1104 os << "\\begin{document}\n";
1105 d->texrow.newline();
1107 // output the parent macros
1108 MacroSet::iterator it = parentMacros.begin();
1109 MacroSet::iterator end = parentMacros.end();
1110 for (; it != end; ++it)
1111 (*it)->write(os, true);
1112 } // output_preamble
1114 d->texrow.start(paragraphs().begin()->id(), 0);
1116 LYXERR(Debug::INFO, "preamble finished, now the body.");
1118 // if we are doing a real file with body, even if this is the
1119 // child of some other buffer, let's cut the link here.
1120 // This happens for example if only a child document is printed.
1121 Buffer const * save_parent = 0;
1122 if (output_preamble) {
1123 save_parent = d->parent_buffer;
1124 d->parent_buffer = 0;
1128 latexParagraphs(*this, text(), os, d->texrow, runparams);
1130 // Restore the parenthood if needed
1131 if (output_preamble)
1132 d->parent_buffer = save_parent;
1134 // add this just in case after all the paragraphs
1136 d->texrow.newline();
1138 if (output_preamble) {
1139 os << "\\end{document}\n";
1140 d->texrow.newline();
1141 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1143 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1145 runparams_in.encoding = runparams.encoding;
1147 // Just to be sure. (Asger)
1148 d->texrow.newline();
1150 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1151 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1155 bool Buffer::isLatex() const
1157 return params().documentClass().outputType() == LATEX;
1161 bool Buffer::isLiterate() const
1163 return params().documentClass().outputType() == LITERATE;
1167 bool Buffer::isDocBook() const
1169 return params().documentClass().outputType() == DOCBOOK;
1173 void Buffer::makeDocBookFile(FileName const & fname,
1174 OutputParams const & runparams,
1175 bool const body_only) const
1177 LYXERR(Debug::LATEX, "makeDocBookFile...");
1180 if (!openFileWrite(ofs, fname))
1183 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1187 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1191 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1192 OutputParams const & runparams,
1193 bool const only_body) const
1195 LaTeXFeatures features(*this, params(), runparams);
1200 DocumentClass const & tclass = params().documentClass();
1201 string const top_element = tclass.latexname();
1204 if (runparams.flavor == OutputParams::XML)
1205 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1208 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1211 if (! tclass.class_header().empty())
1212 os << from_ascii(tclass.class_header());
1213 else if (runparams.flavor == OutputParams::XML)
1214 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1215 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1217 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1219 docstring preamble = from_utf8(params().preamble);
1220 if (runparams.flavor != OutputParams::XML ) {
1221 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1222 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1223 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1224 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1227 string const name = runparams.nice
1228 ? changeExtension(absFileName(), ".sgml") : fname;
1229 preamble += features.getIncludedFiles(name);
1230 preamble += features.getLyXSGMLEntities();
1232 if (!preamble.empty()) {
1233 os << "\n [ " << preamble << " ]";
1238 string top = top_element;
1240 if (runparams.flavor == OutputParams::XML)
1241 top += params().language->code();
1243 top += params().language->code().substr(0, 2);
1246 if (!params().options.empty()) {
1248 top += params().options;
1251 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1252 << " file was created by LyX " << lyx_version
1253 << "\n See http://www.lyx.org/ for more information -->\n";
1255 params().documentClass().counters().reset();
1259 sgml::openTag(os, top);
1261 docbookParagraphs(paragraphs(), *this, os, runparams);
1262 sgml::closeTag(os, top_element);
1266 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1267 // Other flags: -wall -v0 -x
1268 int Buffer::runChktex()
1272 // get LaTeX-Filename
1273 FileName const path(temppath());
1274 string const name = addName(path.absFilename(), latexName());
1275 string const org_path = filePath();
1277 PathChanger p(path); // path to LaTeX file
1278 message(_("Running chktex..."));
1280 // Generate the LaTeX file if neccessary
1281 OutputParams runparams(¶ms().encoding());
1282 runparams.flavor = OutputParams::LATEX;
1283 runparams.nice = false;
1284 makeLaTeXFile(FileName(name), org_path, runparams);
1287 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1288 int const res = chktex.run(terr); // run chktex
1291 Alert::error(_("chktex failure"),
1292 _("Could not run chktex successfully."));
1293 } else if (res > 0) {
1294 ErrorList & errlist = d->errorLists["ChkTeX"];
1296 bufferErrors(terr, errlist);
1307 void Buffer::validate(LaTeXFeatures & features) const
1309 params().validate(features);
1313 for_each(paragraphs().begin(), paragraphs().end(),
1314 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1316 if (lyxerr.debugging(Debug::LATEX)) {
1317 features.showStruct();
1322 void Buffer::getLabelList(vector<docstring> & list) const
1324 // If this is a child document, use the parent's list instead.
1325 if (d->parent_buffer) {
1326 d->parent_buffer->getLabelList(list);
1331 Toc & toc = d->toc_backend.toc("label");
1332 TocIterator toc_it = toc.begin();
1333 TocIterator end = toc.end();
1334 for (; toc_it != end; ++toc_it) {
1335 if (toc_it->depth() == 0)
1336 list.push_back(toc_it->str());
1341 void Buffer::updateBibfilesCache() const
1343 // If this is a child document, use the parent's cache instead.
1344 if (d->parent_buffer) {
1345 d->parent_buffer->updateBibfilesCache();
1349 d->bibfilesCache_.clear();
1350 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1351 if (it->lyxCode() == BIBTEX_CODE) {
1352 InsetBibtex const & inset =
1353 static_cast<InsetBibtex const &>(*it);
1354 support::FileNameList const bibfiles = inset.getBibFiles();
1355 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1358 } else if (it->lyxCode() == INCLUDE_CODE) {
1359 InsetInclude & inset =
1360 static_cast<InsetInclude &>(*it);
1361 inset.updateBibfilesCache();
1362 support::FileNameList const & bibfiles =
1363 inset.getBibfilesCache(*this);
1364 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1369 // the bibinfo cache is now invalid
1370 d->bibinfoCacheValid_ = false;
1374 void Buffer::invalidateBibinfoCache()
1376 d->bibinfoCacheValid_ = false;
1380 support::FileNameList const & Buffer::getBibfilesCache() const
1382 // If this is a child document, use the parent's cache instead.
1383 if (d->parent_buffer)
1384 return d->parent_buffer->getBibfilesCache();
1386 // We update the cache when first used instead of at loading time.
1387 if (d->bibfilesCache_.empty())
1388 const_cast<Buffer *>(this)->updateBibfilesCache();
1390 return d->bibfilesCache_;
1394 BiblioInfo const & Buffer::masterBibInfo() const
1396 // if this is a child document and the parent is already loaded
1397 // use the parent's list instead [ale990412]
1398 Buffer const * const tmp = masterBuffer();
1401 return tmp->masterBibInfo();
1402 return localBibInfo();
1406 BiblioInfo const & Buffer::localBibInfo() const
1408 if (d->bibinfoCacheValid_) {
1409 support::FileNameList const & bibfilesCache = getBibfilesCache();
1410 // compare the cached timestamps with the actual ones.
1411 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1412 support::FileNameList::const_iterator en = bibfilesCache.end();
1413 for (; ei != en; ++ ei) {
1414 time_t lastw = ei->lastModified();
1415 if (lastw != d->bibfileStatus_[*ei]) {
1416 d->bibinfoCacheValid_ = false;
1417 d->bibfileStatus_[*ei] = lastw;
1423 if (!d->bibinfoCacheValid_) {
1424 d->bibinfo_.clear();
1425 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1426 it->fillWithBibKeys(d->bibinfo_, it);
1427 d->bibinfoCacheValid_ = true;
1433 bool Buffer::isDepClean(string const & name) const
1435 DepClean::const_iterator const it = d->dep_clean.find(name);
1436 if (it == d->dep_clean.end())
1442 void Buffer::markDepClean(string const & name)
1444 d->dep_clean[name] = true;
1448 bool Buffer::dispatch(string const & command, bool * result)
1450 return dispatch(lyxaction.lookupFunc(command), result);
1454 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1456 bool dispatched = true;
1458 switch (func.action) {
1459 case LFUN_BUFFER_EXPORT: {
1460 bool const tmp = doExport(to_utf8(func.argument()), false);
1466 case LFUN_BRANCH_ACTIVATE:
1467 case LFUN_BRANCH_DEACTIVATE: {
1468 BranchList & branchList = params().branchlist();
1469 docstring const branchName = func.argument();
1470 Branch * branch = branchList.find(branchName);
1472 LYXERR0("Branch " << branchName << " does not exist.");
1474 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1486 void Buffer::changeLanguage(Language const * from, Language const * to)
1488 LASSERT(from, /**/);
1491 for_each(par_iterator_begin(),
1493 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1497 bool Buffer::isMultiLingual() const
1499 ParConstIterator end = par_iterator_end();
1500 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1501 if (it->isMultiLingual(params()))
1508 DocIterator Buffer::getParFromID(int const id) const
1511 // John says this is called with id == -1 from undo
1512 lyxerr << "getParFromID(), id: " << id << endl;
1513 return doc_iterator_end(inset());
1516 for (DocIterator it = doc_iterator_begin(inset()); !it.atEnd(); it.forwardPar())
1517 if (it.paragraph().id() == id)
1520 return doc_iterator_end(inset());
1524 bool Buffer::hasParWithID(int const id) const
1526 return !getParFromID(id).atEnd();
1530 ParIterator Buffer::par_iterator_begin()
1532 return ParIterator(doc_iterator_begin(inset()));
1536 ParIterator Buffer::par_iterator_end()
1538 return ParIterator(doc_iterator_end(inset()));
1542 ParConstIterator Buffer::par_iterator_begin() const
1544 return lyx::par_const_iterator_begin(inset());
1548 ParConstIterator Buffer::par_iterator_end() const
1550 return lyx::par_const_iterator_end(inset());
1554 Language const * Buffer::language() const
1556 return params().language;
1560 docstring const Buffer::B_(string const & l10n) const
1562 return params().B_(l10n);
1566 bool Buffer::isClean() const
1568 return d->lyx_clean;
1572 bool Buffer::isBakClean() const
1574 return d->bak_clean;
1578 bool Buffer::isExternallyModified(CheckMethod method) const
1580 LASSERT(d->filename.exists(), /**/);
1581 // if method == timestamp, check timestamp before checksum
1582 return (method == checksum_method
1583 || d->timestamp_ != d->filename.lastModified())
1584 && d->checksum_ != d->filename.checksum();
1588 void Buffer::saveCheckSum(FileName const & file) const
1590 if (file.exists()) {
1591 d->timestamp_ = file.lastModified();
1592 d->checksum_ = file.checksum();
1594 // in the case of save to a new file.
1601 void Buffer::markClean() const
1603 if (!d->lyx_clean) {
1604 d->lyx_clean = true;
1607 // if the .lyx file has been saved, we don't need an
1609 d->bak_clean = true;
1613 void Buffer::markBakClean() const
1615 d->bak_clean = true;
1619 void Buffer::setUnnamed(bool flag)
1625 bool Buffer::isUnnamed() const
1631 // FIXME: this function should be moved to buffer_pimpl.C
1632 void Buffer::markDirty()
1635 d->lyx_clean = false;
1638 d->bak_clean = false;
1640 DepClean::iterator it = d->dep_clean.begin();
1641 DepClean::const_iterator const end = d->dep_clean.end();
1643 for (; it != end; ++it)
1648 FileName Buffer::fileName() const
1654 string Buffer::absFileName() const
1656 return d->filename.absFilename();
1660 string Buffer::filePath() const
1662 return d->filename.onlyPath().absFilename() + "/";
1666 bool Buffer::isReadonly() const
1668 return d->read_only;
1672 void Buffer::setParent(Buffer const * buffer)
1674 // Avoids recursive include.
1675 d->parent_buffer = buffer == this ? 0 : buffer;
1680 Buffer const * Buffer::parent()
1682 return d->parent_buffer;
1686 Buffer const * Buffer::masterBuffer() const
1688 if (!d->parent_buffer)
1691 return d->parent_buffer->masterBuffer();
1695 bool Buffer::isChild(Buffer * child) const
1697 return d->children_positions.find(child) != d->children_positions.end();
1701 template<typename M>
1702 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
1707 typename M::iterator it = m.lower_bound(x);
1708 if (it == m.begin())
1716 MacroData const * Buffer::getBufferMacro(docstring const & name,
1717 DocIterator const & pos) const
1719 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
1721 // if paragraphs have no macro context set, pos will be empty
1725 // we haven't found anything yet
1726 DocIterator bestPos = par_iterator_begin();
1727 MacroData const * bestData = 0;
1729 // find macro definitions for name
1730 Impl::NamePositionScopeMacroMap::iterator nameIt
1731 = d->macros.find(name);
1732 if (nameIt != d->macros.end()) {
1733 // find last definition in front of pos or at pos itself
1734 Impl::PositionScopeMacroMap::const_iterator it
1735 = greatest_below(nameIt->second, pos);
1736 if (it != nameIt->second.end()) {
1738 // scope ends behind pos?
1739 if (pos < it->second.first) {
1740 // Looks good, remember this. If there
1741 // is no external macro behind this,
1742 // we found the right one already.
1743 bestPos = it->first;
1744 bestData = &it->second.second;
1748 // try previous macro if there is one
1749 if (it == nameIt->second.begin())
1756 // find macros in included files
1757 Impl::PositionScopeBufferMap::const_iterator it
1758 = greatest_below(d->position_to_children, pos);
1759 if (it == d->position_to_children.end())
1760 // no children before
1764 // do we know something better (i.e. later) already?
1765 if (it->first < bestPos )
1768 // scope ends behind pos?
1769 if (pos < it->second.first) {
1770 // look for macro in external file
1771 d->macro_lock = true;
1772 MacroData const * data
1773 = it->second.second->getMacro(name, false);
1774 d->macro_lock = false;
1776 bestPos = it->first;
1782 // try previous file if there is one
1783 if (it == d->position_to_children.begin())
1788 // return the best macro we have found
1793 MacroData const * Buffer::getMacro(docstring const & name,
1794 DocIterator const & pos, bool global) const
1799 // query buffer macros
1800 MacroData const * data = getBufferMacro(name, pos);
1804 // If there is a master buffer, query that
1805 if (d->parent_buffer) {
1806 d->macro_lock = true;
1807 MacroData const * macro = d->parent_buffer->getMacro(
1808 name, *this, false);
1809 d->macro_lock = false;
1815 data = MacroTable::globalMacros().get(name);
1824 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
1826 // set scope end behind the last paragraph
1827 DocIterator scope = par_iterator_begin();
1828 scope.pit() = scope.lastpit() + 1;
1830 return getMacro(name, scope, global);
1834 MacroData const * Buffer::getMacro(docstring const & name,
1835 Buffer const & child, bool global) const
1837 // look where the child buffer is included first
1838 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
1839 if (it == d->children_positions.end())
1842 // check for macros at the inclusion position
1843 return getMacro(name, it->second, global);
1847 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
1849 pit_type lastpit = it.lastpit();
1851 // look for macros in each paragraph
1852 while (it.pit() <= lastpit) {
1853 Paragraph & par = it.paragraph();
1855 // iterate over the insets of the current paragraph
1856 InsetList const & insets = par.insetList();
1857 InsetList::const_iterator iit = insets.begin();
1858 InsetList::const_iterator end = insets.end();
1859 for (; iit != end; ++iit) {
1860 it.pos() = iit->pos;
1862 // is it a nested text inset?
1863 if (iit->inset->asInsetText()) {
1864 // Inset needs its own scope?
1865 InsetText const * itext
1866 = iit->inset->asInsetText();
1867 bool newScope = itext->isMacroScope();
1869 // scope which ends just behind the inset
1870 DocIterator insetScope = it;
1873 // collect macros in inset
1874 it.push_back(CursorSlice(*iit->inset));
1875 updateMacros(it, newScope ? insetScope : scope);
1880 // is it an external file?
1881 if (iit->inset->lyxCode() == INCLUDE_CODE) {
1882 // get buffer of external file
1883 InsetCommand const & inset
1884 = static_cast<InsetCommand const &>(*iit->inset);
1885 InsetCommandParams const & ip = inset.params();
1886 d->macro_lock = true;
1887 Buffer * child = loadIfNeeded(*this, ip);
1888 d->macro_lock = false;
1892 // register its position, but only when it is
1893 // included first in the buffer
1894 if (d->children_positions.find(child)
1895 == d->children_positions.end())
1896 d->children_positions[child] = it;
1898 // register child with its scope
1899 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
1903 if (iit->inset->lyxCode() != MATHMACRO_CODE)
1907 MathMacroTemplate & macroTemplate
1908 = static_cast<MathMacroTemplate &>(*iit->inset);
1909 MacroContext mc(*this, it);
1910 macroTemplate.updateToContext(mc);
1913 bool valid = macroTemplate.validMacro();
1914 // FIXME: Should be fixNameAndCheckIfValid() in fact,
1915 // then the BufferView's cursor will be invalid in
1916 // some cases which leads to crashes.
1921 d->macros[macroTemplate.name()][it] =
1922 Impl::ScopeMacro(scope, MacroData(*this, it));
1932 void Buffer::updateMacros() const
1937 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
1939 // start with empty table
1941 d->children_positions.clear();
1942 d->position_to_children.clear();
1944 // Iterate over buffer, starting with first paragraph
1945 // The scope must be bigger than any lookup DocIterator
1946 // later. For the global lookup, lastpit+1 is used, hence
1947 // we use lastpit+2 here.
1948 DocIterator it = par_iterator_begin();
1949 DocIterator outerScope = it;
1950 outerScope.pit() = outerScope.lastpit() + 2;
1951 updateMacros(it, outerScope);
1955 void Buffer::updateMacroInstances() const
1957 LYXERR(Debug::MACROS, "updateMacroInstances for "
1958 << d->filename.onlyFileName());
1959 DocIterator it = doc_iterator_begin(inset());
1960 DocIterator end = doc_iterator_end(inset());
1961 for (; it != end; it.forwardPos()) {
1962 // look for MathData cells in InsetMathNest insets
1963 Inset * inset = it.nextInset();
1967 InsetMath * minset = inset->asInsetMath();
1971 // update macro in all cells of the InsetMathNest
1972 DocIterator::idx_type n = minset->nargs();
1973 MacroContext mc = MacroContext(*this, it);
1974 for (DocIterator::idx_type i = 0; i < n; ++i) {
1975 MathData & data = minset->cell(i);
1976 data.updateMacros(0, mc);
1982 void Buffer::listMacroNames(MacroNameSet & macros) const
1987 d->macro_lock = true;
1989 // loop over macro names
1990 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
1991 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
1992 for (; nameIt != nameEnd; ++nameIt)
1993 macros.insert(nameIt->first);
1995 // loop over children
1996 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
1997 Impl::BufferPositionMap::iterator end = d->children_positions.end();
1998 for (; it != end; ++it)
1999 it->first->listMacroNames(macros);
2002 if (d->parent_buffer)
2003 d->parent_buffer->listMacroNames(macros);
2005 d->macro_lock = false;
2009 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2011 if (!d->parent_buffer)
2015 d->parent_buffer->listMacroNames(names);
2018 MacroNameSet::iterator it = names.begin();
2019 MacroNameSet::iterator end = names.end();
2020 for (; it != end; ++it) {
2022 MacroData const * data =
2023 d->parent_buffer->getMacro(*it, *this, false);
2025 macros.insert(data);
2027 // we cannot access the original MathMacroTemplate anymore
2028 // here to calls validate method. So we do its work here manually.
2029 // FIXME: somehow make the template accessible here.
2030 if (data->optionals() > 0)
2031 features.require("xargs");
2037 Buffer::References & Buffer::references(docstring const & label)
2039 if (d->parent_buffer)
2040 return const_cast<Buffer *>(masterBuffer())->references(label);
2042 RefCache::iterator it = d->ref_cache_.find(label);
2043 if (it != d->ref_cache_.end())
2044 return it->second.second;
2046 static InsetLabel const * dummy_il = 0;
2047 static References const dummy_refs;
2048 it = d->ref_cache_.insert(
2049 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2050 return it->second.second;
2054 Buffer::References const & Buffer::references(docstring const & label) const
2056 return const_cast<Buffer *>(this)->references(label);
2060 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2062 masterBuffer()->d->ref_cache_[label].first = il;
2066 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2068 return masterBuffer()->d->ref_cache_[label].first;
2072 void Buffer::clearReferenceCache() const
2074 if (!d->parent_buffer)
2075 d->ref_cache_.clear();
2079 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2082 //FIXME: This does not work for child documents yet.
2083 LASSERT(code == CITE_CODE, /**/);
2084 // Check if the label 'from' appears more than once
2085 vector<docstring> labels;
2087 BiblioInfo const & keys = masterBibInfo();
2088 BiblioInfo::const_iterator bit = keys.begin();
2089 BiblioInfo::const_iterator bend = keys.end();
2091 for (; bit != bend; ++bit)
2093 labels.push_back(bit->first);
2096 if (count(labels.begin(), labels.end(), from) > 1)
2099 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2100 if (it->lyxCode() == code) {
2101 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2102 docstring const oldValue = inset.getParam(paramName);
2103 if (oldValue == from)
2104 inset.setParam(paramName, to);
2110 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2111 pit_type par_end, bool full_source) const
2113 OutputParams runparams(¶ms().encoding());
2114 runparams.nice = true;
2115 runparams.flavor = OutputParams::LATEX;
2116 runparams.linelen = lyxrc.plaintext_linelen;
2117 // No side effect of file copying and image conversion
2118 runparams.dryrun = true;
2122 os << "% " << _("Preview source code") << "\n\n";
2123 d->texrow.newline();
2124 d->texrow.newline();
2126 writeDocBookSource(os, absFileName(), runparams, false);
2128 // latex or literate
2129 writeLaTeXSource(os, string(), runparams, true, true);
2131 runparams.par_begin = par_begin;
2132 runparams.par_end = par_end;
2133 if (par_begin + 1 == par_end) {
2135 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2139 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2140 convert<docstring>(par_begin),
2141 convert<docstring>(par_end - 1))
2144 d->texrow.newline();
2145 d->texrow.newline();
2146 // output paragraphs
2148 docbookParagraphs(paragraphs(), *this, os, runparams);
2150 // latex or literate
2151 latexParagraphs(*this, text(), os, d->texrow, runparams);
2156 ErrorList & Buffer::errorList(string const & type) const
2158 static ErrorList emptyErrorList;
2159 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2160 if (I == d->errorLists.end())
2161 return emptyErrorList;
2167 void Buffer::updateTocItem(std::string const & type,
2168 DocIterator const & dit) const
2171 gui_->updateTocItem(type, dit);
2175 void Buffer::structureChanged() const
2178 gui_->structureChanged();
2182 void Buffer::errors(string const & err) const
2189 void Buffer::message(docstring const & msg) const
2196 void Buffer::setBusy(bool on) const
2203 void Buffer::setReadOnly(bool on) const
2206 d->wa_->setReadOnly(on);
2210 void Buffer::updateTitles() const
2213 d->wa_->updateTitles();
2217 void Buffer::resetAutosaveTimers() const
2220 gui_->resetAutosaveTimers();
2224 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2233 class AutoSaveBuffer : public ForkedProcess
2237 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2238 : buffer_(buffer), fname_(fname) {}
2240 virtual boost::shared_ptr<ForkedProcess> clone() const
2242 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2247 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2248 from_utf8(fname_.absFilename())));
2249 return run(DontWait);
2253 virtual int generateChild();
2255 Buffer const & buffer_;
2260 int AutoSaveBuffer::generateChild()
2262 // tmp_ret will be located (usually) in /tmp
2263 // will that be a problem?
2264 // Note that this calls ForkedCalls::fork(), so it's
2265 // ok cross-platform.
2266 pid_t const pid = fork();
2267 // If you want to debug the autosave
2268 // you should set pid to -1, and comment out the fork.
2269 if (pid != 0 && pid != -1)
2272 // pid = -1 signifies that lyx was unable
2273 // to fork. But we will do the save
2275 bool failed = false;
2276 FileName const tmp_ret = FileName::tempName("lyxauto");
2277 if (!tmp_ret.empty()) {
2278 buffer_.writeFile(tmp_ret);
2279 // assume successful write of tmp_ret
2280 if (!tmp_ret.moveTo(fname_))
2286 // failed to write/rename tmp_ret so try writing direct
2287 if (!buffer_.writeFile(fname_)) {
2288 // It is dangerous to do this in the child,
2289 // but safe in the parent, so...
2290 if (pid == -1) // emit message signal.
2291 buffer_.message(_("Autosave failed!"));
2295 if (pid == 0) // we are the child so...
2304 // Perfect target for a thread...
2305 void Buffer::autoSave() const
2307 if (isBakClean() || isReadonly()) {
2308 // We don't save now, but we'll try again later
2309 resetAutosaveTimers();
2313 // emit message signal.
2314 message(_("Autosaving current document..."));
2316 // create autosave filename
2317 string fname = filePath();
2319 fname += d->filename.onlyFileName();
2322 AutoSaveBuffer autosave(*this, FileName(fname));
2326 resetAutosaveTimers();
2330 string Buffer::bufferFormat() const
2336 if (params().encoding().package() == Encoding::japanese)
2342 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2343 string & result_file) const
2345 string backend_format;
2346 OutputParams runparams(¶ms().encoding());
2347 runparams.flavor = OutputParams::LATEX;
2348 runparams.linelen = lyxrc.plaintext_linelen;
2349 vector<string> backs = backends();
2350 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2351 // Get shortest path to format
2352 Graph::EdgePath path;
2353 for (vector<string>::const_iterator it = backs.begin();
2354 it != backs.end(); ++it) {
2355 Graph::EdgePath p = theConverters().getPath(*it, format);
2356 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2357 backend_format = *it;
2362 runparams.flavor = theConverters().getFlavor(path);
2364 Alert::error(_("Couldn't export file"),
2365 bformat(_("No information for exporting the format %1$s."),
2366 formats.prettyName(format)));
2370 backend_format = format;
2371 // FIXME: Don't hardcode format names here, but use a flag
2372 if (backend_format == "pdflatex")
2373 runparams.flavor = OutputParams::PDFLATEX;
2376 string filename = latexName(false);
2377 filename = addName(temppath(), filename);
2378 filename = changeExtension(filename,
2379 formats.extension(backend_format));
2382 updateMacroInstances();
2384 // Plain text backend
2385 if (backend_format == "text")
2386 writePlaintextFile(*this, FileName(filename), runparams);
2388 else if (backend_format == "lyx")
2389 writeFile(FileName(filename));
2391 else if (isDocBook()) {
2392 runparams.nice = !put_in_tempdir;
2393 makeDocBookFile(FileName(filename), runparams);
2396 else if (backend_format == format) {
2397 runparams.nice = true;
2398 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2400 } else if (!lyxrc.tex_allows_spaces
2401 && contains(filePath(), ' ')) {
2402 Alert::error(_("File name error"),
2403 _("The directory path to the document cannot contain spaces."));
2406 runparams.nice = false;
2407 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2411 string const error_type = (format == "program")
2412 ? "Build" : bufferFormat();
2413 ErrorList & error_list = d->errorLists[error_type];
2414 string const ext = formats.extension(format);
2415 FileName const tmp_result_file(changeExtension(filename, ext));
2416 bool const success = theConverters().convert(this, FileName(filename),
2417 tmp_result_file, FileName(absFileName()), backend_format, format,
2419 // Emit the signal to show the error list.
2420 if (format != backend_format)
2425 if (put_in_tempdir) {
2426 result_file = tmp_result_file.absFilename();
2430 result_file = changeExtension(absFileName(), ext);
2431 // We need to copy referenced files (e. g. included graphics
2432 // if format == "dvi") to the result dir.
2433 vector<ExportedFile> const files =
2434 runparams.exportdata->externalFiles(format);
2435 string const dest = onlyPath(result_file);
2436 CopyStatus status = SUCCESS;
2437 for (vector<ExportedFile>::const_iterator it = files.begin();
2438 it != files.end() && status != CANCEL; ++it) {
2439 string const fmt = formats.getFormatFromFile(it->sourceName);
2440 status = copyFile(fmt, it->sourceName,
2441 makeAbsPath(it->exportName, dest),
2442 it->exportName, status == FORCE);
2444 if (status == CANCEL) {
2445 message(_("Document export cancelled."));
2446 } else if (tmp_result_file.exists()) {
2447 // Finally copy the main file
2448 status = copyFile(format, tmp_result_file,
2449 FileName(result_file), result_file,
2451 message(bformat(_("Document exported as %1$s "
2453 formats.prettyName(format),
2454 makeDisplayPath(result_file)));
2456 // This must be a dummy converter like fax (bug 1888)
2457 message(bformat(_("Document exported as %1$s"),
2458 formats.prettyName(format)));
2465 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2468 return doExport(format, put_in_tempdir, result_file);
2472 bool Buffer::preview(string const & format) const
2475 if (!doExport(format, true, result_file))
2477 return formats.view(*this, FileName(result_file), format);
2481 bool Buffer::isExportable(string const & format) const
2483 vector<string> backs = backends();
2484 for (vector<string>::const_iterator it = backs.begin();
2485 it != backs.end(); ++it)
2486 if (theConverters().isReachable(*it, format))
2492 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2494 vector<string> backs = backends();
2495 vector<Format const *> result =
2496 theConverters().getReachable(backs[0], only_viewable, true);
2497 for (vector<string>::const_iterator it = backs.begin() + 1;
2498 it != backs.end(); ++it) {
2499 vector<Format const *> r =
2500 theConverters().getReachable(*it, only_viewable, false);
2501 result.insert(result.end(), r.begin(), r.end());
2507 vector<string> Buffer::backends() const
2510 if (params().baseClass()->isTeXClassAvailable()) {
2511 v.push_back(bufferFormat());
2512 // FIXME: Don't hardcode format names here, but use a flag
2513 if (v.back() == "latex")
2514 v.push_back("pdflatex");
2516 v.push_back("text");
2522 bool Buffer::readFileHelper(FileName const & s)
2524 // File information about normal file
2526 docstring const file = makeDisplayPath(s.absFilename(), 50);
2527 docstring text = bformat(_("The specified document\n%1$s"
2528 "\ncould not be read."), file);
2529 Alert::error(_("Could not read document"), text);
2533 // Check if emergency save file exists and is newer.
2534 FileName const e(s.absFilename() + ".emergency");
2536 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2537 docstring const file = makeDisplayPath(s.absFilename(), 20);
2538 docstring const text =
2539 bformat(_("An emergency save of the document "
2541 "Recover emergency save?"), file);
2542 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2543 _("&Recover"), _("&Load Original"),
2547 // the file is not saved if we load the emergency file.
2557 // Now check if autosave file is newer.
2558 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2560 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2561 docstring const file = makeDisplayPath(s.absFilename(), 20);
2562 docstring const text =
2563 bformat(_("The backup of the document "
2564 "%1$s is newer.\n\nLoad the "
2565 "backup instead?"), file);
2566 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2567 _("&Load backup"), _("Load &original"),
2571 // the file is not saved if we load the autosave file.
2575 // Here we delete the autosave
2586 bool Buffer::loadLyXFile(FileName const & s)
2588 if (s.isReadableFile()) {
2589 if (readFileHelper(s)) {
2590 lyxvc().file_found_hook(s);
2591 if (!s.isWritable())
2596 docstring const file = makeDisplayPath(s.absFilename(), 20);
2597 // Here we probably should run
2598 if (LyXVC::file_not_found_hook(s)) {
2599 docstring const text =
2600 bformat(_("Do you want to retrieve the document"
2601 " %1$s from version control?"), file);
2602 int const ret = Alert::prompt(_("Retrieve from version control?"),
2603 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2606 // How can we know _how_ to do the checkout?
2607 // With the current VC support it has to be,
2608 // a RCS file since CVS do not have special ,v files.
2610 return loadLyXFile(s);
2618 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2620 TeXErrors::Errors::const_iterator cit = terr.begin();
2621 TeXErrors::Errors::const_iterator end = terr.end();
2623 for (; cit != end; ++cit) {
2626 int errorRow = cit->error_in_line;
2627 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2633 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2634 } while (found && id_start == id_end && pos_start == pos_end);
2636 errorList.push_back(ErrorItem(cit->error_desc,
2637 cit->error_text, id_start, pos_start, pos_end));