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 "DispatchResult.h"
28 #include "DocIterator.h"
30 #include "ErrorList.h"
33 #include "FuncRequest.h"
34 #include "FuncStatus.h"
35 #include "IndicesList.h"
36 #include "InsetIterator.h"
37 #include "InsetList.h"
39 #include "LaTeXFeatures.h"
43 #include "LyXAction.h"
47 #include "output_docbook.h"
49 #include "output_latex.h"
50 #include "output_xhtml.h"
51 #include "output_plaintext.h"
52 #include "paragraph_funcs.h"
53 #include "Paragraph.h"
54 #include "ParagraphParameters.h"
55 #include "ParIterator.h"
56 #include "PDFOptions.h"
57 #include "SpellChecker.h"
60 #include "TexStream.h"
62 #include "TextClass.h"
63 #include "TocBackend.h"
65 #include "VCBackend.h"
67 #include "WordLangTuple.h"
70 #include "insets/InsetBibitem.h"
71 #include "insets/InsetBibtex.h"
72 #include "insets/InsetBranch.h"
73 #include "insets/InsetInclude.h"
74 #include "insets/InsetText.h"
76 #include "mathed/MacroTable.h"
77 #include "mathed/MathMacroTemplate.h"
78 #include "mathed/MathSupport.h"
80 #include "frontends/alert.h"
81 #include "frontends/Delegates.h"
82 #include "frontends/WorkAreaManager.h"
84 #include "graphics/Previews.h"
86 #include "support/lassert.h"
87 #include "support/convert.h"
88 #include "support/debug.h"
89 #include "support/docstring_list.h"
90 #include "support/ExceptionMessage.h"
91 #include "support/FileName.h"
92 #include "support/FileNameList.h"
93 #include "support/filetools.h"
94 #include "support/ForkedCalls.h"
95 #include "support/gettext.h"
96 #include "support/gzstream.h"
97 #include "support/lstrings.h"
98 #include "support/lyxalgo.h"
99 #include "support/os.h"
100 #include "support/Package.h"
101 #include "support/Path.h"
102 #include "support/Systemcall.h"
103 #include "support/textutils.h"
104 #include "support/types.h"
106 #include <boost/bind.hpp>
107 #include <boost/shared_ptr.hpp>
119 using namespace lyx::support;
123 namespace Alert = frontend::Alert;
124 namespace os = support::os;
128 // Do not remove the comment below, so we get merge conflict in
129 // independent branches. Instead add your own.
130 int const LYX_FORMAT = 363; // uwestoehr: support for longtable alignment
132 typedef map<string, bool> DepClean;
133 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
135 void showPrintError(string const & name)
137 docstring str = bformat(_("Could not print the document %1$s.\n"
138 "Check that your printer is set up correctly."),
139 makeDisplayPath(name, 50));
140 Alert::error(_("Print document failed"), str);
145 class BufferSet : public std::set<Buffer const *> {};
150 Impl(Buffer & parent, FileName const & file, bool readonly);
164 mutable TexRow texrow;
166 /// need to regenerate .tex?
170 mutable bool lyx_clean;
172 /// is autosave needed?
173 mutable bool bak_clean;
175 /// is this a unnamed file (New...)?
181 /// name of the file the buffer is associated with.
184 /** Set to true only when the file is fully loaded.
185 * Used to prevent the premature generation of previews
186 * and by the citation inset.
188 bool file_fully_loaded;
191 mutable TocBackend toc_backend;
194 typedef pair<DocIterator, MacroData> ScopeMacro;
195 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
196 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
197 /// map from the macro name to the position map,
198 /// which maps the macro definition position to the scope and the MacroData.
199 NamePositionScopeMacroMap macros;
202 /// positions of child buffers in the buffer
203 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
204 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
205 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
206 /// position of children buffers in this buffer
207 BufferPositionMap children_positions;
208 /// map from children inclusion positions to their scope and their buffer
209 PositionScopeBufferMap position_to_children;
211 /// Container for all sort of Buffer dependant errors.
212 map<string, ErrorList> errorLists;
214 /// timestamp and checksum used to test if the file has been externally
215 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
217 unsigned long checksum_;
220 frontend::WorkAreaManager * wa_;
225 /// A cache for the bibfiles (including bibfiles of loaded child
226 /// documents), needed for appropriate update of natbib labels.
227 mutable support::FileNameList bibfilesCache_;
229 // FIXME The caching mechanism could be improved. At present, we have a
230 // cache for each Buffer, that caches all the bibliography info for that
231 // Buffer. A more efficient solution would be to have a global cache per
232 // file, and then to construct the Buffer's bibinfo from that.
233 /// A cache for bibliography info
234 mutable BiblioInfo bibinfo_;
235 /// whether the bibinfo cache is valid
236 bool bibinfoCacheValid_;
237 /// Cache of timestamps of .bib files
238 map<FileName, time_t> bibfileStatus_;
240 mutable RefCache ref_cache_;
242 /// our Text that should be wrapped in an InsetText
245 /// This is here to force the test to be done whenever parent_buffer
247 Buffer const * parent() const {
248 // if parent_buffer is not loaded, then it has been unloaded,
249 // which means that parent_buffer is an invalid pointer. So we
250 // set it to null in that case.
251 if (!theBufferList().isLoaded(parent_buffer))
253 return parent_buffer;
256 void setParent(Buffer const * pb) { parent_buffer = pb; }
258 /// So we can force access via the accessors.
259 mutable Buffer const * parent_buffer;
263 /// Creates the per buffer temporary directory
264 static FileName createBufferTmpDir()
267 // We are in our own directory. Why bother to mangle name?
268 // In fact I wrote this code to circumvent a problematic behaviour
269 // (bug?) of EMX mkstemp().
270 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
271 convert<string>(count++));
273 if (!tmpfl.createDirectory(0777)) {
274 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
275 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
276 from_utf8(tmpfl.absFilename())));
282 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
283 : lyx_clean(true), bak_clean(true), unnamed(false),
284 read_only(readonly_), filename(file), file_fully_loaded(false),
285 toc_backend(&parent), macro_lock(false), timestamp_(0),
286 checksum_(0), wa_(0), undo_(parent), bibinfoCacheValid_(false),
289 temppath = createBufferTmpDir();
290 lyxvc.setBuffer(&parent);
292 wa_ = new frontend::WorkAreaManager;
296 Buffer::Buffer(string const & file, bool readonly)
297 : d(new Impl(*this, FileName(file), readonly)), gui_(0)
299 LYXERR(Debug::INFO, "Buffer::Buffer()");
301 d->inset = new InsetText(*this);
302 d->inset->setAutoBreakRows(true);
303 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
309 LYXERR(Debug::INFO, "Buffer::~Buffer()");
310 // here the buffer should take care that it is
311 // saved properly, before it goes into the void.
313 // GuiView already destroyed
316 if (d->unnamed && d->filename.extension() == "internal") {
317 // No need to do additional cleanups for internal buffer.
322 // loop over children
323 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
324 Impl::BufferPositionMap::iterator end = d->children_positions.end();
325 for (; it != end; ++it) {
326 Buffer * child = const_cast<Buffer *>(it->first);
327 // The child buffer might have been closed already.
328 if (theBufferList().isLoaded(child))
329 theBufferList().releaseChild(this, child);
332 // clear references to children in macro tables
333 d->children_positions.clear();
334 d->position_to_children.clear();
336 if (!d->temppath.destroyDirectory()) {
337 Alert::warning(_("Could not remove temporary directory"),
338 bformat(_("Could not remove the temporary directory %1$s"),
339 from_utf8(d->temppath.absFilename())));
342 // Remove any previewed LaTeX snippets associated with this buffer.
343 thePreviews().removeLoader(*this);
349 void Buffer::changed() const
356 frontend::WorkAreaManager & Buffer::workAreaManager() const
358 LASSERT(d->wa_, /**/);
363 Text & Buffer::text() const
365 return d->inset->text();
369 Inset & Buffer::inset() const
375 BufferParams & Buffer::params()
381 BufferParams const & Buffer::params() const
387 ParagraphList & Buffer::paragraphs()
389 return text().paragraphs();
393 ParagraphList const & Buffer::paragraphs() const
395 return text().paragraphs();
399 LyXVC & Buffer::lyxvc()
405 LyXVC const & Buffer::lyxvc() const
411 string const Buffer::temppath() const
413 return d->temppath.absFilename();
417 TexRow & Buffer::texrow()
423 TexRow const & Buffer::texrow() const
429 TocBackend & Buffer::tocBackend() const
431 return d->toc_backend;
435 Undo & Buffer::undo()
441 string Buffer::latexName(bool const no_path) const
443 FileName latex_name = makeLatexName(d->filename);
444 return no_path ? latex_name.onlyFileName()
445 : latex_name.absFilename();
449 string Buffer::logName(LogType * type) const
451 string const filename = latexName(false);
453 if (filename.empty()) {
459 string const path = temppath();
461 FileName const fname(addName(temppath(),
462 onlyFilename(changeExtension(filename,
465 // FIXME: how do we know this is the name of the build log?
466 FileName const bname(
467 addName(path, onlyFilename(
468 changeExtension(filename,
469 formats.extension(bufferFormat()) + ".out"))));
471 // Also consider the master buffer log file
472 FileName masterfname = fname;
474 if (masterBuffer() != this) {
475 string const mlogfile = masterBuffer()->logName(&mtype);
476 masterfname = FileName(mlogfile);
479 // If no Latex log or Build log is newer, show Build log
480 if (bname.exists() &&
481 ((!fname.exists() && !masterfname.exists())
482 || (fname.lastModified() < bname.lastModified()
483 && masterfname.lastModified() < bname.lastModified()))) {
484 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
487 return bname.absFilename();
488 // If we have a newer master file log or only a master log, show this
489 } else if (fname != masterfname
490 && (!fname.exists() && (masterfname.exists()
491 || fname.lastModified() < masterfname.lastModified()))) {
492 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
495 return masterfname.absFilename();
497 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
500 return fname.absFilename();
504 void Buffer::setReadonly(bool const flag)
506 if (d->read_only != flag) {
513 void Buffer::setFileName(string const & newfile)
515 d->filename = makeAbsPath(newfile);
516 setReadonly(d->filename.isReadOnly());
521 int Buffer::readHeader(Lexer & lex)
523 int unknown_tokens = 0;
525 int begin_header_line = -1;
527 // Initialize parameters that may be/go lacking in header:
528 params().branchlist().clear();
529 params().preamble.erase();
530 params().options.erase();
531 params().master.erase();
532 params().float_placement.erase();
533 params().paperwidth.erase();
534 params().paperheight.erase();
535 params().leftmargin.erase();
536 params().rightmargin.erase();
537 params().topmargin.erase();
538 params().bottommargin.erase();
539 params().headheight.erase();
540 params().headsep.erase();
541 params().footskip.erase();
542 params().columnsep.erase();
543 params().fontsCJK.erase();
544 params().listings_params.clear();
545 params().clearLayoutModules();
546 params().clearRemovedModules();
547 params().pdfoptions().clear();
548 params().indiceslist().clear();
549 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
551 for (int i = 0; i < 4; ++i) {
552 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
553 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
556 ErrorList & errorList = d->errorLists["Parse"];
565 if (token == "\\end_header")
569 if (token == "\\begin_header") {
570 begin_header_line = line;
574 LYXERR(Debug::PARSER, "Handling document header token: `"
577 string unknown = params().readToken(lex, token, d->filename.onlyPath());
578 if (!unknown.empty()) {
579 if (unknown[0] != '\\' && token == "\\textclass") {
580 Alert::warning(_("Unknown document class"),
581 bformat(_("Using the default document class, because the "
582 "class %1$s is unknown."), from_utf8(unknown)));
585 docstring const s = bformat(_("Unknown token: "
589 errorList.push_back(ErrorItem(_("Document header error"),
594 if (begin_header_line) {
595 docstring const s = _("\\begin_header is missing");
596 errorList.push_back(ErrorItem(_("Document header error"),
600 params().makeDocumentClass();
602 return unknown_tokens;
607 // changed to be public and have one parameter
608 // Returns true if "\end_document" is not read (Asger)
609 bool Buffer::readDocument(Lexer & lex)
611 ErrorList & errorList = d->errorLists["Parse"];
614 if (!lex.checkFor("\\begin_document")) {
615 docstring const s = _("\\begin_document is missing");
616 errorList.push_back(ErrorItem(_("Document header error"),
620 // we are reading in a brand new document
621 LASSERT(paragraphs().empty(), /**/);
625 if (params().outputChanges) {
626 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
627 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
628 LaTeXFeatures::isAvailable("xcolor");
630 if (!dvipost && !xcolorulem) {
631 Alert::warning(_("Changes not shown in LaTeX output"),
632 _("Changes will not be highlighted in LaTeX output, "
633 "because neither dvipost nor xcolor/ulem are installed.\n"
634 "Please install these packages or redefine "
635 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
636 } else if (!xcolorulem) {
637 Alert::warning(_("Changes not shown in LaTeX output"),
638 _("Changes will not be highlighted in LaTeX output "
639 "when using pdflatex, because xcolor and ulem are not installed.\n"
640 "Please install both packages or redefine "
641 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
645 if (!params().master.empty()) {
646 FileName const master_file = makeAbsPath(params().master,
647 onlyPath(absFileName()));
648 if (isLyXFilename(master_file.absFilename())) {
650 checkAndLoadLyXFile(master_file, true);
652 // necessary e.g. after a reload
653 // to re-register the child (bug 5873)
654 // FIXME: clean up updateMacros (here, only
655 // child registering is needed).
656 master->updateMacros();
657 // set master as master buffer, but only
658 // if we are a real child
659 if (master->isChild(this))
661 // if the master is not fully loaded
662 // it is probably just loading this
663 // child. No warning needed then.
664 else if (master->isFullyLoaded())
665 LYXERR0("The master '"
667 << "' assigned to this document ("
669 << ") does not include "
670 "this document. Ignoring the master assignment.");
676 bool const res = text().read(*this, lex, errorList, d->inset);
679 updateMacroInstances();
684 // needed to insert the selection
685 void Buffer::insertStringAsLines(ParagraphList & pars,
686 pit_type & pit, pos_type & pos,
687 Font const & fn, docstring const & str, bool autobreakrows)
691 // insert the string, don't insert doublespace
692 bool space_inserted = true;
693 for (docstring::const_iterator cit = str.begin();
694 cit != str.end(); ++cit) {
695 Paragraph & par = pars[pit];
697 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
698 breakParagraph(params(), pars, pit, pos,
699 par.layout().isEnvironment());
702 space_inserted = true;
706 // do not insert consecutive spaces if !free_spacing
707 } else if ((*cit == ' ' || *cit == '\t') &&
708 space_inserted && !par.isFreeSpacing()) {
710 } else if (*cit == '\t') {
711 if (!par.isFreeSpacing()) {
712 // tabs are like spaces here
713 par.insertChar(pos, ' ', font, params().trackChanges);
715 space_inserted = true;
717 par.insertChar(pos, *cit, font, params().trackChanges);
719 space_inserted = true;
721 } else if (!isPrintable(*cit)) {
722 // Ignore unprintables
725 // just insert the character
726 par.insertChar(pos, *cit, font, params().trackChanges);
728 space_inserted = (*cit == ' ');
735 bool Buffer::readString(string const & s)
737 params().compressed = false;
739 // remove dummy empty par
740 paragraphs().clear();
744 FileName const name = FileName::tempName("Buffer_readString");
745 switch (readFile(lex, name, true)) {
749 // We need to call lyx2lyx, so write the input to a file
750 ofstream os(name.toFilesystemEncoding().c_str());
753 return readFile(name);
763 bool Buffer::readFile(FileName const & filename)
765 FileName fname(filename);
767 params().compressed = fname.isZippedFile();
769 // remove dummy empty par
770 paragraphs().clear();
773 if (readFile(lex, fname) != success)
780 bool Buffer::isFullyLoaded() const
782 return d->file_fully_loaded;
786 void Buffer::setFullyLoaded(bool value)
788 d->file_fully_loaded = value;
792 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
795 LASSERT(!filename.empty(), /**/);
797 // the first (non-comment) token _must_ be...
798 if (!lex.checkFor("\\lyxformat")) {
799 Alert::error(_("Document format failure"),
800 bformat(_("%1$s is not a readable LyX document."),
801 from_utf8(filename.absFilename())));
807 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
808 // if present remove ".," from string.
809 size_t dot = tmp_format.find_first_of(".,");
810 //lyxerr << " dot found at " << dot << endl;
811 if (dot != string::npos)
812 tmp_format.erase(dot, 1);
813 int const file_format = convert<int>(tmp_format);
814 //lyxerr << "format: " << file_format << endl;
816 // save timestamp and checksum of the original disk file, making sure
817 // to not overwrite them with those of the file created in the tempdir
818 // when it has to be converted to the current format.
820 // Save the timestamp and checksum of disk file. If filename is an
821 // emergency file, save the timestamp and checksum of the original lyx file
822 // because isExternallyModified will check for this file. (BUG4193)
823 string diskfile = filename.absFilename();
824 if (suffixIs(diskfile, ".emergency"))
825 diskfile = diskfile.substr(0, diskfile.size() - 10);
826 saveCheckSum(FileName(diskfile));
829 if (file_format != LYX_FORMAT) {
832 // lyx2lyx would fail
835 FileName const tmpfile = FileName::tempName("Buffer_readFile");
836 if (tmpfile.empty()) {
837 Alert::error(_("Conversion failed"),
838 bformat(_("%1$s is from a different"
839 " version of LyX, but a temporary"
840 " file for converting it could"
842 from_utf8(filename.absFilename())));
845 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
846 if (lyx2lyx.empty()) {
847 Alert::error(_("Conversion script not found"),
848 bformat(_("%1$s is from a different"
849 " version of LyX, but the"
850 " conversion script lyx2lyx"
851 " could not be found."),
852 from_utf8(filename.absFilename())));
855 ostringstream command;
856 command << os::python()
857 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
858 << " -t " << convert<string>(LYX_FORMAT)
859 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
860 << ' ' << quoteName(filename.toFilesystemEncoding());
861 string const command_str = command.str();
863 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
865 cmd_ret const ret = runCommand(command_str);
866 if (ret.first != 0) {
867 Alert::error(_("Conversion script failed"),
868 bformat(_("%1$s is from a different version"
869 " of LyX, but the lyx2lyx script"
870 " failed to convert it."),
871 from_utf8(filename.absFilename())));
874 bool const ret = readFile(tmpfile);
875 // Do stuff with tmpfile name and buffer name here.
876 return ret ? success : failure;
881 if (readDocument(lex)) {
882 Alert::error(_("Document format failure"),
883 bformat(_("%1$s ended unexpectedly, which means"
884 " that it is probably corrupted."),
885 from_utf8(filename.absFilename())));
888 d->file_fully_loaded = true;
893 // Should probably be moved to somewhere else: BufferView? LyXView?
894 bool Buffer::save() const
896 // We don't need autosaves in the immediate future. (Asger)
897 resetAutosaveTimers();
899 string const encodedFilename = d->filename.toFilesystemEncoding();
902 bool madeBackup = false;
904 // make a backup if the file already exists
905 if (lyxrc.make_backup && fileName().exists()) {
906 backupName = FileName(absFileName() + '~');
907 if (!lyxrc.backupdir_path.empty()) {
908 string const mangledName =
909 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
910 backupName = FileName(addName(lyxrc.backupdir_path,
913 if (fileName().copyTo(backupName)) {
916 Alert::error(_("Backup failure"),
917 bformat(_("Cannot create backup file %1$s.\n"
918 "Please check whether the directory exists and is writeable."),
919 from_utf8(backupName.absFilename())));
920 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
924 // ask if the disk file has been externally modified (use checksum method)
925 if (fileName().exists() && isExternallyModified(checksum_method)) {
926 docstring const file = makeDisplayPath(absFileName(), 20);
927 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
928 "you want to overwrite this file?"), file);
929 int const ret = Alert::prompt(_("Overwrite modified file?"),
930 text, 1, 1, _("&Overwrite"), _("&Cancel"));
935 if (writeFile(d->filename)) {
939 // Saving failed, so backup is not backup
941 backupName.moveTo(d->filename);
947 bool Buffer::writeFile(FileName const & fname) const
949 if (d->read_only && fname == d->filename)
954 docstring const str = bformat(_("Saving document %1$s..."),
955 makeDisplayPath(fname.absFilename()));
958 if (params().compressed) {
959 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
960 retval = ofs && write(ofs);
962 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
963 retval = ofs && write(ofs);
967 message(str + _(" could not write file!"));
971 removeAutosaveFile();
973 saveCheckSum(d->filename);
974 message(str + _(" done."));
980 bool Buffer::write(ostream & ofs) const
983 // Use the standard "C" locale for file output.
984 ofs.imbue(locale::classic());
987 // The top of the file should not be written by params().
989 // write out a comment in the top of the file
990 ofs << "#LyX " << lyx_version
991 << " created this file. For more info see http://www.lyx.org/\n"
992 << "\\lyxformat " << LYX_FORMAT << "\n"
993 << "\\begin_document\n";
995 /// For each author, set 'used' to true if there is a change
996 /// by this author in the document; otherwise set it to 'false'.
997 AuthorList::Authors::const_iterator a_it = params().authors().begin();
998 AuthorList::Authors::const_iterator a_end = params().authors().end();
999 for (; a_it != a_end; ++a_it)
1000 a_it->second.setUsed(false);
1002 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1003 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1004 for ( ; it != end; ++it)
1005 it->checkAuthors(params().authors());
1007 // now write out the buffer parameters.
1008 ofs << "\\begin_header\n";
1009 params().writeFile(ofs);
1010 ofs << "\\end_header\n";
1013 ofs << "\n\\begin_body\n";
1014 text().write(*this, ofs);
1015 ofs << "\n\\end_body\n";
1017 // Write marker that shows file is complete
1018 ofs << "\\end_document" << endl;
1020 // Shouldn't really be needed....
1023 // how to check if close went ok?
1024 // Following is an attempt... (BE 20001011)
1026 // good() returns false if any error occured, including some
1027 // formatting error.
1028 // bad() returns true if something bad happened in the buffer,
1029 // which should include file system full errors.
1034 lyxerr << "File was not closed properly." << endl;
1041 bool Buffer::makeLaTeXFile(FileName const & fname,
1042 string const & original_path,
1043 OutputParams const & runparams_in,
1044 bool output_preamble, bool output_body) const
1046 OutputParams runparams = runparams_in;
1047 if (params().useXetex)
1048 runparams.flavor = OutputParams::XETEX;
1050 string const encoding = runparams.encoding->iconvName();
1051 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1054 try { ofs.reset(encoding); }
1055 catch (iconv_codecvt_facet_exception & e) {
1056 lyxerr << "Caught iconv exception: " << e.what() << endl;
1057 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1058 "verify that the support software for your encoding (%1$s) is "
1059 "properly installed"), from_ascii(encoding)));
1062 if (!openFileWrite(ofs, fname))
1065 //TexStream ts(ofs.rdbuf(), &texrow());
1066 ErrorList & errorList = d->errorLists["Export"];
1068 bool failed_export = false;
1071 writeLaTeXSource(ofs, original_path,
1072 runparams, output_preamble, output_body);
1074 catch (EncodingException & e) {
1075 odocstringstream ods;
1076 ods.put(e.failed_char);
1078 oss << "0x" << hex << e.failed_char << dec;
1079 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1080 " (code point %2$s)"),
1081 ods.str(), from_utf8(oss.str()));
1082 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1083 "representable in the chosen encoding.\n"
1084 "Changing the document encoding to utf8 could help."),
1085 e.par_id, e.pos, e.pos + 1));
1086 failed_export = true;
1088 catch (iconv_codecvt_facet_exception & e) {
1089 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1090 _(e.what()), -1, 0, 0));
1091 failed_export = true;
1093 catch (exception const & e) {
1094 errorList.push_back(ErrorItem(_("conversion failed"),
1095 _(e.what()), -1, 0, 0));
1096 failed_export = true;
1099 lyxerr << "Caught some really weird exception..." << endl;
1105 failed_export = true;
1106 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1110 return !failed_export;
1114 void Buffer::writeLaTeXSource(odocstream & os,
1115 string const & original_path,
1116 OutputParams const & runparams_in,
1117 bool const output_preamble, bool const output_body) const
1119 // The child documents, if any, shall be already loaded at this point.
1121 OutputParams runparams = runparams_in;
1123 // Classify the unicode characters appearing in math insets
1124 Encodings::initUnicodeMath(*this);
1126 // validate the buffer.
1127 LYXERR(Debug::LATEX, " Validating buffer...");
1128 LaTeXFeatures features(*this, params(), runparams);
1130 LYXERR(Debug::LATEX, " Buffer validation done.");
1132 // The starting paragraph of the coming rows is the
1133 // first paragraph of the document. (Asger)
1134 if (output_preamble && runparams.nice) {
1135 os << "%% LyX " << lyx_version << " created this file. "
1136 "For more info, see http://www.lyx.org/.\n"
1137 "%% Do not edit unless you really know what "
1139 d->texrow.newline();
1140 d->texrow.newline();
1142 LYXERR(Debug::INFO, "lyx document header finished");
1144 // Don't move this behind the parent_buffer=0 code below,
1145 // because then the macros will not get the right "redefinition"
1146 // flag as they don't see the parent macros which are output before.
1149 // fold macros if possible, still with parent buffer as the
1150 // macros will be put in the prefix anyway.
1151 updateMacroInstances();
1153 // There are a few differences between nice LaTeX and usual files:
1154 // usual is \batchmode and has a
1155 // special input@path to allow the including of figures
1156 // with either \input or \includegraphics (what figinsets do).
1157 // input@path is set when the actual parameter
1158 // original_path is set. This is done for usual tex-file, but not
1159 // for nice-latex-file. (Matthias 250696)
1160 // Note that input@path is only needed for something the user does
1161 // in the preamble, included .tex files or ERT, files included by
1162 // LyX work without it.
1163 if (output_preamble) {
1164 if (!runparams.nice) {
1165 // code for usual, NOT nice-latex-file
1166 os << "\\batchmode\n"; // changed
1167 // from \nonstopmode
1168 d->texrow.newline();
1170 if (!original_path.empty()) {
1172 // We don't know the encoding of inputpath
1173 docstring const inputpath = from_utf8(latex_path(original_path));
1174 os << "\\makeatletter\n"
1175 << "\\def\\input@path{{"
1176 << inputpath << "/}}\n"
1177 << "\\makeatother\n";
1178 d->texrow.newline();
1179 d->texrow.newline();
1180 d->texrow.newline();
1183 // get parent macros (if this buffer has a parent) which will be
1184 // written at the document begin further down.
1185 MacroSet parentMacros;
1186 listParentMacros(parentMacros, features);
1188 // Write the preamble
1189 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1191 runparams.use_japanese = features.isRequired("japanese");
1197 os << "\\begin{document}\n";
1198 d->texrow.newline();
1200 // output the parent macros
1201 MacroSet::iterator it = parentMacros.begin();
1202 MacroSet::iterator end = parentMacros.end();
1203 for (; it != end; ++it)
1204 (*it)->write(os, true);
1205 } // output_preamble
1207 d->texrow.start(paragraphs().begin()->id(), 0);
1209 LYXERR(Debug::INFO, "preamble finished, now the body.");
1211 // if we are doing a real file with body, even if this is the
1212 // child of some other buffer, let's cut the link here.
1213 // This happens for example if only a child document is printed.
1214 Buffer const * save_parent = 0;
1215 if (output_preamble) {
1216 save_parent = d->parent();
1221 latexParagraphs(*this, text(), os, d->texrow, runparams);
1223 // Restore the parenthood if needed
1224 if (output_preamble)
1225 d->setParent(save_parent);
1227 // add this just in case after all the paragraphs
1229 d->texrow.newline();
1231 if (output_preamble) {
1232 os << "\\end{document}\n";
1233 d->texrow.newline();
1234 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1236 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1238 runparams_in.encoding = runparams.encoding;
1240 // Just to be sure. (Asger)
1241 d->texrow.newline();
1243 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1244 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1248 bool Buffer::isLatex() const
1250 return params().documentClass().outputType() == LATEX;
1254 bool Buffer::isLiterate() const
1256 return params().documentClass().outputType() == LITERATE;
1260 bool Buffer::isDocBook() const
1262 return params().documentClass().outputType() == DOCBOOK;
1266 void Buffer::makeDocBookFile(FileName const & fname,
1267 OutputParams const & runparams,
1268 bool const body_only) const
1270 LYXERR(Debug::LATEX, "makeDocBookFile...");
1273 if (!openFileWrite(ofs, fname))
1276 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1280 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1284 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1285 OutputParams const & runparams,
1286 bool const only_body) const
1288 LaTeXFeatures features(*this, params(), runparams);
1293 DocumentClass const & tclass = params().documentClass();
1294 string const top_element = tclass.latexname();
1297 if (runparams.flavor == OutputParams::XML)
1298 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1301 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1304 if (! tclass.class_header().empty())
1305 os << from_ascii(tclass.class_header());
1306 else if (runparams.flavor == OutputParams::XML)
1307 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1308 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1310 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1312 docstring preamble = from_utf8(params().preamble);
1313 if (runparams.flavor != OutputParams::XML ) {
1314 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1315 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1316 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1317 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1320 string const name = runparams.nice
1321 ? changeExtension(absFileName(), ".sgml") : fname;
1322 preamble += features.getIncludedFiles(name);
1323 preamble += features.getLyXSGMLEntities();
1325 if (!preamble.empty()) {
1326 os << "\n [ " << preamble << " ]";
1331 string top = top_element;
1333 if (runparams.flavor == OutputParams::XML)
1334 top += params().language->code();
1336 top += params().language->code().substr(0, 2);
1339 if (!params().options.empty()) {
1341 top += params().options;
1344 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1345 << " file was created by LyX " << lyx_version
1346 << "\n See http://www.lyx.org/ for more information -->\n";
1348 params().documentClass().counters().reset();
1352 sgml::openTag(os, top);
1354 docbookParagraphs(paragraphs(), *this, os, runparams);
1355 sgml::closeTag(os, top_element);
1359 void Buffer::makeLyXHTMLFile(FileName const & fname,
1360 OutputParams const & runparams,
1361 bool const body_only) const
1363 LYXERR(Debug::LATEX, "makeLYXHTMLFile...");
1366 if (!openFileWrite(ofs, fname))
1369 writeLyXHTMLSource(ofs, runparams, body_only);
1373 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1377 void Buffer::writeLyXHTMLSource(odocstream & os,
1378 OutputParams const & runparams,
1379 bool const only_body) const
1381 LaTeXFeatures features(*this, params(), runparams);
1387 os << "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"" <<
1388 " \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n";
1389 // FIXME Language should be set properly.
1390 os << "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\n";
1393 // FIXME Presumably need to set this right
1394 os << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1395 // FIXME Get this during validation? What about other meta-data?
1396 os << "<title>TBA</title>\n";
1398 os << features.getTClassHTMLPreamble();
1402 docstring const styleinfo = features.getTClassHTMLStyles();
1403 if (!styleinfo.empty()) {
1404 os << "<style type='text/css'>\n";
1408 os << "</head>\n<body>\n";
1411 params().documentClass().counters().reset();
1412 xhtmlParagraphs(paragraphs(), *this, os, runparams);
1414 os << "</body>\n</html>\n";
1418 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1419 // Other flags: -wall -v0 -x
1420 int Buffer::runChktex()
1424 // get LaTeX-Filename
1425 FileName const path(temppath());
1426 string const name = addName(path.absFilename(), latexName());
1427 string const org_path = filePath();
1429 PathChanger p(path); // path to LaTeX file
1430 message(_("Running chktex..."));
1432 // Generate the LaTeX file if neccessary
1433 OutputParams runparams(¶ms().encoding());
1434 runparams.flavor = OutputParams::LATEX;
1435 runparams.nice = false;
1436 makeLaTeXFile(FileName(name), org_path, runparams);
1439 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1440 int const res = chktex.run(terr); // run chktex
1443 Alert::error(_("chktex failure"),
1444 _("Could not run chktex successfully."));
1445 } else if (res > 0) {
1446 ErrorList & errlist = d->errorLists["ChkTeX"];
1448 bufferErrors(terr, errlist);
1459 void Buffer::validate(LaTeXFeatures & features) const
1461 params().validate(features);
1465 for_each(paragraphs().begin(), paragraphs().end(),
1466 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1468 if (lyxerr.debugging(Debug::LATEX)) {
1469 features.showStruct();
1474 void Buffer::getLabelList(vector<docstring> & list) const
1476 // If this is a child document, use the parent's list instead.
1477 Buffer const * const pbuf = d->parent();
1479 pbuf->getLabelList(list);
1484 Toc & toc = d->toc_backend.toc("label");
1485 TocIterator toc_it = toc.begin();
1486 TocIterator end = toc.end();
1487 for (; toc_it != end; ++toc_it) {
1488 if (toc_it->depth() == 0)
1489 list.push_back(toc_it->str());
1494 void Buffer::updateBibfilesCache(UpdateScope scope) const
1496 // If this is a child document, use the parent's cache instead.
1497 Buffer const * const pbuf = d->parent();
1498 if (pbuf && scope != UpdateChildOnly) {
1499 pbuf->updateBibfilesCache();
1503 d->bibfilesCache_.clear();
1504 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1505 if (it->lyxCode() == BIBTEX_CODE) {
1506 InsetBibtex const & inset =
1507 static_cast<InsetBibtex const &>(*it);
1508 support::FileNameList const bibfiles = inset.getBibFiles();
1509 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1512 } else if (it->lyxCode() == INCLUDE_CODE) {
1513 InsetInclude & inset =
1514 static_cast<InsetInclude &>(*it);
1515 inset.updateBibfilesCache();
1516 support::FileNameList const & bibfiles =
1517 inset.getBibfilesCache();
1518 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1523 // the bibinfo cache is now invalid
1524 d->bibinfoCacheValid_ = false;
1528 void Buffer::invalidateBibinfoCache()
1530 d->bibinfoCacheValid_ = false;
1534 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1536 // If this is a child document, use the parent's cache instead.
1537 Buffer const * const pbuf = d->parent();
1538 if (pbuf && scope != UpdateChildOnly)
1539 return pbuf->getBibfilesCache();
1541 // We update the cache when first used instead of at loading time.
1542 if (d->bibfilesCache_.empty())
1543 const_cast<Buffer *>(this)->updateBibfilesCache(scope);
1545 return d->bibfilesCache_;
1549 BiblioInfo const & Buffer::masterBibInfo() const
1551 // if this is a child document and the parent is already loaded
1552 // use the parent's list instead [ale990412]
1553 Buffer const * const tmp = masterBuffer();
1556 return tmp->masterBibInfo();
1557 return localBibInfo();
1561 BiblioInfo const & Buffer::localBibInfo() const
1563 if (d->bibinfoCacheValid_) {
1564 support::FileNameList const & bibfilesCache = getBibfilesCache();
1565 // compare the cached timestamps with the actual ones.
1566 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1567 support::FileNameList::const_iterator en = bibfilesCache.end();
1568 for (; ei != en; ++ ei) {
1569 time_t lastw = ei->lastModified();
1570 if (lastw != d->bibfileStatus_[*ei]) {
1571 d->bibinfoCacheValid_ = false;
1572 d->bibfileStatus_[*ei] = lastw;
1578 if (!d->bibinfoCacheValid_) {
1579 d->bibinfo_.clear();
1580 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1581 it->fillWithBibKeys(d->bibinfo_, it);
1582 d->bibinfoCacheValid_ = true;
1588 bool Buffer::isDepClean(string const & name) const
1590 DepClean::const_iterator const it = d->dep_clean.find(name);
1591 if (it == d->dep_clean.end())
1597 void Buffer::markDepClean(string const & name)
1599 d->dep_clean[name] = true;
1603 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1605 switch (cmd.action) {
1606 case LFUN_BUFFER_EXPORT: {
1607 docstring const arg = cmd.argument();
1608 bool enable = arg == "custom" || isExportable(to_utf8(arg));
1610 flag.message(bformat(
1611 _("Don't know how to export to format: %1$s"), arg));
1612 flag.setEnabled(enable);
1616 case LFUN_BRANCH_ACTIVATE:
1617 case LFUN_BRANCH_DEACTIVATE: {
1618 BranchList const & branchList = params().branchlist();
1619 docstring const branchName = cmd.argument();
1620 flag.setEnabled(!branchName.empty()
1621 && branchList.find(branchName));
1625 case LFUN_BRANCH_ADD:
1626 case LFUN_BRANCHES_RENAME:
1627 case LFUN_BUFFER_PRINT:
1628 // if no Buffer is present, then of course we won't be called!
1629 flag.setEnabled(true);
1639 void Buffer::dispatch(string const & command, DispatchResult & result)
1641 return dispatch(lyxaction.lookupFunc(command), result);
1645 // NOTE We can end up here even if we have no GUI, because we are called
1646 // by LyX::exec to handled command-line requests. So we may need to check
1647 // whether we have a GUI or not. The boolean use_gui holds this information.
1648 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1650 // We'll set this back to false if need be.
1651 bool dispatched = true;
1653 switch (func.action) {
1654 case LFUN_BUFFER_EXPORT: {
1655 bool success = doExport(to_utf8(func.argument()), false);
1656 dr.setError(success);
1658 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
1663 case LFUN_BRANCH_ADD: {
1664 BranchList & branchList = params().branchlist();
1665 docstring const branchName = func.argument();
1666 if (branchName.empty()) {
1670 Branch * branch = branchList.find(branchName);
1672 LYXERR0("Branch " << branchName << " does already exist.");
1674 docstring const msg =
1675 bformat(_("Branch \"%1$s\" does already exist."), branchName);
1678 branchList.add(branchName);
1680 dr.update(Update::Force);
1685 case LFUN_BRANCH_ACTIVATE:
1686 case LFUN_BRANCH_DEACTIVATE: {
1687 BranchList & branchList = params().branchlist();
1688 docstring const branchName = func.argument();
1689 // the case without a branch name is handled elsewhere
1690 if (branchName.empty()) {
1694 Branch * branch = branchList.find(branchName);
1696 LYXERR0("Branch " << branchName << " does not exist.");
1698 docstring const msg =
1699 bformat(_("Branch \"%1$s\" does not exist."), branchName);
1702 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1704 dr.update(Update::Force);
1709 case LFUN_BRANCHES_RENAME: {
1710 if (func.argument().empty())
1713 docstring const oldname = from_utf8(func.getArg(0));
1714 docstring const newname = from_utf8(func.getArg(1));
1715 InsetIterator it = inset_iterator_begin(inset());
1716 InsetIterator const end = inset_iterator_end(inset());
1717 bool success = false;
1718 for (; it != end; ++it) {
1719 if (it->lyxCode() == BRANCH_CODE) {
1720 InsetBranch & ins = static_cast<InsetBranch &>(*it);
1721 if (ins.branch() == oldname) {
1722 undo().recordUndo(it);
1723 ins.rename(newname);
1728 if (it->lyxCode() == INCLUDE_CODE) {
1729 // get buffer of external file
1730 InsetInclude const & ins =
1731 static_cast<InsetInclude const &>(*it);
1732 Buffer * child = ins.getChildBuffer();
1735 child->dispatch(func, dr);
1740 dr.update(Update::Force);
1744 case LFUN_BUFFER_PRINT: {
1745 // we'll assume there's a problem until we succeed
1747 string target = func.getArg(0);
1748 string target_name = func.getArg(1);
1749 string command = func.getArg(2);
1752 || target_name.empty()
1753 || command.empty()) {
1754 LYXERR0("Unable to parse " << func.argument());
1755 docstring const msg =
1756 bformat(_("Unable to parse \"%1$s\""), func.argument());
1760 if (target != "printer" && target != "file") {
1761 LYXERR0("Unrecognized target \"" << target << '"');
1762 docstring const msg =
1763 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
1768 if (!doExport("dvi", true)) {
1769 showPrintError(absFileName());
1770 dr.setMessage(_("Error exporting to DVI."));
1774 // Push directory path.
1775 string const path = temppath();
1776 // Prevent the compiler from optimizing away p
1780 // there are three cases here:
1781 // 1. we print to a file
1782 // 2. we print directly to a printer
1783 // 3. we print using a spool command (print to file first)
1786 string const dviname = changeExtension(latexName(true), "dvi");
1788 if (target == "printer") {
1789 if (!lyxrc.print_spool_command.empty()) {
1790 // case 3: print using a spool
1791 string const psname = changeExtension(dviname,".ps");
1792 command += ' ' + lyxrc.print_to_file
1795 + quoteName(dviname);
1797 string command2 = lyxrc.print_spool_command + ' ';
1798 if (target_name != "default") {
1799 command2 += lyxrc.print_spool_printerprefix
1803 command2 += quoteName(psname);
1805 // If successful, then spool command
1806 res = one.startscript(Systemcall::Wait, command);
1809 // If there's no GUI, we have to wait on this command. Otherwise,
1810 // LyX deletes the temporary directory, and with it the spooled
1811 // file, before it can be printed!!
1812 Systemcall::Starttype stype = use_gui ?
1813 Systemcall::DontWait : Systemcall::Wait;
1814 res = one.startscript(stype, command2);
1817 // case 2: print directly to a printer
1818 if (target_name != "default")
1819 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
1821 Systemcall::Starttype stype = use_gui ?
1822 Systemcall::DontWait : Systemcall::Wait;
1823 res = one.startscript(stype, command + quoteName(dviname));
1827 // case 1: print to a file
1828 FileName const filename(makeAbsPath(target_name, filePath()));
1829 FileName const dvifile(makeAbsPath(dviname, path));
1830 if (filename.exists()) {
1831 docstring text = bformat(
1832 _("The file %1$s already exists.\n\n"
1833 "Do you want to overwrite that file?"),
1834 makeDisplayPath(filename.absFilename()));
1835 if (Alert::prompt(_("Overwrite file?"),
1836 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
1839 command += ' ' + lyxrc.print_to_file
1840 + quoteName(filename.toFilesystemEncoding())
1842 + quoteName(dvifile.toFilesystemEncoding());
1844 Systemcall::Starttype stype = use_gui ?
1845 Systemcall::DontWait : Systemcall::Wait;
1846 res = one.startscript(stype, command);
1852 dr.setMessage(_("Error running external commands."));
1853 showPrintError(absFileName());
1862 dr.dispatched(dispatched);
1866 void Buffer::changeLanguage(Language const * from, Language const * to)
1868 LASSERT(from, /**/);
1871 for_each(par_iterator_begin(),
1873 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1877 bool Buffer::isMultiLingual() const
1879 ParConstIterator end = par_iterator_end();
1880 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1881 if (it->isMultiLingual(params()))
1888 DocIterator Buffer::getParFromID(int const id) const
1890 Buffer * buf = const_cast<Buffer *>(this);
1892 // John says this is called with id == -1 from undo
1893 lyxerr << "getParFromID(), id: " << id << endl;
1894 return doc_iterator_end(buf);
1897 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
1898 if (it.paragraph().id() == id)
1901 return doc_iterator_end(buf);
1905 bool Buffer::hasParWithID(int const id) const
1907 return !getParFromID(id).atEnd();
1911 ParIterator Buffer::par_iterator_begin()
1913 return ParIterator(doc_iterator_begin(this));
1917 ParIterator Buffer::par_iterator_end()
1919 return ParIterator(doc_iterator_end(this));
1923 ParConstIterator Buffer::par_iterator_begin() const
1925 return ParConstIterator(doc_iterator_begin(this));
1929 ParConstIterator Buffer::par_iterator_end() const
1931 return ParConstIterator(doc_iterator_end(this));
1935 Language const * Buffer::language() const
1937 return params().language;
1941 docstring const Buffer::B_(string const & l10n) const
1943 return params().B_(l10n);
1947 bool Buffer::isClean() const
1949 return d->lyx_clean;
1953 bool Buffer::isBakClean() const
1955 return d->bak_clean;
1959 bool Buffer::isExternallyModified(CheckMethod method) const
1961 LASSERT(d->filename.exists(), /**/);
1962 // if method == timestamp, check timestamp before checksum
1963 return (method == checksum_method
1964 || d->timestamp_ != d->filename.lastModified())
1965 && d->checksum_ != d->filename.checksum();
1969 void Buffer::saveCheckSum(FileName const & file) const
1971 if (file.exists()) {
1972 d->timestamp_ = file.lastModified();
1973 d->checksum_ = file.checksum();
1975 // in the case of save to a new file.
1982 void Buffer::markClean() const
1984 if (!d->lyx_clean) {
1985 d->lyx_clean = true;
1988 // if the .lyx file has been saved, we don't need an
1990 d->bak_clean = true;
1994 void Buffer::markBakClean() const
1996 d->bak_clean = true;
2000 void Buffer::setUnnamed(bool flag)
2006 bool Buffer::isUnnamed() const
2012 // FIXME: this function should be moved to buffer_pimpl.C
2013 void Buffer::markDirty()
2016 d->lyx_clean = false;
2019 d->bak_clean = false;
2021 DepClean::iterator it = d->dep_clean.begin();
2022 DepClean::const_iterator const end = d->dep_clean.end();
2024 for (; it != end; ++it)
2029 FileName Buffer::fileName() const
2035 string Buffer::absFileName() const
2037 return d->filename.absFilename();
2041 string Buffer::filePath() const
2043 return d->filename.onlyPath().absFilename() + "/";
2047 bool Buffer::isReadonly() const
2049 return d->read_only;
2053 void Buffer::setParent(Buffer const * buffer)
2055 // Avoids recursive include.
2056 d->setParent(buffer == this ? 0 : buffer);
2061 Buffer const * Buffer::parent() const
2067 void Buffer::collectRelatives(BufferSet & bufs) const
2071 parent()->collectRelatives(bufs);
2073 // loop over children
2074 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2075 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2076 for (; it != end; ++it)
2077 bufs.insert(const_cast<Buffer *>(it->first));
2081 std::vector<Buffer const *> Buffer::allRelatives() const
2084 collectRelatives(bufs);
2085 BufferSet::iterator it = bufs.begin();
2086 std::vector<Buffer const *> ret;
2087 for (; it != bufs.end(); ++it)
2093 Buffer const * Buffer::masterBuffer() const
2095 Buffer const * const pbuf = d->parent();
2099 return pbuf->masterBuffer();
2103 bool Buffer::isChild(Buffer * child) const
2105 return d->children_positions.find(child) != d->children_positions.end();
2109 DocIterator Buffer::firstChildPosition(Buffer const * child)
2111 Impl::BufferPositionMap::iterator it;
2112 it = d->children_positions.find(child);
2113 if (it == d->children_positions.end())
2114 return DocIterator(this);
2119 std::vector<Buffer *> Buffer::getChildren() const
2121 std::vector<Buffer *> clist;
2122 // loop over children
2123 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2124 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2125 for (; it != end; ++it) {
2126 Buffer * child = const_cast<Buffer *>(it->first);
2127 clist.push_back(child);
2128 // there might be grandchildren
2129 std::vector<Buffer *> glist = child->getChildren();
2130 for (vector<Buffer *>::const_iterator git = glist.begin();
2131 git != glist.end(); ++git)
2132 clist.push_back(*git);
2138 template<typename M>
2139 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
2144 typename M::iterator it = m.lower_bound(x);
2145 if (it == m.begin())
2153 MacroData const * Buffer::getBufferMacro(docstring const & name,
2154 DocIterator const & pos) const
2156 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2158 // if paragraphs have no macro context set, pos will be empty
2162 // we haven't found anything yet
2163 DocIterator bestPos = par_iterator_begin();
2164 MacroData const * bestData = 0;
2166 // find macro definitions for name
2167 Impl::NamePositionScopeMacroMap::iterator nameIt
2168 = d->macros.find(name);
2169 if (nameIt != d->macros.end()) {
2170 // find last definition in front of pos or at pos itself
2171 Impl::PositionScopeMacroMap::const_iterator it
2172 = greatest_below(nameIt->second, pos);
2173 if (it != nameIt->second.end()) {
2175 // scope ends behind pos?
2176 if (pos < it->second.first) {
2177 // Looks good, remember this. If there
2178 // is no external macro behind this,
2179 // we found the right one already.
2180 bestPos = it->first;
2181 bestData = &it->second.second;
2185 // try previous macro if there is one
2186 if (it == nameIt->second.begin())
2193 // find macros in included files
2194 Impl::PositionScopeBufferMap::const_iterator it
2195 = greatest_below(d->position_to_children, pos);
2196 if (it == d->position_to_children.end())
2197 // no children before
2201 // do we know something better (i.e. later) already?
2202 if (it->first < bestPos )
2205 // scope ends behind pos?
2206 if (pos < it->second.first) {
2207 // look for macro in external file
2208 d->macro_lock = true;
2209 MacroData const * data
2210 = it->second.second->getMacro(name, false);
2211 d->macro_lock = false;
2213 bestPos = it->first;
2219 // try previous file if there is one
2220 if (it == d->position_to_children.begin())
2225 // return the best macro we have found
2230 MacroData const * Buffer::getMacro(docstring const & name,
2231 DocIterator const & pos, bool global) const
2236 // query buffer macros
2237 MacroData const * data = getBufferMacro(name, pos);
2241 // If there is a master buffer, query that
2242 Buffer const * const pbuf = d->parent();
2244 d->macro_lock = true;
2245 MacroData const * macro = pbuf->getMacro(
2246 name, *this, false);
2247 d->macro_lock = false;
2253 data = MacroTable::globalMacros().get(name);
2262 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2264 // set scope end behind the last paragraph
2265 DocIterator scope = par_iterator_begin();
2266 scope.pit() = scope.lastpit() + 1;
2268 return getMacro(name, scope, global);
2272 MacroData const * Buffer::getMacro(docstring const & name,
2273 Buffer const & child, bool global) const
2275 // look where the child buffer is included first
2276 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2277 if (it == d->children_positions.end())
2280 // check for macros at the inclusion position
2281 return getMacro(name, it->second, global);
2285 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
2287 pit_type lastpit = it.lastpit();
2289 // look for macros in each paragraph
2290 while (it.pit() <= lastpit) {
2291 Paragraph & par = it.paragraph();
2293 // iterate over the insets of the current paragraph
2294 InsetList const & insets = par.insetList();
2295 InsetList::const_iterator iit = insets.begin();
2296 InsetList::const_iterator end = insets.end();
2297 for (; iit != end; ++iit) {
2298 it.pos() = iit->pos;
2300 // is it a nested text inset?
2301 if (iit->inset->asInsetText()) {
2302 // Inset needs its own scope?
2303 InsetText const * itext = iit->inset->asInsetText();
2304 bool newScope = itext->isMacroScope();
2306 // scope which ends just behind the inset
2307 DocIterator insetScope = it;
2310 // collect macros in inset
2311 it.push_back(CursorSlice(*iit->inset));
2312 updateMacros(it, newScope ? insetScope : scope);
2317 // is it an external file?
2318 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2319 // get buffer of external file
2320 InsetInclude const & inset =
2321 static_cast<InsetInclude const &>(*iit->inset);
2322 d->macro_lock = true;
2323 Buffer * child = inset.getChildBuffer();
2324 d->macro_lock = false;
2328 // register its position, but only when it is
2329 // included first in the buffer
2330 if (d->children_positions.find(child) ==
2331 d->children_positions.end())
2332 d->children_positions[child] = it;
2334 // register child with its scope
2335 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
2339 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2343 MathMacroTemplate & macroTemplate =
2344 static_cast<MathMacroTemplate &>(*iit->inset);
2345 MacroContext mc(*this, it);
2346 macroTemplate.updateToContext(mc);
2349 bool valid = macroTemplate.validMacro();
2350 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2351 // then the BufferView's cursor will be invalid in
2352 // some cases which leads to crashes.
2357 d->macros[macroTemplate.name()][it] =
2358 Impl::ScopeMacro(scope, MacroData(*this, it));
2368 void Buffer::updateMacros() const
2373 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2375 // start with empty table
2377 d->children_positions.clear();
2378 d->position_to_children.clear();
2380 // Iterate over buffer, starting with first paragraph
2381 // The scope must be bigger than any lookup DocIterator
2382 // later. For the global lookup, lastpit+1 is used, hence
2383 // we use lastpit+2 here.
2384 DocIterator it = par_iterator_begin();
2385 DocIterator outerScope = it;
2386 outerScope.pit() = outerScope.lastpit() + 2;
2387 updateMacros(it, outerScope);
2391 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2393 InsetIterator it = inset_iterator_begin(inset());
2394 InsetIterator const end = inset_iterator_end(inset());
2395 for (; it != end; ++it) {
2396 if (it->lyxCode() == BRANCH_CODE) {
2397 InsetBranch & br = static_cast<InsetBranch &>(*it);
2398 docstring const name = br.branch();
2399 if (!from_master && !params().branchlist().find(name))
2400 result.push_back(name);
2401 else if (from_master && !masterBuffer()->params().branchlist().find(name))
2402 result.push_back(name);
2405 if (it->lyxCode() == INCLUDE_CODE) {
2406 // get buffer of external file
2407 InsetInclude const & ins =
2408 static_cast<InsetInclude const &>(*it);
2409 Buffer * child = ins.getChildBuffer();
2412 child->getUsedBranches(result, true);
2415 // remove duplicates
2420 void Buffer::updateMacroInstances() const
2422 LYXERR(Debug::MACROS, "updateMacroInstances for "
2423 << d->filename.onlyFileName());
2424 DocIterator it = doc_iterator_begin(this);
2425 DocIterator end = doc_iterator_end(this);
2426 for (; it != end; it.forwardPos()) {
2427 // look for MathData cells in InsetMathNest insets
2428 Inset * inset = it.nextInset();
2432 InsetMath * minset = inset->asInsetMath();
2436 // update macro in all cells of the InsetMathNest
2437 DocIterator::idx_type n = minset->nargs();
2438 MacroContext mc = MacroContext(*this, it);
2439 for (DocIterator::idx_type i = 0; i < n; ++i) {
2440 MathData & data = minset->cell(i);
2441 data.updateMacros(0, mc);
2447 void Buffer::listMacroNames(MacroNameSet & macros) const
2452 d->macro_lock = true;
2454 // loop over macro names
2455 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2456 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2457 for (; nameIt != nameEnd; ++nameIt)
2458 macros.insert(nameIt->first);
2460 // loop over children
2461 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2462 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2463 for (; it != end; ++it)
2464 it->first->listMacroNames(macros);
2467 Buffer const * const pbuf = d->parent();
2469 pbuf->listMacroNames(macros);
2471 d->macro_lock = false;
2475 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2477 Buffer const * const pbuf = d->parent();
2482 pbuf->listMacroNames(names);
2485 MacroNameSet::iterator it = names.begin();
2486 MacroNameSet::iterator end = names.end();
2487 for (; it != end; ++it) {
2489 MacroData const * data =
2490 pbuf->getMacro(*it, *this, false);
2492 macros.insert(data);
2494 // we cannot access the original MathMacroTemplate anymore
2495 // here to calls validate method. So we do its work here manually.
2496 // FIXME: somehow make the template accessible here.
2497 if (data->optionals() > 0)
2498 features.require("xargs");
2504 Buffer::References & Buffer::references(docstring const & label)
2507 return const_cast<Buffer *>(masterBuffer())->references(label);
2509 RefCache::iterator it = d->ref_cache_.find(label);
2510 if (it != d->ref_cache_.end())
2511 return it->second.second;
2513 static InsetLabel const * dummy_il = 0;
2514 static References const dummy_refs;
2515 it = d->ref_cache_.insert(
2516 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2517 return it->second.second;
2521 Buffer::References const & Buffer::references(docstring const & label) const
2523 return const_cast<Buffer *>(this)->references(label);
2527 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2529 masterBuffer()->d->ref_cache_[label].first = il;
2533 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2535 return masterBuffer()->d->ref_cache_[label].first;
2539 void Buffer::clearReferenceCache() const
2542 d->ref_cache_.clear();
2546 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2549 //FIXME: This does not work for child documents yet.
2550 LASSERT(code == CITE_CODE, /**/);
2551 // Check if the label 'from' appears more than once
2552 vector<docstring> labels;
2554 BiblioInfo const & keys = masterBibInfo();
2555 BiblioInfo::const_iterator bit = keys.begin();
2556 BiblioInfo::const_iterator bend = keys.end();
2558 for (; bit != bend; ++bit)
2560 labels.push_back(bit->first);
2563 if (count(labels.begin(), labels.end(), from) > 1)
2566 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2567 if (it->lyxCode() == code) {
2568 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2569 docstring const oldValue = inset.getParam(paramName);
2570 if (oldValue == from)
2571 inset.setParam(paramName, to);
2577 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2578 pit_type par_end, bool full_source) const
2580 OutputParams runparams(¶ms().encoding());
2581 runparams.nice = true;
2582 runparams.flavor = params().useXetex ?
2583 OutputParams::XETEX : OutputParams::LATEX;
2584 runparams.linelen = lyxrc.plaintext_linelen;
2585 // No side effect of file copying and image conversion
2586 runparams.dryrun = true;
2589 os << "% " << _("Preview source code") << "\n\n";
2591 d->texrow.newline();
2592 d->texrow.newline();
2594 writeDocBookSource(os, absFileName(), runparams, false);
2596 // latex or literate
2597 writeLaTeXSource(os, string(), runparams, true, true);
2599 runparams.par_begin = par_begin;
2600 runparams.par_end = par_end;
2601 if (par_begin + 1 == par_end) {
2603 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2607 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2608 convert<docstring>(par_begin),
2609 convert<docstring>(par_end - 1))
2616 // output paragraphs
2618 docbookParagraphs(paragraphs(), *this, os, runparams);
2620 // latex or literate
2621 latexParagraphs(*this, text(), os, texrow, runparams);
2626 ErrorList & Buffer::errorList(string const & type) const
2628 static ErrorList emptyErrorList;
2629 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2630 if (I == d->errorLists.end())
2631 return emptyErrorList;
2637 void Buffer::updateTocItem(std::string const & type,
2638 DocIterator const & dit) const
2641 gui_->updateTocItem(type, dit);
2645 void Buffer::structureChanged() const
2648 gui_->structureChanged();
2652 void Buffer::errors(string const & err, bool from_master) const
2655 gui_->errors(err, from_master);
2659 void Buffer::message(docstring const & msg) const
2666 void Buffer::setBusy(bool on) const
2673 void Buffer::setReadOnly(bool on) const
2676 d->wa_->setReadOnly(on);
2680 void Buffer::updateTitles() const
2683 d->wa_->updateTitles();
2687 void Buffer::resetAutosaveTimers() const
2690 gui_->resetAutosaveTimers();
2694 bool Buffer::hasGuiDelegate() const
2700 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2709 class AutoSaveBuffer : public ForkedProcess {
2712 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2713 : buffer_(buffer), fname_(fname) {}
2715 virtual boost::shared_ptr<ForkedProcess> clone() const
2717 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2722 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2723 from_utf8(fname_.absFilename())));
2724 return run(DontWait);
2728 virtual int generateChild();
2730 Buffer const & buffer_;
2735 int AutoSaveBuffer::generateChild()
2737 // tmp_ret will be located (usually) in /tmp
2738 // will that be a problem?
2739 // Note that this calls ForkedCalls::fork(), so it's
2740 // ok cross-platform.
2741 pid_t const pid = fork();
2742 // If you want to debug the autosave
2743 // you should set pid to -1, and comment out the fork.
2744 if (pid != 0 && pid != -1)
2747 // pid = -1 signifies that lyx was unable
2748 // to fork. But we will do the save
2750 bool failed = false;
2751 FileName const tmp_ret = FileName::tempName("lyxauto");
2752 if (!tmp_ret.empty()) {
2753 buffer_.writeFile(tmp_ret);
2754 // assume successful write of tmp_ret
2755 if (!tmp_ret.moveTo(fname_))
2761 // failed to write/rename tmp_ret so try writing direct
2762 if (!buffer_.writeFile(fname_)) {
2763 // It is dangerous to do this in the child,
2764 // but safe in the parent, so...
2765 if (pid == -1) // emit message signal.
2766 buffer_.message(_("Autosave failed!"));
2770 if (pid == 0) // we are the child so...
2779 FileName Buffer::getAutosaveFilename() const
2781 // if the document is unnamed try to save in the backup dir, else
2782 // in the default document path, and as a last try in the filePath,
2783 // which will most often be the temporary directory
2786 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
2787 : lyxrc.backupdir_path;
2788 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
2791 string const fname = "#" + d->filename.onlyFileName() + "#";
2792 return makeAbsPath(fname, fpath);
2796 void Buffer::removeAutosaveFile() const
2798 FileName const f = getAutosaveFilename();
2804 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
2806 FileName const newauto = getAutosaveFilename();
2807 if (!(oldauto == newauto || oldauto.moveTo(newauto)))
2808 LYXERR0("Unable to remove autosave file `" << oldauto << "'!");
2812 // Perfect target for a thread...
2813 void Buffer::autoSave() const
2815 if (isBakClean() || isReadonly()) {
2816 // We don't save now, but we'll try again later
2817 resetAutosaveTimers();
2821 // emit message signal.
2822 message(_("Autosaving current document..."));
2823 AutoSaveBuffer autosave(*this, getAutosaveFilename());
2827 resetAutosaveTimers();
2831 string Buffer::bufferFormat() const
2833 string format = params().documentClass().outputFormat();
2834 if (format == "latex") {
2835 if (params().useXetex)
2837 if (params().encoding().package() == Encoding::japanese)
2844 string Buffer::getDefaultOutputFormat() const
2846 if (!params().defaultOutputFormat.empty()
2847 && params().defaultOutputFormat != "default")
2848 return params().defaultOutputFormat;
2849 typedef vector<Format const *> Formats;
2850 Formats formats = exportableFormats(true);
2853 || params().useXetex
2854 || params().encoding().package() == Encoding::japanese) {
2855 if (formats.empty())
2857 // return the first we find
2858 return formats.front()->name();
2860 return lyxrc.default_view_format;
2865 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2866 string & result_file) const
2868 string backend_format;
2869 OutputParams runparams(¶ms().encoding());
2870 runparams.flavor = OutputParams::LATEX;
2871 runparams.linelen = lyxrc.plaintext_linelen;
2872 vector<string> backs = backends();
2873 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2874 // Get shortest path to format
2875 Graph::EdgePath path;
2876 for (vector<string>::const_iterator it = backs.begin();
2877 it != backs.end(); ++it) {
2878 Graph::EdgePath p = theConverters().getPath(*it, format);
2879 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2880 backend_format = *it;
2885 runparams.flavor = theConverters().getFlavor(path);
2887 Alert::error(_("Couldn't export file"),
2888 bformat(_("No information for exporting the format %1$s."),
2889 formats.prettyName(format)));
2893 backend_format = format;
2894 // FIXME: Don't hardcode format names here, but use a flag
2895 if (backend_format == "pdflatex")
2896 runparams.flavor = OutputParams::PDFLATEX;
2899 string filename = latexName(false);
2900 filename = addName(temppath(), filename);
2901 filename = changeExtension(filename,
2902 formats.extension(backend_format));
2905 updateMacroInstances();
2907 // Plain text backend
2908 if (backend_format == "text")
2909 writePlaintextFile(*this, FileName(filename), runparams);
2911 else if (backend_format == "xhtml")
2912 makeLyXHTMLFile(FileName(filename), runparams);
2913 else if (backend_format == "lyx")
2914 writeFile(FileName(filename));
2916 else if (isDocBook()) {
2917 runparams.nice = !put_in_tempdir;
2918 makeDocBookFile(FileName(filename), runparams);
2921 else if (backend_format == format) {
2922 runparams.nice = true;
2923 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2925 } else if (!lyxrc.tex_allows_spaces
2926 && contains(filePath(), ' ')) {
2927 Alert::error(_("File name error"),
2928 _("The directory path to the document cannot contain spaces."));
2931 runparams.nice = false;
2932 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2936 string const error_type = (format == "program")
2937 ? "Build" : bufferFormat();
2938 ErrorList & error_list = d->errorLists[error_type];
2939 string const ext = formats.extension(format);
2940 FileName const tmp_result_file(changeExtension(filename, ext));
2941 bool const success = theConverters().convert(this, FileName(filename),
2942 tmp_result_file, FileName(absFileName()), backend_format, format,
2944 // Emit the signal to show the error list.
2945 if (format != backend_format) {
2947 // also to the children, in case of master-buffer-view
2948 std::vector<Buffer *> clist = getChildren();
2949 for (vector<Buffer *>::const_iterator cit = clist.begin();
2950 cit != clist.end(); ++cit)
2951 (*cit)->errors(error_type, true);
2956 if (put_in_tempdir) {
2957 result_file = tmp_result_file.absFilename();
2961 result_file = changeExtension(absFileName(), ext);
2962 // We need to copy referenced files (e. g. included graphics
2963 // if format == "dvi") to the result dir.
2964 vector<ExportedFile> const files =
2965 runparams.exportdata->externalFiles(format);
2966 string const dest = onlyPath(result_file);
2967 CopyStatus status = SUCCESS;
2968 for (vector<ExportedFile>::const_iterator it = files.begin();
2969 it != files.end() && status != CANCEL; ++it) {
2970 string const fmt = formats.getFormatFromFile(it->sourceName);
2971 status = copyFile(fmt, it->sourceName,
2972 makeAbsPath(it->exportName, dest),
2973 it->exportName, status == FORCE);
2975 if (status == CANCEL) {
2976 message(_("Document export cancelled."));
2977 } else if (tmp_result_file.exists()) {
2978 // Finally copy the main file
2979 status = copyFile(format, tmp_result_file,
2980 FileName(result_file), result_file,
2982 message(bformat(_("Document exported as %1$s "
2984 formats.prettyName(format),
2985 makeDisplayPath(result_file)));
2987 // This must be a dummy converter like fax (bug 1888)
2988 message(bformat(_("Document exported as %1$s"),
2989 formats.prettyName(format)));
2996 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2999 return doExport(format, put_in_tempdir, result_file);
3003 bool Buffer::preview(string const & format) const
3006 if (!doExport(format, true, result_file))
3008 return formats.view(*this, FileName(result_file), format);
3012 bool Buffer::isExportable(string const & format) const
3014 vector<string> backs = backends();
3015 for (vector<string>::const_iterator it = backs.begin();
3016 it != backs.end(); ++it)
3017 if (theConverters().isReachable(*it, format))
3023 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
3025 vector<string> backs = backends();
3026 vector<Format const *> result =
3027 theConverters().getReachable(backs[0], only_viewable, true);
3028 for (vector<string>::const_iterator it = backs.begin() + 1;
3029 it != backs.end(); ++it) {
3030 vector<Format const *> r =
3031 theConverters().getReachable(*it, only_viewable, false);
3032 result.insert(result.end(), r.begin(), r.end());
3038 vector<string> Buffer::backends() const
3041 if (params().baseClass()->isTeXClassAvailable()) {
3042 v.push_back(bufferFormat());
3043 // FIXME: Don't hardcode format names here, but use a flag
3044 if (v.back() == "latex")
3045 v.push_back("pdflatex");
3047 v.push_back("text");
3048 v.push_back("xhtml");
3054 bool Buffer::readFileHelper(FileName const & s)
3056 // File information about normal file
3058 docstring const file = makeDisplayPath(s.absFilename(), 50);
3059 docstring text = bformat(_("The specified document\n%1$s"
3060 "\ncould not be read."), file);
3061 Alert::error(_("Could not read document"), text);
3065 // Check if emergency save file exists and is newer.
3066 FileName const e(s.absFilename() + ".emergency");
3068 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
3069 docstring const file = makeDisplayPath(s.absFilename(), 20);
3070 docstring const text =
3071 bformat(_("An emergency save of the document "
3073 "Recover emergency save?"), file);
3074 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
3075 _("&Recover"), _("&Load Original"),
3079 // the file is not saved if we load the emergency file.
3089 // Now check if autosave file is newer.
3090 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
3092 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
3093 docstring const file = makeDisplayPath(s.absFilename(), 20);
3094 docstring const text =
3095 bformat(_("The backup of the document "
3096 "%1$s is newer.\n\nLoad the "
3097 "backup instead?"), file);
3098 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
3099 _("&Load backup"), _("Load &original"),
3103 // the file is not saved if we load the autosave file.
3107 // Here we delete the autosave
3118 bool Buffer::loadLyXFile(FileName const & s)
3120 if (s.isReadableFile()) {
3121 if (readFileHelper(s)) {
3122 lyxvc().file_found_hook(s);
3123 if (!s.isWritable())
3128 docstring const file = makeDisplayPath(s.absFilename(), 20);
3129 // Here we probably should run
3130 if (LyXVC::file_not_found_hook(s)) {
3131 docstring const text =
3132 bformat(_("Do you want to retrieve the document"
3133 " %1$s from version control?"), file);
3134 int const ret = Alert::prompt(_("Retrieve from version control?"),
3135 text, 0, 1, _("&Retrieve"), _("&Cancel"));
3138 // How can we know _how_ to do the checkout?
3139 // With the current VC support it has to be,
3140 // a RCS file since CVS do not have special ,v files.
3142 return loadLyXFile(s);
3150 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3152 TeXErrors::Errors::const_iterator cit = terr.begin();
3153 TeXErrors::Errors::const_iterator end = terr.end();
3155 for (; cit != end; ++cit) {
3158 int errorRow = cit->error_in_line;
3159 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3165 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3166 } while (found && id_start == id_end && pos_start == pos_end);
3168 errorList.push_back(ErrorItem(cit->error_desc,
3169 cit->error_text, id_start, pos_start, pos_end));
3174 void Buffer::setBuffersForInsets() const
3176 inset().setBuffer(const_cast<Buffer &>(*this));
3180 void Buffer::updateLabels(UpdateScope scope) const
3182 // Use the master text class also for child documents
3183 Buffer const * const master = masterBuffer();
3184 DocumentClass const & textclass = master->params().documentClass();
3186 // keep the buffers to be children in this set. If the call from the
3187 // master comes back we can see which of them were actually seen (i.e.
3188 // via an InsetInclude). The remaining ones in the set need still be updated.
3189 static std::set<Buffer const *> bufToUpdate;
3190 if (scope == UpdateMaster) {
3191 // If this is a child document start with the master
3192 if (master != this) {
3193 bufToUpdate.insert(this);
3194 master->updateLabels();
3195 // Do this here in case the master has no gui associated with it. Then,
3196 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3200 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3201 if (bufToUpdate.find(this) == bufToUpdate.end())
3205 // start over the counters in the master
3206 textclass.counters().reset();
3209 // update will be done below for this buffer
3210 bufToUpdate.erase(this);
3212 // update all caches
3213 clearReferenceCache();
3216 Buffer & cbuf = const_cast<Buffer &>(*this);
3218 LASSERT(!text().paragraphs().empty(), /**/);
3221 ParIterator parit = cbuf.par_iterator_begin();
3222 updateLabels(parit);
3225 // TocBackend update will be done later.
3228 cbuf.tocBackend().update();
3229 if (scope == UpdateMaster)
3230 cbuf.structureChanged();
3234 static depth_type getDepth(DocIterator const & it)
3236 depth_type depth = 0;
3237 for (size_t i = 0 ; i < it.depth() ; ++i)
3238 if (!it[i].inset().inMathed())
3239 depth += it[i].paragraph().getDepth() + 1;
3240 // remove 1 since the outer inset does not count
3244 static depth_type getItemDepth(ParIterator const & it)
3246 Paragraph const & par = *it;
3247 LabelType const labeltype = par.layout().labeltype;
3249 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3252 // this will hold the lowest depth encountered up to now.
3253 depth_type min_depth = getDepth(it);
3254 ParIterator prev_it = it;
3257 --prev_it.top().pit();
3259 // start of nested inset: go to outer par
3261 if (prev_it.empty()) {
3262 // start of document: nothing to do
3267 // We search for the first paragraph with same label
3268 // that is not more deeply nested.
3269 Paragraph & prev_par = *prev_it;
3270 depth_type const prev_depth = getDepth(prev_it);
3271 if (labeltype == prev_par.layout().labeltype) {
3272 if (prev_depth < min_depth)
3273 return prev_par.itemdepth + 1;
3274 if (prev_depth == min_depth)
3275 return prev_par.itemdepth;
3277 min_depth = min(min_depth, prev_depth);
3278 // small optimization: if we are at depth 0, we won't
3279 // find anything else
3280 if (prev_depth == 0)
3286 static bool needEnumCounterReset(ParIterator const & it)
3288 Paragraph const & par = *it;
3289 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3290 depth_type const cur_depth = par.getDepth();
3291 ParIterator prev_it = it;
3292 while (prev_it.pit()) {
3293 --prev_it.top().pit();
3294 Paragraph const & prev_par = *prev_it;
3295 if (prev_par.getDepth() <= cur_depth)
3296 return prev_par.layout().labeltype != LABEL_ENUMERATE;
3298 // start of nested inset: reset
3303 // set the label of a paragraph. This includes the counters.
3304 static void setLabel(Buffer const & buf, ParIterator & it)
3306 BufferParams const & bp = buf.masterBuffer()->params();
3307 DocumentClass const & textclass = bp.documentClass();
3308 Paragraph & par = it.paragraph();
3309 Layout const & layout = par.layout();
3310 Counters & counters = textclass.counters();
3312 if (par.params().startOfAppendix()) {
3313 // FIXME: only the counter corresponding to toplevel
3314 // sectionning should be reset
3316 counters.appendix(true);
3318 par.params().appendix(counters.appendix());
3320 // Compute the item depth of the paragraph
3321 par.itemdepth = getItemDepth(it);
3323 if (layout.margintype == MARGIN_MANUAL
3324 || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3325 if (par.params().labelWidthString().empty())
3326 par.params().labelWidthString(par.translateIfPossible(layout.labelstring(), bp));
3328 par.params().labelWidthString(docstring());
3331 switch(layout.labeltype) {
3333 if (layout.toclevel <= bp.secnumdepth
3334 && (layout.latextype != LATEX_ENVIRONMENT
3335 || isFirstInSequence(it.pit(), it.plist()))) {
3336 counters.step(layout.counter);
3337 par.params().labelString(
3338 par.expandLabel(layout, bp));
3340 par.params().labelString(docstring());
3343 case LABEL_ITEMIZE: {
3344 // At some point of time we should do something more
3345 // clever here, like:
3346 // par.params().labelString(
3347 // bp.user_defined_bullet(par.itemdepth).getText());
3348 // for now, use a simple hardcoded label
3349 docstring itemlabel;
3350 switch (par.itemdepth) {
3352 itemlabel = char_type(0x2022);
3355 itemlabel = char_type(0x2013);
3358 itemlabel = char_type(0x2217);
3361 itemlabel = char_type(0x2219); // or 0x00b7
3364 par.params().labelString(itemlabel);
3368 case LABEL_ENUMERATE: {
3369 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
3371 switch (par.itemdepth) {
3380 enumcounter += "iv";
3383 // not a valid enumdepth...
3387 // Maybe we have to reset the enumeration counter.
3388 if (needEnumCounterReset(it))
3389 counters.reset(enumcounter);
3390 counters.step(enumcounter);
3392 par.params().labelString(counters.theCounter(enumcounter));
3397 case LABEL_SENSITIVE: {
3398 string const & type = counters.current_float();
3399 docstring full_label;
3401 full_label = buf.B_("Senseless!!! ");
3403 docstring name = buf.B_(textclass.floats().getType(type).name());
3404 if (counters.hasCounter(from_utf8(type))) {
3405 counters.step(from_utf8(type));
3406 full_label = bformat(from_ascii("%1$s %2$s:"),
3408 counters.theCounter(from_utf8(type)));
3410 full_label = bformat(from_ascii("%1$s #:"), name);
3412 par.params().labelString(full_label);
3416 case LABEL_NO_LABEL:
3417 par.params().labelString(docstring());
3421 case LABEL_TOP_ENVIRONMENT:
3422 case LABEL_CENTERED_TOP_ENVIRONMENT:
3425 par.params().labelString(
3426 par.translateIfPossible(layout.labelstring(), bp));
3432 void Buffer::updateLabels(ParIterator & parit) const
3434 LASSERT(parit.pit() == 0, /**/);
3436 // set the position of the text in the buffer to be able
3437 // to resolve macros in it. This has nothing to do with
3438 // labels, but by putting it here we avoid implementing
3439 // a whole bunch of traversal routines just for this call.
3440 parit.text()->setMacrocontextPosition(parit);
3442 depth_type maxdepth = 0;
3443 pit_type const lastpit = parit.lastpit();
3444 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3445 // reduce depth if necessary
3446 parit->params().depth(min(parit->params().depth(), maxdepth));
3447 maxdepth = parit->getMaxDepthAfter();
3449 // set the counter for this paragraph
3450 setLabel(*this, parit);
3453 InsetList::const_iterator iit = parit->insetList().begin();
3454 InsetList::const_iterator end = parit->insetList().end();
3455 for (; iit != end; ++iit) {
3456 parit.pos() = iit->pos;
3457 iit->inset->updateLabels(parit);
3463 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
3464 WordLangTuple & word_lang, docstring_list & suggestions) const
3468 suggestions.clear();
3469 word_lang = WordLangTuple();
3470 // OK, we start from here.
3471 DocIterator const end = doc_iterator_end(this);
3472 for (; from != end; from.forwardPos()) {
3473 // We are only interested in text so remove the math CursorSlice.
3474 while (from.inMathed())
3475 from.forwardInset();
3477 if (from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions)) {