3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Stefan Schimanski
9 * Full author contact details are available in file CREDITS.
17 #include "LayoutFile.h"
18 #include "BiblioInfo.h"
19 #include "BranchList.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
25 #include "Converter.h"
27 #include "DocIterator.h"
29 #include "ErrorList.h"
32 #include "FuncRequest.h"
33 #include "InsetIterator.h"
34 #include "InsetList.h"
36 #include "LaTeXFeatures.h"
40 #include "LyXAction.h"
44 #include "output_docbook.h"
46 #include "output_latex.h"
47 #include "output_plaintext.h"
48 #include "paragraph_funcs.h"
49 #include "Paragraph.h"
50 #include "ParagraphParameters.h"
51 #include "ParIterator.h"
52 #include "PDFOptions.h"
55 #include "TexStream.h"
57 #include "TextClass.h"
58 #include "TocBackend.h"
60 #include "VCBackend.h"
64 #include "insets/InsetBibitem.h"
65 #include "insets/InsetBibtex.h"
66 #include "insets/InsetInclude.h"
67 #include "insets/InsetText.h"
69 #include "mathed/MacroTable.h"
70 #include "mathed/MathMacroTemplate.h"
71 #include "mathed/MathSupport.h"
73 #include "frontends/alert.h"
74 #include "frontends/Delegates.h"
75 #include "frontends/WorkAreaManager.h"
77 #include "graphics/Previews.h"
79 #include "support/lassert.h"
80 #include "support/convert.h"
81 #include "support/debug.h"
82 #include "support/ExceptionMessage.h"
83 #include "support/FileName.h"
84 #include "support/FileNameList.h"
85 #include "support/filetools.h"
86 #include "support/ForkedCalls.h"
87 #include "support/gettext.h"
88 #include "support/gzstream.h"
89 #include "support/lstrings.h"
90 #include "support/lyxalgo.h"
91 #include "support/os.h"
92 #include "support/Package.h"
93 #include "support/Path.h"
94 #include "support/textutils.h"
95 #include "support/types.h"
97 #include <boost/bind.hpp>
98 #include <boost/shared_ptr.hpp>
109 using namespace lyx::support;
113 namespace Alert = frontend::Alert;
114 namespace os = support::os;
118 int const LYX_FORMAT = 335;
120 typedef map<string, bool> DepClean;
121 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
128 Impl(Buffer & parent, FileName const & file, bool readonly);
141 mutable TexRow texrow;
142 Buffer const * parent_buffer;
144 /// need to regenerate .tex?
148 mutable bool lyx_clean;
150 /// is autosave needed?
151 mutable bool bak_clean;
153 /// is this a unnamed file (New...)?
159 /// name of the file the buffer is associated with.
162 /** Set to true only when the file is fully loaded.
163 * Used to prevent the premature generation of previews
164 * and by the citation inset.
166 bool file_fully_loaded;
169 mutable TocBackend toc_backend;
172 typedef pair<DocIterator, MacroData> ScopeMacro;
173 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
174 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
175 /// map from the macro name to the position map,
176 /// which maps the macro definition position to the scope and the MacroData.
177 NamePositionScopeMacroMap macros;
180 /// positions of child buffers in the buffer
181 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
182 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
183 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
184 /// position of children buffers in this buffer
185 BufferPositionMap children_positions;
186 /// map from children inclusion positions to their scope and their buffer
187 PositionScopeBufferMap position_to_children;
189 /// Container for all sort of Buffer dependant errors.
190 map<string, ErrorList> errorLists;
192 /// timestamp and checksum used to test if the file has been externally
193 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
195 unsigned long checksum_;
198 frontend::WorkAreaManager * wa_;
203 /// A cache for the bibfiles (including bibfiles of loaded child
204 /// documents), needed for appropriate update of natbib labels.
205 mutable support::FileNameList bibfilesCache_;
207 // FIXME The caching mechanism could be improved. At present, we have a
208 // cache for each Buffer, that caches all the bibliography info for that
209 // Buffer. A more efficient solution would be to have a global cache per
210 // file, and then to construct the Buffer's bibinfo from that.
211 /// A cache for bibliography info
212 mutable BiblioInfo bibinfo_;
213 /// Cache of timestamps of .bib files
214 map<FileName, time_t> bibfileStatus_;
216 mutable RefCache ref_cache_;
218 /// our Text that should be wrapped in an InsetText
223 /// Creates the per buffer temporary directory
224 static FileName createBufferTmpDir()
227 // We are in our own directory. Why bother to mangle name?
228 // In fact I wrote this code to circumvent a problematic behaviour
229 // (bug?) of EMX mkstemp().
230 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
231 convert<string>(count++));
233 if (!tmpfl.createDirectory(0777)) {
234 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
235 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
236 from_utf8(tmpfl.absFilename())));
242 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
243 : parent_buffer(0), lyx_clean(true), bak_clean(true), unnamed(false),
244 read_only(readonly_), filename(file), file_fully_loaded(false),
245 toc_backend(&parent), macro_lock(false), timestamp_(0),
246 checksum_(0), wa_(0), undo_(parent)
248 temppath = createBufferTmpDir();
249 lyxvc.setBuffer(&parent);
251 wa_ = new frontend::WorkAreaManager;
255 Buffer::Buffer(string const & file, bool readonly)
256 : d(new Impl(*this, FileName(file), readonly)), gui_(0)
258 LYXERR(Debug::INFO, "Buffer::Buffer()");
260 d->inset.setBuffer(*this);
261 d->inset.initParagraphs(*this);
262 d->inset.setAutoBreakRows(true);
263 d->inset.getText(0)->setMacrocontextPosition(par_iterator_begin());
269 LYXERR(Debug::INFO, "Buffer::~Buffer()");
270 // here the buffer should take care that it is
271 // saved properly, before it goes into the void.
273 // GuiView already destroyed
276 // clear references to children in macro tables
277 d->children_positions.clear();
278 d->position_to_children.clear();
280 if (!d->temppath.destroyDirectory()) {
281 Alert::warning(_("Could not remove temporary directory"),
282 bformat(_("Could not remove the temporary directory %1$s"),
283 from_utf8(d->temppath.absFilename())));
286 // Remove any previewed LaTeX snippets associated with this buffer.
287 graphics::Previews::get().removeLoader(*this);
293 void Buffer::changed() const
300 frontend::WorkAreaManager & Buffer::workAreaManager() const
302 LASSERT(d->wa_, /**/);
307 Text & Buffer::text() const
309 return const_cast<Text &>(d->inset.text_);
313 Inset & Buffer::inset() const
315 return const_cast<InsetText &>(d->inset);
319 BufferParams & Buffer::params()
325 BufferParams const & Buffer::params() const
331 ParagraphList & Buffer::paragraphs()
333 return text().paragraphs();
337 ParagraphList const & Buffer::paragraphs() const
339 return text().paragraphs();
343 LyXVC & Buffer::lyxvc()
349 LyXVC const & Buffer::lyxvc() const
355 string const Buffer::temppath() const
357 return d->temppath.absFilename();
361 TexRow const & Buffer::texrow() const
367 TocBackend & Buffer::tocBackend() const
369 return d->toc_backend;
373 Undo & Buffer::undo()
379 string Buffer::latexName(bool const no_path) const
381 FileName latex_name = makeLatexName(d->filename);
382 return no_path ? latex_name.onlyFileName()
383 : latex_name.absFilename();
387 string Buffer::logName(LogType * type) const
389 string const filename = latexName(false);
391 if (filename.empty()) {
397 string const path = temppath();
399 FileName const fname(addName(temppath(),
400 onlyFilename(changeExtension(filename,
402 FileName const bname(
403 addName(path, onlyFilename(
404 changeExtension(filename,
405 formats.extension("literate") + ".out"))));
407 // If no Latex log or Build log is newer, show Build log
409 if (bname.exists() &&
410 (!fname.exists() || fname.lastModified() < bname.lastModified())) {
411 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
414 return bname.absFilename();
416 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
419 return fname.absFilename();
423 void Buffer::setReadonly(bool const flag)
425 if (d->read_only != flag) {
432 void Buffer::setFileName(string const & newfile)
434 d->filename = makeAbsPath(newfile);
435 setReadonly(d->filename.isReadOnly());
440 int Buffer::readHeader(Lexer & lex)
442 int unknown_tokens = 0;
444 int begin_header_line = -1;
446 // Initialize parameters that may be/go lacking in header:
447 params().branchlist().clear();
448 params().preamble.erase();
449 params().options.erase();
450 params().master.erase();
451 params().float_placement.erase();
452 params().paperwidth.erase();
453 params().paperheight.erase();
454 params().leftmargin.erase();
455 params().rightmargin.erase();
456 params().topmargin.erase();
457 params().bottommargin.erase();
458 params().headheight.erase();
459 params().headsep.erase();
460 params().footskip.erase();
461 params().columnsep.erase();
462 params().listings_params.clear();
463 params().clearLayoutModules();
464 params().pdfoptions().clear();
466 for (int i = 0; i < 4; ++i) {
467 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
468 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
471 ErrorList & errorList = d->errorLists["Parse"];
480 if (token == "\\end_header")
484 if (token == "\\begin_header") {
485 begin_header_line = line;
489 LYXERR(Debug::PARSER, "Handling document header token: `"
492 string unknown = params().readToken(lex, token, d->filename.onlyPath());
493 if (!unknown.empty()) {
494 if (unknown[0] != '\\' && token == "\\textclass") {
495 Alert::warning(_("Unknown document class"),
496 bformat(_("Using the default document class, because the "
497 "class %1$s is unknown."), from_utf8(unknown)));
500 docstring const s = bformat(_("Unknown token: "
504 errorList.push_back(ErrorItem(_("Document header error"),
509 if (begin_header_line) {
510 docstring const s = _("\\begin_header is missing");
511 errorList.push_back(ErrorItem(_("Document header error"),
515 params().makeDocumentClass();
517 return unknown_tokens;
522 // changed to be public and have one parameter
523 // Returns false if "\end_document" is not read (Asger)
524 bool Buffer::readDocument(Lexer & lex)
526 ErrorList & errorList = d->errorLists["Parse"];
529 if (!lex.checkFor("\\begin_document")) {
530 docstring const s = _("\\begin_document is missing");
531 errorList.push_back(ErrorItem(_("Document header error"),
535 // we are reading in a brand new document
536 LASSERT(paragraphs().empty(), /**/);
540 if (params().outputChanges) {
541 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
542 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
543 LaTeXFeatures::isAvailable("xcolor");
545 if (!dvipost && !xcolorsoul) {
546 Alert::warning(_("Changes not shown in LaTeX output"),
547 _("Changes will not be highlighted in LaTeX output, "
548 "because neither dvipost nor xcolor/soul are installed.\n"
549 "Please install these packages or redefine "
550 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
551 } else if (!xcolorsoul) {
552 Alert::warning(_("Changes not shown in LaTeX output"),
553 _("Changes will not be highlighted in LaTeX output "
554 "when using pdflatex, because xcolor and soul are not installed.\n"
555 "Please install both packages or redefine "
556 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
560 if (!params().master.empty()) {
561 FileName const master_file = makeAbsPath(params().master,
562 onlyPath(absFileName()));
563 if (isLyXFilename(master_file.absFilename())) {
564 Buffer * master = checkAndLoadLyXFile(master_file);
565 d->parent_buffer = master;
570 bool const res = text().read(*this, lex, errorList, &(d->inset));
573 updateMacroInstances();
578 // needed to insert the selection
579 void Buffer::insertStringAsLines(ParagraphList & pars,
580 pit_type & pit, pos_type & pos,
581 Font const & fn, docstring const & str, bool autobreakrows)
585 // insert the string, don't insert doublespace
586 bool space_inserted = true;
587 for (docstring::const_iterator cit = str.begin();
588 cit != str.end(); ++cit) {
589 Paragraph & par = pars[pit];
591 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
592 breakParagraph(params(), pars, pit, pos,
593 par.layout().isEnvironment());
596 space_inserted = true;
600 // do not insert consecutive spaces if !free_spacing
601 } else if ((*cit == ' ' || *cit == '\t') &&
602 space_inserted && !par.isFreeSpacing()) {
604 } else if (*cit == '\t') {
605 if (!par.isFreeSpacing()) {
606 // tabs are like spaces here
607 par.insertChar(pos, ' ', font, params().trackChanges);
609 space_inserted = true;
611 const pos_type n = 8 - pos % 8;
612 for (pos_type i = 0; i < n; ++i) {
613 par.insertChar(pos, ' ', font, params().trackChanges);
616 space_inserted = true;
618 } else if (!isPrintable(*cit)) {
619 // Ignore unprintables
622 // just insert the character
623 par.insertChar(pos, *cit, font, params().trackChanges);
625 space_inserted = (*cit == ' ');
632 bool Buffer::readString(string const & s)
634 params().compressed = false;
636 // remove dummy empty par
637 paragraphs().clear();
641 FileName const name = FileName::tempName();
642 switch (readFile(lex, name, true)) {
646 // We need to call lyx2lyx, so write the input to a file
647 ofstream os(name.toFilesystemEncoding().c_str());
650 return readFile(name);
660 bool Buffer::readFile(FileName const & filename)
662 FileName fname(filename);
664 // remove dummy empty par
665 paragraphs().clear();
668 if (readFile(lex, fname) != success)
675 bool Buffer::isFullyLoaded() const
677 return d->file_fully_loaded;
681 void Buffer::setFullyLoaded(bool value)
683 d->file_fully_loaded = value;
687 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
690 LASSERT(!filename.empty(), /**/);
692 // the first (non-comment) token _must_ be...
693 if (!lex.checkFor("\\lyxformat")) {
694 Alert::error(_("Document format failure"),
695 bformat(_("%1$s is not a readable LyX document."),
696 from_utf8(filename.absFilename())));
702 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
703 // if present remove ".," from string.
704 size_t dot = tmp_format.find_first_of(".,");
705 //lyxerr << " dot found at " << dot << endl;
706 if (dot != string::npos)
707 tmp_format.erase(dot, 1);
708 int const file_format = convert<int>(tmp_format);
709 //lyxerr << "format: " << file_format << endl;
711 // save timestamp and checksum of the original disk file, making sure
712 // to not overwrite them with those of the file created in the tempdir
713 // when it has to be converted to the current format.
715 // Save the timestamp and checksum of disk file. If filename is an
716 // emergency file, save the timestamp and checksum of the original lyx file
717 // because isExternallyModified will check for this file. (BUG4193)
718 string diskfile = filename.absFilename();
719 if (suffixIs(diskfile, ".emergency"))
720 diskfile = diskfile.substr(0, diskfile.size() - 10);
721 saveCheckSum(FileName(diskfile));
724 if (file_format != LYX_FORMAT) {
727 // lyx2lyx would fail
730 FileName const tmpfile = FileName::tempName();
731 if (tmpfile.empty()) {
732 Alert::error(_("Conversion failed"),
733 bformat(_("%1$s is from a different"
734 " version of LyX, but a temporary"
735 " file for converting it could"
737 from_utf8(filename.absFilename())));
740 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
741 if (lyx2lyx.empty()) {
742 Alert::error(_("Conversion script not found"),
743 bformat(_("%1$s is from a different"
744 " version of LyX, but the"
745 " conversion script lyx2lyx"
746 " could not be found."),
747 from_utf8(filename.absFilename())));
750 ostringstream command;
751 command << os::python()
752 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
753 << " -t " << convert<string>(LYX_FORMAT)
754 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
755 << ' ' << quoteName(filename.toFilesystemEncoding());
756 string const command_str = command.str();
758 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
760 cmd_ret const ret = runCommand(command_str);
761 if (ret.first != 0) {
762 Alert::error(_("Conversion script failed"),
763 bformat(_("%1$s is from a different version"
764 " of LyX, but the lyx2lyx script"
765 " failed to convert it."),
766 from_utf8(filename.absFilename())));
769 bool const ret = readFile(tmpfile);
770 // Do stuff with tmpfile name and buffer name here.
771 return ret ? success : failure;
776 if (readDocument(lex)) {
777 Alert::error(_("Document format failure"),
778 bformat(_("%1$s ended unexpectedly, which means"
779 " that it is probably corrupted."),
780 from_utf8(filename.absFilename())));
783 d->file_fully_loaded = true;
788 // Should probably be moved to somewhere else: BufferView? LyXView?
789 bool Buffer::save() const
791 // We don't need autosaves in the immediate future. (Asger)
792 resetAutosaveTimers();
794 string const encodedFilename = d->filename.toFilesystemEncoding();
797 bool madeBackup = false;
799 // make a backup if the file already exists
800 if (lyxrc.make_backup && fileName().exists()) {
801 backupName = FileName(absFileName() + '~');
802 if (!lyxrc.backupdir_path.empty()) {
803 string const mangledName =
804 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
805 backupName = FileName(addName(lyxrc.backupdir_path,
808 if (fileName().copyTo(backupName)) {
811 Alert::error(_("Backup failure"),
812 bformat(_("Cannot create backup file %1$s.\n"
813 "Please check whether the directory exists and is writeable."),
814 from_utf8(backupName.absFilename())));
815 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
819 // ask if the disk file has been externally modified (use checksum method)
820 if (fileName().exists() && isExternallyModified(checksum_method)) {
821 docstring const file = makeDisplayPath(absFileName(), 20);
822 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
823 "you want to overwrite this file?"), file);
824 int const ret = Alert::prompt(_("Overwrite modified file?"),
825 text, 1, 1, _("&Overwrite"), _("&Cancel"));
830 if (writeFile(d->filename)) {
834 // Saving failed, so backup is not backup
836 backupName.moveTo(d->filename);
842 bool Buffer::writeFile(FileName const & fname) const
844 if (d->read_only && fname == d->filename)
849 docstring const str = bformat(_("Saving document %1$s..."),
850 makeDisplayPath(fname.absFilename()));
853 if (params().compressed) {
854 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
855 retval = ofs && write(ofs);
857 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
858 retval = ofs && write(ofs);
862 message(str + _(" could not write file!"));
866 removeAutosaveFile(d->filename.absFilename());
868 saveCheckSum(d->filename);
869 message(str + _(" done."));
875 bool Buffer::write(ostream & ofs) const
878 // Use the standard "C" locale for file output.
879 ofs.imbue(locale::classic());
882 // The top of the file should not be written by params().
884 // write out a comment in the top of the file
885 ofs << "#LyX " << lyx_version
886 << " created this file. For more info see http://www.lyx.org/\n"
887 << "\\lyxformat " << LYX_FORMAT << "\n"
888 << "\\begin_document\n";
890 /// For each author, set 'used' to true if there is a change
891 /// by this author in the document; otherwise set it to 'false'.
892 AuthorList::Authors::const_iterator a_it = params().authors().begin();
893 AuthorList::Authors::const_iterator a_end = params().authors().end();
894 for (; a_it != a_end; ++a_it)
895 a_it->second.setUsed(false);
897 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
898 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
899 for ( ; it != end; ++it)
900 it->checkAuthors(params().authors());
902 // now write out the buffer parameters.
903 ofs << "\\begin_header\n";
904 params().writeFile(ofs);
905 ofs << "\\end_header\n";
908 ofs << "\n\\begin_body\n";
909 text().write(*this, ofs);
910 ofs << "\n\\end_body\n";
912 // Write marker that shows file is complete
913 ofs << "\\end_document" << endl;
915 // Shouldn't really be needed....
918 // how to check if close went ok?
919 // Following is an attempt... (BE 20001011)
921 // good() returns false if any error occured, including some
923 // bad() returns true if something bad happened in the buffer,
924 // which should include file system full errors.
929 lyxerr << "File was not closed properly." << endl;
936 bool Buffer::makeLaTeXFile(FileName const & fname,
937 string const & original_path,
938 OutputParams const & runparams,
939 bool output_preamble, bool output_body) const
941 string const encoding = runparams.encoding->iconvName();
942 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
945 try { ofs.reset(encoding); }
946 catch (iconv_codecvt_facet_exception & e) {
947 lyxerr << "Caught iconv exception: " << e.what() << endl;
948 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
949 "verify that the support software for your encoding (%1$s) is "
950 "properly installed"), from_ascii(encoding)));
953 if (!openFileWrite(ofs, fname))
956 //TexStream ts(ofs.rdbuf(), &texrow());
957 ErrorList & errorList = d->errorLists["Export"];
959 bool failed_export = false;
962 writeLaTeXSource(ofs, original_path,
963 runparams, output_preamble, output_body);
965 catch (EncodingException & e) {
966 odocstringstream ods;
967 ods.put(e.failed_char);
969 oss << "0x" << hex << e.failed_char << dec;
970 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
971 " (code point %2$s)"),
972 ods.str(), from_utf8(oss.str()));
973 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
974 "representable in the chosen encoding.\n"
975 "Changing the document encoding to utf8 could help."),
976 e.par_id, e.pos, e.pos + 1));
977 failed_export = true;
979 catch (iconv_codecvt_facet_exception & e) {
980 errorList.push_back(ErrorItem(_("iconv conversion failed"),
981 _(e.what()), -1, 0, 0));
982 failed_export = true;
984 catch (exception const & e) {
985 errorList.push_back(ErrorItem(_("conversion failed"),
986 _(e.what()), -1, 0, 0));
987 failed_export = true;
990 lyxerr << "Caught some really weird exception..." << endl;
996 failed_export = true;
997 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1001 return !failed_export;
1005 void Buffer::writeLaTeXSource(odocstream & os,
1006 string const & original_path,
1007 OutputParams const & runparams_in,
1008 bool const output_preamble, bool const output_body) const
1010 // The child documents, if any, shall be already loaded at this point.
1012 OutputParams runparams = runparams_in;
1014 // validate the buffer.
1015 LYXERR(Debug::LATEX, " Validating buffer...");
1016 LaTeXFeatures features(*this, params(), runparams);
1018 LYXERR(Debug::LATEX, " Buffer validation done.");
1020 // The starting paragraph of the coming rows is the
1021 // first paragraph of the document. (Asger)
1022 if (output_preamble && runparams.nice) {
1023 os << "%% LyX " << lyx_version << " created this file. "
1024 "For more info, see http://www.lyx.org/.\n"
1025 "%% Do not edit unless you really know what "
1027 d->texrow.newline();
1028 d->texrow.newline();
1030 LYXERR(Debug::INFO, "lyx document header finished");
1032 // Don't move this behind the parent_buffer=0 code below,
1033 // because then the macros will not get the right "redefinition"
1034 // flag as they don't see the parent macros which are output before.
1037 // fold macros if possible, still with parent buffer as the
1038 // macros will be put in the prefix anyway.
1039 updateMacroInstances();
1041 // There are a few differences between nice LaTeX and usual files:
1042 // usual is \batchmode and has a
1043 // special input@path to allow the including of figures
1044 // with either \input or \includegraphics (what figinsets do).
1045 // input@path is set when the actual parameter
1046 // original_path is set. This is done for usual tex-file, but not
1047 // for nice-latex-file. (Matthias 250696)
1048 // Note that input@path is only needed for something the user does
1049 // in the preamble, included .tex files or ERT, files included by
1050 // LyX work without it.
1051 if (output_preamble) {
1052 if (!runparams.nice) {
1053 // code for usual, NOT nice-latex-file
1054 os << "\\batchmode\n"; // changed
1055 // from \nonstopmode
1056 d->texrow.newline();
1058 if (!original_path.empty()) {
1060 // We don't know the encoding of inputpath
1061 docstring const inputpath = from_utf8(latex_path(original_path));
1062 os << "\\makeatletter\n"
1063 << "\\def\\input@path{{"
1064 << inputpath << "/}}\n"
1065 << "\\makeatother\n";
1066 d->texrow.newline();
1067 d->texrow.newline();
1068 d->texrow.newline();
1071 // get parent macros (if this buffer has a parent) which will be
1072 // written at the document begin further down.
1073 MacroSet parentMacros;
1074 listParentMacros(parentMacros, features);
1076 // Write the preamble
1077 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1083 os << "\\begin{document}\n";
1084 d->texrow.newline();
1086 // output the parent macros
1087 MacroSet::iterator it = parentMacros.begin();
1088 MacroSet::iterator end = parentMacros.end();
1089 for (; it != end; ++it)
1090 (*it)->write(os, true);
1091 } // output_preamble
1093 d->texrow.start(paragraphs().begin()->id(), 0);
1095 LYXERR(Debug::INFO, "preamble finished, now the body.");
1097 // if we are doing a real file with body, even if this is the
1098 // child of some other buffer, let's cut the link here.
1099 // This happens for example if only a child document is printed.
1100 Buffer const * save_parent = 0;
1101 if (output_preamble) {
1102 save_parent = d->parent_buffer;
1103 d->parent_buffer = 0;
1107 latexParagraphs(*this, text(), os, d->texrow, runparams);
1109 // Restore the parenthood if needed
1110 if (output_preamble)
1111 d->parent_buffer = save_parent;
1113 // add this just in case after all the paragraphs
1115 d->texrow.newline();
1117 if (output_preamble) {
1118 os << "\\end{document}\n";
1119 d->texrow.newline();
1120 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1122 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1124 runparams_in.encoding = runparams.encoding;
1126 // Just to be sure. (Asger)
1127 d->texrow.newline();
1129 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1130 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1134 bool Buffer::isLatex() const
1136 return params().documentClass().outputType() == LATEX;
1140 bool Buffer::isLiterate() const
1142 return params().documentClass().outputType() == LITERATE;
1146 bool Buffer::isDocBook() const
1148 return params().documentClass().outputType() == DOCBOOK;
1152 void Buffer::makeDocBookFile(FileName const & fname,
1153 OutputParams const & runparams,
1154 bool const body_only) const
1156 LYXERR(Debug::LATEX, "makeDocBookFile...");
1159 if (!openFileWrite(ofs, fname))
1162 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1166 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1170 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1171 OutputParams const & runparams,
1172 bool const only_body) const
1174 LaTeXFeatures features(*this, params(), runparams);
1179 DocumentClass const & tclass = params().documentClass();
1180 string const top_element = tclass.latexname();
1183 if (runparams.flavor == OutputParams::XML)
1184 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1187 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1190 if (! tclass.class_header().empty())
1191 os << from_ascii(tclass.class_header());
1192 else if (runparams.flavor == OutputParams::XML)
1193 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1194 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1196 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1198 docstring preamble = from_utf8(params().preamble);
1199 if (runparams.flavor != OutputParams::XML ) {
1200 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1201 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1202 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1203 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1206 string const name = runparams.nice
1207 ? changeExtension(absFileName(), ".sgml") : fname;
1208 preamble += features.getIncludedFiles(name);
1209 preamble += features.getLyXSGMLEntities();
1211 if (!preamble.empty()) {
1212 os << "\n [ " << preamble << " ]";
1217 string top = top_element;
1219 if (runparams.flavor == OutputParams::XML)
1220 top += params().language->code();
1222 top += params().language->code().substr(0,2);
1225 if (!params().options.empty()) {
1227 top += params().options;
1230 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1231 << " file was created by LyX " << lyx_version
1232 << "\n See http://www.lyx.org/ for more information -->\n";
1234 params().documentClass().counters().reset();
1238 sgml::openTag(os, top);
1240 docbookParagraphs(paragraphs(), *this, os, runparams);
1241 sgml::closeTag(os, top_element);
1245 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1246 // Other flags: -wall -v0 -x
1247 int Buffer::runChktex()
1251 // get LaTeX-Filename
1252 FileName const path(temppath());
1253 string const name = addName(path.absFilename(), latexName());
1254 string const org_path = filePath();
1256 PathChanger p(path); // path to LaTeX file
1257 message(_("Running chktex..."));
1259 // Generate the LaTeX file if neccessary
1260 OutputParams runparams(¶ms().encoding());
1261 runparams.flavor = OutputParams::LATEX;
1262 runparams.nice = false;
1263 makeLaTeXFile(FileName(name), org_path, runparams);
1266 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1267 int const res = chktex.run(terr); // run chktex
1270 Alert::error(_("chktex failure"),
1271 _("Could not run chktex successfully."));
1272 } else if (res > 0) {
1273 ErrorList & errlist = d->errorLists["ChkTeX"];
1275 bufferErrors(terr, errlist);
1286 void Buffer::validate(LaTeXFeatures & features) const
1288 params().validate(features);
1292 for_each(paragraphs().begin(), paragraphs().end(),
1293 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1295 if (lyxerr.debugging(Debug::LATEX)) {
1296 features.showStruct();
1301 void Buffer::getLabelList(vector<docstring> & list) const
1303 // If this is a child document, use the parent's list instead.
1304 if (d->parent_buffer) {
1305 d->parent_buffer->getLabelList(list);
1310 Toc & toc = d->toc_backend.toc("label");
1311 TocIterator toc_it = toc.begin();
1312 TocIterator end = toc.end();
1313 for (; toc_it != end; ++toc_it) {
1314 if (toc_it->depth() == 0)
1315 list.push_back(toc_it->str());
1320 void Buffer::updateBibfilesCache() const
1322 // If this is a child document, use the parent's cache instead.
1323 if (d->parent_buffer) {
1324 d->parent_buffer->updateBibfilesCache();
1328 d->bibfilesCache_.clear();
1329 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1330 if (it->lyxCode() == BIBTEX_CODE) {
1331 InsetBibtex const & inset =
1332 static_cast<InsetBibtex const &>(*it);
1333 support::FileNameList const bibfiles = inset.getBibFiles();
1334 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1337 } else if (it->lyxCode() == INCLUDE_CODE) {
1338 InsetInclude & inset =
1339 static_cast<InsetInclude &>(*it);
1340 inset.updateBibfilesCache();
1341 support::FileNameList const & bibfiles =
1342 inset.getBibfilesCache(*this);
1343 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1351 support::FileNameList const & Buffer::getBibfilesCache() const
1353 // If this is a child document, use the parent's cache instead.
1354 if (d->parent_buffer)
1355 return d->parent_buffer->getBibfilesCache();
1357 // We update the cache when first used instead of at loading time.
1358 if (d->bibfilesCache_.empty())
1359 const_cast<Buffer *>(this)->updateBibfilesCache();
1361 return d->bibfilesCache_;
1365 BiblioInfo const & Buffer::masterBibInfo() const
1367 // if this is a child document and the parent is already loaded
1368 // use the parent's list instead [ale990412]
1369 Buffer const * const tmp = masterBuffer();
1372 return tmp->masterBibInfo();
1373 return localBibInfo();
1377 BiblioInfo const & Buffer::localBibInfo() const
1379 support::FileNameList const & bibfilesCache = getBibfilesCache();
1380 // compare the cached timestamps with the actual ones.
1381 bool changed = false;
1382 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1383 support::FileNameList::const_iterator en = bibfilesCache.end();
1384 for (; ei != en; ++ ei) {
1385 time_t lastw = ei->lastModified();
1386 if (lastw != d->bibfileStatus_[*ei]) {
1388 d->bibfileStatus_[*ei] = lastw;
1394 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1395 it->fillWithBibKeys(d->bibinfo_, it);
1401 bool Buffer::isDepClean(string const & name) const
1403 DepClean::const_iterator const it = d->dep_clean.find(name);
1404 if (it == d->dep_clean.end())
1410 void Buffer::markDepClean(string const & name)
1412 d->dep_clean[name] = true;
1416 bool Buffer::dispatch(string const & command, bool * result)
1418 return dispatch(lyxaction.lookupFunc(command), result);
1422 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1424 bool dispatched = true;
1426 switch (func.action) {
1427 case LFUN_BUFFER_EXPORT: {
1428 bool const tmp = doExport(to_utf8(func.argument()), false);
1434 case LFUN_BRANCH_ACTIVATE:
1435 case LFUN_BRANCH_DEACTIVATE: {
1436 BranchList & branchList = params().branchlist();
1437 docstring const branchName = func.argument();
1438 Branch * branch = branchList.find(branchName);
1440 LYXERR0("Branch " << branchName << " does not exist.");
1442 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1454 void Buffer::changeLanguage(Language const * from, Language const * to)
1456 LASSERT(from, /**/);
1459 for_each(par_iterator_begin(),
1461 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1465 bool Buffer::isMultiLingual() const
1467 ParConstIterator end = par_iterator_end();
1468 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1469 if (it->isMultiLingual(params()))
1476 DocIterator Buffer::getParFromID(int const id) const
1479 // John says this is called with id == -1 from undo
1480 lyxerr << "getParFromID(), id: " << id << endl;
1481 return doc_iterator_end(inset());
1484 for (DocIterator it = doc_iterator_begin(inset()); !it.atEnd(); it.forwardPar())
1485 if (it.paragraph().id() == id)
1488 return doc_iterator_end(inset());
1492 bool Buffer::hasParWithID(int const id) const
1494 return !getParFromID(id).atEnd();
1498 ParIterator Buffer::par_iterator_begin()
1500 return ParIterator(doc_iterator_begin(inset()));
1504 ParIterator Buffer::par_iterator_end()
1506 return ParIterator(doc_iterator_end(inset()));
1510 ParConstIterator Buffer::par_iterator_begin() const
1512 return lyx::par_const_iterator_begin(inset());
1516 ParConstIterator Buffer::par_iterator_end() const
1518 return lyx::par_const_iterator_end(inset());
1522 Language const * Buffer::language() const
1524 return params().language;
1528 docstring const Buffer::B_(string const & l10n) const
1530 return params().B_(l10n);
1534 bool Buffer::isClean() const
1536 return d->lyx_clean;
1540 bool Buffer::isBakClean() const
1542 return d->bak_clean;
1546 bool Buffer::isExternallyModified(CheckMethod method) const
1548 LASSERT(d->filename.exists(), /**/);
1549 // if method == timestamp, check timestamp before checksum
1550 return (method == checksum_method
1551 || d->timestamp_ != d->filename.lastModified())
1552 && d->checksum_ != d->filename.checksum();
1556 void Buffer::saveCheckSum(FileName const & file) const
1558 if (file.exists()) {
1559 d->timestamp_ = file.lastModified();
1560 d->checksum_ = file.checksum();
1562 // in the case of save to a new file.
1569 void Buffer::markClean() const
1571 if (!d->lyx_clean) {
1572 d->lyx_clean = true;
1575 // if the .lyx file has been saved, we don't need an
1577 d->bak_clean = true;
1581 void Buffer::markBakClean() const
1583 d->bak_clean = true;
1587 void Buffer::setUnnamed(bool flag)
1593 bool Buffer::isUnnamed() const
1599 // FIXME: this function should be moved to buffer_pimpl.C
1600 void Buffer::markDirty()
1603 d->lyx_clean = false;
1606 d->bak_clean = false;
1608 DepClean::iterator it = d->dep_clean.begin();
1609 DepClean::const_iterator const end = d->dep_clean.end();
1611 for (; it != end; ++it)
1616 FileName Buffer::fileName() const
1622 string Buffer::absFileName() const
1624 return d->filename.absFilename();
1628 string Buffer::filePath() const
1630 return d->filename.onlyPath().absFilename() + "/";
1634 bool Buffer::isReadonly() const
1636 return d->read_only;
1640 void Buffer::setParent(Buffer const * buffer)
1642 // Avoids recursive include.
1643 d->parent_buffer = buffer == this ? 0 : buffer;
1648 Buffer const * Buffer::parent()
1650 return d->parent_buffer;
1654 Buffer const * Buffer::masterBuffer() const
1656 if (!d->parent_buffer)
1659 return d->parent_buffer->masterBuffer();
1663 template<typename M>
1664 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
1669 typename M::iterator it = m.lower_bound(x);
1670 if (it == m.begin())
1678 MacroData const * Buffer::getBufferMacro(docstring const & name,
1679 DocIterator const & pos) const
1681 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
1683 // if paragraphs have no macro context set, pos will be empty
1687 // we haven't found anything yet
1688 DocIterator bestPos = par_iterator_begin();
1689 MacroData const * bestData = 0;
1691 // find macro definitions for name
1692 Impl::NamePositionScopeMacroMap::iterator nameIt
1693 = d->macros.find(name);
1694 if (nameIt != d->macros.end()) {
1695 // find last definition in front of pos or at pos itself
1696 Impl::PositionScopeMacroMap::const_iterator it
1697 = greatest_below(nameIt->second, pos);
1698 if (it != nameIt->second.end()) {
1700 // scope ends behind pos?
1701 if (pos < it->second.first) {
1702 // Looks good, remember this. If there
1703 // is no external macro behind this,
1704 // we found the right one already.
1705 bestPos = it->first;
1706 bestData = &it->second.second;
1710 // try previous macro if there is one
1711 if (it == nameIt->second.begin())
1718 // find macros in included files
1719 Impl::PositionScopeBufferMap::const_iterator it
1720 = greatest_below(d->position_to_children, pos);
1721 if (it == d->position_to_children.end())
1722 // no children before
1726 // do we know something better (i.e. later) already?
1727 if (it->first < bestPos )
1730 // scope ends behind pos?
1731 if (pos < it->second.first) {
1732 // look for macro in external file
1733 d->macro_lock = true;
1734 MacroData const * data
1735 = it->second.second->getMacro(name, false);
1736 d->macro_lock = false;
1738 bestPos = it->first;
1744 // try previous file if there is one
1745 if (it == d->position_to_children.begin())
1750 // return the best macro we have found
1755 MacroData const * Buffer::getMacro(docstring const & name,
1756 DocIterator const & pos, bool global) const
1761 // query buffer macros
1762 MacroData const * data = getBufferMacro(name, pos);
1766 // If there is a master buffer, query that
1767 if (d->parent_buffer) {
1768 d->macro_lock = true;
1769 MacroData const * macro = d->parent_buffer->getMacro(
1770 name, *this, false);
1771 d->macro_lock = false;
1777 data = MacroTable::globalMacros().get(name);
1786 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
1788 // set scope end behind the last paragraph
1789 DocIterator scope = par_iterator_begin();
1790 scope.pit() = scope.lastpit() + 1;
1792 return getMacro(name, scope, global);
1796 MacroData const * Buffer::getMacro(docstring const & name,
1797 Buffer const & child, bool global) const
1799 // look where the child buffer is included first
1800 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
1801 if (it == d->children_positions.end())
1804 // check for macros at the inclusion position
1805 return getMacro(name, it->second, global);
1809 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
1811 pit_type lastpit = it.lastpit();
1813 // look for macros in each paragraph
1814 while (it.pit() <= lastpit) {
1815 Paragraph & par = it.paragraph();
1817 // iterate over the insets of the current paragraph
1818 InsetList const & insets = par.insetList();
1819 InsetList::const_iterator iit = insets.begin();
1820 InsetList::const_iterator end = insets.end();
1821 for (; iit != end; ++iit) {
1822 it.pos() = iit->pos;
1824 // is it a nested text inset?
1825 if (iit->inset->asInsetText()) {
1826 // Inset needs its own scope?
1827 InsetText const * itext
1828 = iit->inset->asInsetText();
1829 bool newScope = itext->isMacroScope();
1831 // scope which ends just behind the inset
1832 DocIterator insetScope = it;
1835 // collect macros in inset
1836 it.push_back(CursorSlice(*iit->inset));
1837 updateMacros(it, newScope ? insetScope : scope);
1842 // is it an external file?
1843 if (iit->inset->lyxCode() == INCLUDE_CODE) {
1844 // get buffer of external file
1845 InsetCommand const & inset
1846 = static_cast<InsetCommand const &>(*iit->inset);
1847 InsetCommandParams const & ip = inset.params();
1848 d->macro_lock = true;
1849 Buffer * child = loadIfNeeded(*this, ip);
1850 d->macro_lock = false;
1854 // register its position, but only when it is
1855 // included first in the buffer
1856 if (d->children_positions.find(child)
1857 == d->children_positions.end())
1858 d->children_positions[child] = it;
1860 // register child with its scope
1861 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
1865 if (iit->inset->lyxCode() != MATHMACRO_CODE)
1869 MathMacroTemplate & macroTemplate
1870 = static_cast<MathMacroTemplate &>(*iit->inset);
1871 MacroContext mc(*this, it);
1872 macroTemplate.updateToContext(mc);
1875 bool valid = macroTemplate.validMacro();
1876 // FIXME: Should be fixNameAndCheckIfValid() in fact,
1877 // then the BufferView's cursor will be invalid in
1878 // some cases which leads to crashes.
1883 d->macros[macroTemplate.name()][it] =
1884 Impl::ScopeMacro(scope, MacroData(*this, it));
1894 void Buffer::updateMacros() const
1899 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
1901 // start with empty table
1903 d->children_positions.clear();
1904 d->position_to_children.clear();
1906 // Iterate over buffer, starting with first paragraph
1907 // The scope must be bigger than any lookup DocIterator
1908 // later. For the global lookup, lastpit+1 is used, hence
1909 // we use lastpit+2 here.
1910 DocIterator it = par_iterator_begin();
1911 DocIterator outerScope = it;
1912 outerScope.pit() = outerScope.lastpit() + 2;
1913 updateMacros(it, outerScope);
1917 void Buffer::updateMacroInstances() const
1919 LYXERR(Debug::MACROS, "updateMacroInstances for "
1920 << d->filename.onlyFileName());
1921 DocIterator it = doc_iterator_begin(inset());
1922 DocIterator end = doc_iterator_end(inset());
1923 for (; it != end; it.forwardPos()) {
1924 // look for MathData cells in InsetMathNest insets
1925 Inset * inset = it.nextInset();
1929 InsetMath * minset = inset->asInsetMath();
1933 // update macro in all cells of the InsetMathNest
1934 DocIterator::idx_type n = minset->nargs();
1935 MacroContext mc = MacroContext(*this, it);
1936 for (DocIterator::idx_type i = 0; i < n; ++i) {
1937 MathData & data = minset->cell(i);
1938 data.updateMacros(0, mc);
1944 void Buffer::listMacroNames(MacroNameSet & macros) const
1949 d->macro_lock = true;
1951 // loop over macro names
1952 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
1953 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
1954 for (; nameIt != nameEnd; ++nameIt)
1955 macros.insert(nameIt->first);
1957 // loop over children
1958 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
1959 Impl::BufferPositionMap::iterator end = d->children_positions.end();
1960 for (; it != end; ++it)
1961 it->first->listMacroNames(macros);
1964 if (d->parent_buffer)
1965 d->parent_buffer->listMacroNames(macros);
1967 d->macro_lock = false;
1971 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
1973 if (!d->parent_buffer)
1977 d->parent_buffer->listMacroNames(names);
1980 MacroNameSet::iterator it = names.begin();
1981 MacroNameSet::iterator end = names.end();
1982 for (; it != end; ++it) {
1984 MacroData const * data =
1985 d->parent_buffer->getMacro(*it, *this, false);
1987 macros.insert(data);
1989 // we cannot access the original MathMacroTemplate anymore
1990 // here to calls validate method. So we do its work here manually.
1991 // FIXME: somehow make the template accessible here.
1992 if (data->optionals() > 0)
1993 features.require("xargs");
1999 Buffer::References & Buffer::references(docstring const & label)
2001 if (d->parent_buffer)
2002 return const_cast<Buffer *>(masterBuffer())->references(label);
2004 RefCache::iterator it = d->ref_cache_.find(label);
2005 if (it != d->ref_cache_.end())
2006 return it->second.second;
2008 static InsetLabel const * dummy_il = 0;
2009 static References const dummy_refs;
2010 it = d->ref_cache_.insert(
2011 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2012 return it->second.second;
2016 Buffer::References const & Buffer::references(docstring const & label) const
2018 return const_cast<Buffer *>(this)->references(label);
2022 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2024 masterBuffer()->d->ref_cache_[label].first = il;
2028 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2030 return masterBuffer()->d->ref_cache_[label].first;
2034 void Buffer::clearReferenceCache() const
2036 if (!d->parent_buffer)
2037 d->ref_cache_.clear();
2041 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2044 //FIXME: This does not work for child documents yet.
2045 LASSERT(code == CITE_CODE, /**/);
2046 // Check if the label 'from' appears more than once
2047 vector<docstring> labels;
2049 BiblioInfo const & keys = masterBibInfo();
2050 BiblioInfo::const_iterator bit = keys.begin();
2051 BiblioInfo::const_iterator bend = keys.end();
2053 for (; bit != bend; ++bit)
2055 labels.push_back(bit->first);
2058 if (count(labels.begin(), labels.end(), from) > 1)
2061 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2062 if (it->lyxCode() == code) {
2063 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2064 docstring const oldValue = inset.getParam(paramName);
2065 if (oldValue == from)
2066 inset.setParam(paramName, to);
2072 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2073 pit_type par_end, bool full_source)
2075 OutputParams runparams(¶ms().encoding());
2076 runparams.nice = true;
2077 runparams.flavor = OutputParams::LATEX;
2078 runparams.linelen = lyxrc.plaintext_linelen;
2079 // No side effect of file copying and image conversion
2080 runparams.dryrun = true;
2084 os << "% " << _("Preview source code") << "\n\n";
2085 d->texrow.newline();
2086 d->texrow.newline();
2088 writeLaTeXSource(os, filePath(), runparams, true, true);
2090 writeDocBookSource(os, absFileName(), runparams, false);
2092 runparams.par_begin = par_begin;
2093 runparams.par_end = par_end;
2094 if (par_begin + 1 == par_end) {
2096 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2100 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2101 convert<docstring>(par_begin),
2102 convert<docstring>(par_end - 1))
2105 d->texrow.newline();
2106 d->texrow.newline();
2107 // output paragraphs
2109 latexParagraphs(*this, text(), os, d->texrow, runparams);
2112 docbookParagraphs(paragraphs(), *this, os, runparams);
2117 ErrorList & Buffer::errorList(string const & type) const
2119 static ErrorList emptyErrorList;
2120 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2121 if (I == d->errorLists.end())
2122 return emptyErrorList;
2128 void Buffer::structureChanged() const
2131 gui_->structureChanged();
2135 void Buffer::errors(string const & err) const
2142 void Buffer::message(docstring const & msg) const
2149 void Buffer::setBusy(bool on) const
2156 void Buffer::setReadOnly(bool on) const
2159 d->wa_->setReadOnly(on);
2163 void Buffer::updateTitles() const
2166 d->wa_->updateTitles();
2170 void Buffer::resetAutosaveTimers() const
2173 gui_->resetAutosaveTimers();
2177 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2186 class AutoSaveBuffer : public ForkedProcess {
2189 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2190 : buffer_(buffer), fname_(fname) {}
2192 virtual boost::shared_ptr<ForkedProcess> clone() const
2194 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2199 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2200 from_utf8(fname_.absFilename())));
2201 return run(DontWait);
2205 virtual int generateChild();
2207 Buffer const & buffer_;
2212 int AutoSaveBuffer::generateChild()
2214 // tmp_ret will be located (usually) in /tmp
2215 // will that be a problem?
2216 // Note that this calls ForkedCalls::fork(), so it's
2217 // ok cross-platform.
2218 pid_t const pid = fork();
2219 // If you want to debug the autosave
2220 // you should set pid to -1, and comment out the fork.
2221 if (pid != 0 && pid != -1)
2224 // pid = -1 signifies that lyx was unable
2225 // to fork. But we will do the save
2227 bool failed = false;
2228 FileName const tmp_ret = FileName::tempName("lyxauto");
2229 if (!tmp_ret.empty()) {
2230 buffer_.writeFile(tmp_ret);
2231 // assume successful write of tmp_ret
2232 if (!tmp_ret.moveTo(fname_))
2238 // failed to write/rename tmp_ret so try writing direct
2239 if (!buffer_.writeFile(fname_)) {
2240 // It is dangerous to do this in the child,
2241 // but safe in the parent, so...
2242 if (pid == -1) // emit message signal.
2243 buffer_.message(_("Autosave failed!"));
2247 if (pid == 0) // we are the child so...
2256 // Perfect target for a thread...
2257 void Buffer::autoSave() const
2259 if (isBakClean() || isReadonly()) {
2260 // We don't save now, but we'll try again later
2261 resetAutosaveTimers();
2265 // emit message signal.
2266 message(_("Autosaving current document..."));
2268 // create autosave filename
2269 string fname = filePath();
2271 fname += d->filename.onlyFileName();
2274 AutoSaveBuffer autosave(*this, FileName(fname));
2278 resetAutosaveTimers();
2282 string Buffer::bufferFormat() const
2292 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2293 string & result_file) const
2295 string backend_format;
2296 OutputParams runparams(¶ms().encoding());
2297 runparams.flavor = OutputParams::LATEX;
2298 runparams.linelen = lyxrc.plaintext_linelen;
2299 vector<string> backs = backends();
2300 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2301 // Get shortest path to format
2302 Graph::EdgePath path;
2303 for (vector<string>::const_iterator it = backs.begin();
2304 it != backs.end(); ++it) {
2305 Graph::EdgePath p = theConverters().getPath(*it, format);
2306 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2307 backend_format = *it;
2312 runparams.flavor = theConverters().getFlavor(path);
2314 Alert::error(_("Couldn't export file"),
2315 bformat(_("No information for exporting the format %1$s."),
2316 formats.prettyName(format)));
2320 backend_format = format;
2321 // FIXME: Don't hardcode format names here, but use a flag
2322 if (backend_format == "pdflatex")
2323 runparams.flavor = OutputParams::PDFLATEX;
2326 string filename = latexName(false);
2327 filename = addName(temppath(), filename);
2328 filename = changeExtension(filename,
2329 formats.extension(backend_format));
2332 updateMacroInstances();
2334 // Plain text backend
2335 if (backend_format == "text")
2336 writePlaintextFile(*this, FileName(filename), runparams);
2338 else if (backend_format == "lyx")
2339 writeFile(FileName(filename));
2341 else if (isDocBook()) {
2342 runparams.nice = !put_in_tempdir;
2343 makeDocBookFile(FileName(filename), runparams);
2346 else if (backend_format == format) {
2347 runparams.nice = true;
2348 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2350 } else if (!lyxrc.tex_allows_spaces
2351 && contains(filePath(), ' ')) {
2352 Alert::error(_("File name error"),
2353 _("The directory path to the document cannot contain spaces."));
2356 runparams.nice = false;
2357 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2361 string const error_type = (format == "program")
2362 ? "Build" : bufferFormat();
2363 string const ext = formats.extension(format);
2364 FileName const tmp_result_file(changeExtension(filename, ext));
2365 bool const success = theConverters().convert(this, FileName(filename),
2366 tmp_result_file, FileName(absFileName()), backend_format, format,
2367 errorList(error_type));
2368 // Emit the signal to show the error list.
2369 if (format != backend_format)
2374 if (put_in_tempdir) {
2375 result_file = tmp_result_file.absFilename();
2379 result_file = changeExtension(absFileName(), ext);
2380 // We need to copy referenced files (e. g. included graphics
2381 // if format == "dvi") to the result dir.
2382 vector<ExportedFile> const files =
2383 runparams.exportdata->externalFiles(format);
2384 string const dest = onlyPath(result_file);
2385 CopyStatus status = SUCCESS;
2386 for (vector<ExportedFile>::const_iterator it = files.begin();
2387 it != files.end() && status != CANCEL; ++it) {
2388 string const fmt = formats.getFormatFromFile(it->sourceName);
2389 status = copyFile(fmt, it->sourceName,
2390 makeAbsPath(it->exportName, dest),
2391 it->exportName, status == FORCE);
2393 if (status == CANCEL) {
2394 message(_("Document export cancelled."));
2395 } else if (tmp_result_file.exists()) {
2396 // Finally copy the main file
2397 status = copyFile(format, tmp_result_file,
2398 FileName(result_file), result_file,
2400 message(bformat(_("Document exported as %1$s "
2402 formats.prettyName(format),
2403 makeDisplayPath(result_file)));
2405 // This must be a dummy converter like fax (bug 1888)
2406 message(bformat(_("Document exported as %1$s"),
2407 formats.prettyName(format)));
2414 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2417 return doExport(format, put_in_tempdir, result_file);
2421 bool Buffer::preview(string const & format) const
2424 if (!doExport(format, true, result_file))
2426 return formats.view(*this, FileName(result_file), format);
2430 bool Buffer::isExportable(string const & format) const
2432 vector<string> backs = backends();
2433 for (vector<string>::const_iterator it = backs.begin();
2434 it != backs.end(); ++it)
2435 if (theConverters().isReachable(*it, format))
2441 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2443 vector<string> backs = backends();
2444 vector<Format const *> result =
2445 theConverters().getReachable(backs[0], only_viewable, true);
2446 for (vector<string>::const_iterator it = backs.begin() + 1;
2447 it != backs.end(); ++it) {
2448 vector<Format const *> r =
2449 theConverters().getReachable(*it, only_viewable, false);
2450 result.insert(result.end(), r.begin(), r.end());
2456 vector<string> Buffer::backends() const
2459 if (params().baseClass()->isTeXClassAvailable()) {
2460 v.push_back(bufferFormat());
2461 // FIXME: Don't hardcode format names here, but use a flag
2462 if (v.back() == "latex")
2463 v.push_back("pdflatex");
2465 v.push_back("text");
2471 bool Buffer::readFileHelper(FileName const & s)
2473 // File information about normal file
2475 docstring const file = makeDisplayPath(s.absFilename(), 50);
2476 docstring text = bformat(_("The specified document\n%1$s"
2477 "\ncould not be read."), file);
2478 Alert::error(_("Could not read document"), text);
2482 // Check if emergency save file exists and is newer.
2483 FileName const e(s.absFilename() + ".emergency");
2485 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2486 docstring const file = makeDisplayPath(s.absFilename(), 20);
2487 docstring const text =
2488 bformat(_("An emergency save of the document "
2490 "Recover emergency save?"), file);
2491 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2492 _("&Recover"), _("&Load Original"),
2496 // the file is not saved if we load the emergency file.
2506 // Now check if autosave file is newer.
2507 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2509 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2510 docstring const file = makeDisplayPath(s.absFilename(), 20);
2511 docstring const text =
2512 bformat(_("The backup of the document "
2513 "%1$s is newer.\n\nLoad the "
2514 "backup instead?"), file);
2515 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2516 _("&Load backup"), _("Load &original"),
2520 // the file is not saved if we load the autosave file.
2524 // Here we delete the autosave
2535 bool Buffer::loadLyXFile(FileName const & s)
2537 if (s.isReadableFile()) {
2538 if (readFileHelper(s)) {
2539 lyxvc().file_found_hook(s);
2540 if (!s.isWritable())
2545 docstring const file = makeDisplayPath(s.absFilename(), 20);
2546 // Here we probably should run
2547 if (LyXVC::file_not_found_hook(s)) {
2548 docstring const text =
2549 bformat(_("Do you want to retrieve the document"
2550 " %1$s from version control?"), file);
2551 int const ret = Alert::prompt(_("Retrieve from version control?"),
2552 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2555 // How can we know _how_ to do the checkout?
2556 // With the current VC support it has to be,
2557 // a RCS file since CVS do not have special ,v files.
2559 return loadLyXFile(s);
2567 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2569 TeXErrors::Errors::const_iterator cit = terr.begin();
2570 TeXErrors::Errors::const_iterator end = terr.end();
2572 for (; cit != end; ++cit) {
2575 int errorRow = cit->error_in_line;
2576 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2582 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2583 } while (found && id_start == id_end && pos_start == pos_end);
2585 errorList.push_back(ErrorItem(cit->error_desc,
2586 cit->error_text, id_start, pos_start, pos_end));