3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Stefan Schimanski
9 * Full author contact details are available in file CREDITS.
17 #include "LayoutFile.h"
18 #include "BiblioInfo.h"
19 #include "BranchList.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
25 #include "Converter.h"
27 #include "DocIterator.h"
29 #include "ErrorList.h"
32 #include "FuncRequest.h"
33 #include "InsetIterator.h"
34 #include "InsetList.h"
36 #include "LaTeXFeatures.h"
40 #include "LyXAction.h"
44 #include "output_docbook.h"
46 #include "output_latex.h"
47 #include "output_plaintext.h"
48 #include "paragraph_funcs.h"
49 #include "Paragraph.h"
50 #include "ParagraphParameters.h"
51 #include "ParIterator.h"
52 #include "PDFOptions.h"
55 #include "TexStream.h"
57 #include "TextClass.h"
58 #include "TocBackend.h"
60 #include "VCBackend.h"
64 #include "insets/InsetBibitem.h"
65 #include "insets/InsetBibtex.h"
66 #include "insets/InsetInclude.h"
67 #include "insets/InsetText.h"
69 #include "mathed/MacroTable.h"
70 #include "mathed/MathMacroTemplate.h"
71 #include "mathed/MathSupport.h"
73 #include "frontends/alert.h"
74 #include "frontends/Delegates.h"
75 #include "frontends/WorkAreaManager.h"
77 #include "graphics/Previews.h"
79 #include "support/lassert.h"
80 #include "support/convert.h"
81 #include "support/debug.h"
82 #include "support/ExceptionMessage.h"
83 #include "support/FileName.h"
84 #include "support/FileNameList.h"
85 #include "support/filetools.h"
86 #include "support/ForkedCalls.h"
87 #include "support/gettext.h"
88 #include "support/gzstream.h"
89 #include "support/lstrings.h"
90 #include "support/lyxalgo.h"
91 #include "support/os.h"
92 #include "support/Package.h"
93 #include "support/Path.h"
94 #include "support/textutils.h"
95 #include "support/types.h"
97 #include <boost/bind.hpp>
98 #include <boost/shared_ptr.hpp>
110 using namespace lyx::support;
114 namespace Alert = frontend::Alert;
115 namespace os = support::os;
119 // Do not remove the comment below, so we get merge conflict in
120 // independent branches. Instead add your own.
121 int const LYX_FORMAT = 348; // uwestoehr: add support for \*phantom
123 typedef map<string, bool> DepClean;
124 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
128 class BufferSet : public std::set<Buffer const *> {};
133 Impl(Buffer & parent, FileName const & file, bool readonly);
147 mutable TexRow texrow;
149 /// need to regenerate .tex?
153 mutable bool lyx_clean;
155 /// is autosave needed?
156 mutable bool bak_clean;
158 /// is this a unnamed file (New...)?
164 /// name of the file the buffer is associated with.
167 /** Set to true only when the file is fully loaded.
168 * Used to prevent the premature generation of previews
169 * and by the citation inset.
171 bool file_fully_loaded;
174 mutable TocBackend toc_backend;
177 typedef pair<DocIterator, MacroData> ScopeMacro;
178 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
179 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
180 /// map from the macro name to the position map,
181 /// which maps the macro definition position to the scope and the MacroData.
182 NamePositionScopeMacroMap macros;
185 /// positions of child buffers in the buffer
186 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
187 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
188 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
189 /// position of children buffers in this buffer
190 BufferPositionMap children_positions;
191 /// map from children inclusion positions to their scope and their buffer
192 PositionScopeBufferMap position_to_children;
194 /// Container for all sort of Buffer dependant errors.
195 map<string, ErrorList> errorLists;
197 /// timestamp and checksum used to test if the file has been externally
198 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
200 unsigned long checksum_;
203 frontend::WorkAreaManager * wa_;
208 /// A cache for the bibfiles (including bibfiles of loaded child
209 /// documents), needed for appropriate update of natbib labels.
210 mutable support::FileNameList bibfilesCache_;
212 // FIXME The caching mechanism could be improved. At present, we have a
213 // cache for each Buffer, that caches all the bibliography info for that
214 // Buffer. A more efficient solution would be to have a global cache per
215 // file, and then to construct the Buffer's bibinfo from that.
216 /// A cache for bibliography info
217 mutable BiblioInfo bibinfo_;
218 /// whether the bibinfo cache is valid
219 bool bibinfoCacheValid_;
220 /// Cache of timestamps of .bib files
221 map<FileName, time_t> bibfileStatus_;
223 mutable RefCache ref_cache_;
225 /// our Text that should be wrapped in an InsetText
228 /// This is here to force the test to be done whenever parent_buffer
230 Buffer const * parent() const {
231 // if parent_buffer is not loaded, then it has been unloaded,
232 // which means that parent_buffer is an invalid pointer. So we
233 // set it to null in that case.
234 if (!theBufferList().isLoaded(parent_buffer))
236 return parent_buffer;
239 void setParent(Buffer const * pb) { parent_buffer = pb; }
241 /// So we can force access via the accessors.
242 mutable Buffer const * parent_buffer;
246 /// Creates the per buffer temporary directory
247 static FileName createBufferTmpDir()
250 // We are in our own directory. Why bother to mangle name?
251 // In fact I wrote this code to circumvent a problematic behaviour
252 // (bug?) of EMX mkstemp().
253 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
254 convert<string>(count++));
256 if (!tmpfl.createDirectory(0777)) {
257 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
258 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
259 from_utf8(tmpfl.absFilename())));
265 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
266 : lyx_clean(true), bak_clean(true), unnamed(false),
267 read_only(readonly_), filename(file), file_fully_loaded(false),
268 toc_backend(&parent), macro_lock(false), timestamp_(0),
269 checksum_(0), wa_(0), undo_(parent), bibinfoCacheValid_(false),
272 temppath = createBufferTmpDir();
273 lyxvc.setBuffer(&parent);
275 wa_ = new frontend::WorkAreaManager;
279 Buffer::Buffer(string const & file, bool readonly)
280 : d(new Impl(*this, FileName(file), readonly)), gui_(0)
282 LYXERR(Debug::INFO, "Buffer::Buffer()");
284 d->inset = new InsetText(*this);
285 d->inset->setAutoBreakRows(true);
286 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
292 LYXERR(Debug::INFO, "Buffer::~Buffer()");
293 // here the buffer should take care that it is
294 // saved properly, before it goes into the void.
296 // GuiView already destroyed
299 if (d->unnamed && d->filename.extension() == "internal") {
300 // No need to do additional cleanups for internal buffer.
305 // loop over children
306 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
307 Impl::BufferPositionMap::iterator end = d->children_positions.end();
308 for (; it != end; ++it) {
309 Buffer * child = const_cast<Buffer *>(it->first);
310 // The child buffer might have been closed already.
311 if (theBufferList().isLoaded(child))
312 theBufferList().releaseChild(this, child);
315 // clear references to children in macro tables
316 d->children_positions.clear();
317 d->position_to_children.clear();
319 if (!d->temppath.destroyDirectory()) {
320 Alert::warning(_("Could not remove temporary directory"),
321 bformat(_("Could not remove the temporary directory %1$s"),
322 from_utf8(d->temppath.absFilename())));
325 // Remove any previewed LaTeX snippets associated with this buffer.
326 thePreviews().removeLoader(*this);
332 void Buffer::changed() const
339 frontend::WorkAreaManager & Buffer::workAreaManager() const
341 LASSERT(d->wa_, /**/);
346 Text & Buffer::text() const
348 return d->inset->text();
352 Inset & Buffer::inset() const
358 BufferParams & Buffer::params()
364 BufferParams const & Buffer::params() const
370 ParagraphList & Buffer::paragraphs()
372 return text().paragraphs();
376 ParagraphList const & Buffer::paragraphs() const
378 return text().paragraphs();
382 LyXVC & Buffer::lyxvc()
388 LyXVC const & Buffer::lyxvc() const
394 string const Buffer::temppath() const
396 return d->temppath.absFilename();
400 TexRow & Buffer::texrow()
406 TexRow const & Buffer::texrow() const
412 TocBackend & Buffer::tocBackend() const
414 return d->toc_backend;
418 Undo & Buffer::undo()
424 string Buffer::latexName(bool const no_path) const
426 FileName latex_name = makeLatexName(d->filename);
427 return no_path ? latex_name.onlyFileName()
428 : latex_name.absFilename();
432 string Buffer::logName(LogType * type) const
434 string const filename = latexName(false);
436 if (filename.empty()) {
442 string const path = temppath();
444 FileName const fname(addName(temppath(),
445 onlyFilename(changeExtension(filename,
447 FileName const bname(
448 addName(path, onlyFilename(
449 changeExtension(filename,
450 formats.extension("literate") + ".out"))));
452 // If no Latex log or Build log is newer, show Build log
454 if (bname.exists() &&
455 (!fname.exists() || fname.lastModified() < bname.lastModified())) {
456 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
459 return bname.absFilename();
461 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
464 return fname.absFilename();
468 void Buffer::setReadonly(bool const flag)
470 if (d->read_only != flag) {
477 void Buffer::setFileName(string const & newfile)
479 d->filename = makeAbsPath(newfile);
480 setReadonly(d->filename.isReadOnly());
485 int Buffer::readHeader(Lexer & lex)
487 int unknown_tokens = 0;
489 int begin_header_line = -1;
491 // Initialize parameters that may be/go lacking in header:
492 params().branchlist().clear();
493 params().preamble.erase();
494 params().options.erase();
495 params().master.erase();
496 params().float_placement.erase();
497 params().paperwidth.erase();
498 params().paperheight.erase();
499 params().leftmargin.erase();
500 params().rightmargin.erase();
501 params().topmargin.erase();
502 params().bottommargin.erase();
503 params().headheight.erase();
504 params().headsep.erase();
505 params().footskip.erase();
506 params().columnsep.erase();
507 params().fontsCJK.erase();
508 params().listings_params.clear();
509 params().clearLayoutModules();
510 params().clearRemovedModules();
511 params().pdfoptions().clear();
513 for (int i = 0; i < 4; ++i) {
514 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
515 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
518 ErrorList & errorList = d->errorLists["Parse"];
527 if (token == "\\end_header")
531 if (token == "\\begin_header") {
532 begin_header_line = line;
536 LYXERR(Debug::PARSER, "Handling document header token: `"
539 string unknown = params().readToken(lex, token, d->filename.onlyPath());
540 if (!unknown.empty()) {
541 if (unknown[0] != '\\' && token == "\\textclass") {
542 Alert::warning(_("Unknown document class"),
543 bformat(_("Using the default document class, because the "
544 "class %1$s is unknown."), from_utf8(unknown)));
547 docstring const s = bformat(_("Unknown token: "
551 errorList.push_back(ErrorItem(_("Document header error"),
556 if (begin_header_line) {
557 docstring const s = _("\\begin_header is missing");
558 errorList.push_back(ErrorItem(_("Document header error"),
562 params().makeDocumentClass();
564 return unknown_tokens;
569 // changed to be public and have one parameter
570 // Returns true if "\end_document" is not read (Asger)
571 bool Buffer::readDocument(Lexer & lex)
573 ErrorList & errorList = d->errorLists["Parse"];
576 if (!lex.checkFor("\\begin_document")) {
577 docstring const s = _("\\begin_document is missing");
578 errorList.push_back(ErrorItem(_("Document header error"),
582 // we are reading in a brand new document
583 LASSERT(paragraphs().empty(), /**/);
587 if (params().outputChanges) {
588 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
589 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
590 LaTeXFeatures::isAvailable("xcolor");
592 if (!dvipost && !xcolorulem) {
593 Alert::warning(_("Changes not shown in LaTeX output"),
594 _("Changes will not be highlighted in LaTeX output, "
595 "because neither dvipost nor xcolor/ulem are installed.\n"
596 "Please install these packages or redefine "
597 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
598 } else if (!xcolorulem) {
599 Alert::warning(_("Changes not shown in LaTeX output"),
600 _("Changes will not be highlighted in LaTeX output "
601 "when using pdflatex, because xcolor and ulem are not installed.\n"
602 "Please install both packages or redefine "
603 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
607 if (!params().master.empty()) {
608 FileName const master_file = makeAbsPath(params().master,
609 onlyPath(absFileName()));
610 if (isLyXFilename(master_file.absFilename())) {
612 checkAndLoadLyXFile(master_file, true);
614 // necessary e.g. after a reload
615 // to re-register the child (bug 5873)
616 // FIXME: clean up updateMacros (here, only
617 // child registering is needed).
618 master->updateMacros();
619 // set master as master buffer, but only
620 // if we are a real child
621 if (master->isChild(this))
623 // if the master is not fully loaded
624 // it is probably just loading this
625 // child. No warning needed then.
626 else if (master->isFullyLoaded())
627 LYXERR0("The master '"
629 << "' assigned to this document ("
631 << ") does not include "
632 "this document. Ignoring the master assignment.");
638 bool const res = text().read(*this, lex, errorList, d->inset);
641 updateMacroInstances();
646 // needed to insert the selection
647 void Buffer::insertStringAsLines(ParagraphList & pars,
648 pit_type & pit, pos_type & pos,
649 Font const & fn, docstring const & str, bool autobreakrows)
653 // insert the string, don't insert doublespace
654 bool space_inserted = true;
655 for (docstring::const_iterator cit = str.begin();
656 cit != str.end(); ++cit) {
657 Paragraph & par = pars[pit];
659 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
660 breakParagraph(params(), pars, pit, pos,
661 par.layout().isEnvironment());
664 space_inserted = true;
668 // do not insert consecutive spaces if !free_spacing
669 } else if ((*cit == ' ' || *cit == '\t') &&
670 space_inserted && !par.isFreeSpacing()) {
672 } else if (*cit == '\t') {
673 if (!par.isFreeSpacing()) {
674 // tabs are like spaces here
675 par.insertChar(pos, ' ', font, params().trackChanges);
677 space_inserted = true;
679 par.insertChar(pos, *cit, font, params().trackChanges);
681 space_inserted = true;
683 } else if (!isPrintable(*cit)) {
684 // Ignore unprintables
687 // just insert the character
688 par.insertChar(pos, *cit, font, params().trackChanges);
690 space_inserted = (*cit == ' ');
697 bool Buffer::readString(string const & s)
699 params().compressed = false;
701 // remove dummy empty par
702 paragraphs().clear();
706 FileName const name = FileName::tempName("Buffer_readString");
707 switch (readFile(lex, name, true)) {
711 // We need to call lyx2lyx, so write the input to a file
712 ofstream os(name.toFilesystemEncoding().c_str());
715 return readFile(name);
725 bool Buffer::readFile(FileName const & filename)
727 FileName fname(filename);
729 params().compressed = fname.isZippedFile();
731 // remove dummy empty par
732 paragraphs().clear();
735 if (readFile(lex, fname) != success)
742 bool Buffer::isFullyLoaded() const
744 return d->file_fully_loaded;
748 void Buffer::setFullyLoaded(bool value)
750 d->file_fully_loaded = value;
754 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
757 LASSERT(!filename.empty(), /**/);
759 // the first (non-comment) token _must_ be...
760 if (!lex.checkFor("\\lyxformat")) {
761 Alert::error(_("Document format failure"),
762 bformat(_("%1$s is not a readable LyX document."),
763 from_utf8(filename.absFilename())));
769 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
770 // if present remove ".," from string.
771 size_t dot = tmp_format.find_first_of(".,");
772 //lyxerr << " dot found at " << dot << endl;
773 if (dot != string::npos)
774 tmp_format.erase(dot, 1);
775 int const file_format = convert<int>(tmp_format);
776 //lyxerr << "format: " << file_format << endl;
778 // save timestamp and checksum of the original disk file, making sure
779 // to not overwrite them with those of the file created in the tempdir
780 // when it has to be converted to the current format.
782 // Save the timestamp and checksum of disk file. If filename is an
783 // emergency file, save the timestamp and checksum of the original lyx file
784 // because isExternallyModified will check for this file. (BUG4193)
785 string diskfile = filename.absFilename();
786 if (suffixIs(diskfile, ".emergency"))
787 diskfile = diskfile.substr(0, diskfile.size() - 10);
788 saveCheckSum(FileName(diskfile));
791 if (file_format != LYX_FORMAT) {
794 // lyx2lyx would fail
797 FileName const tmpfile = FileName::tempName("Buffer_readFile");
798 if (tmpfile.empty()) {
799 Alert::error(_("Conversion failed"),
800 bformat(_("%1$s is from a different"
801 " version of LyX, but a temporary"
802 " file for converting it could"
804 from_utf8(filename.absFilename())));
807 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
808 if (lyx2lyx.empty()) {
809 Alert::error(_("Conversion script not found"),
810 bformat(_("%1$s is from a different"
811 " version of LyX, but the"
812 " conversion script lyx2lyx"
813 " could not be found."),
814 from_utf8(filename.absFilename())));
817 ostringstream command;
818 command << os::python()
819 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
820 << " -t " << convert<string>(LYX_FORMAT)
821 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
822 << ' ' << quoteName(filename.toFilesystemEncoding());
823 string const command_str = command.str();
825 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
827 cmd_ret const ret = runCommand(command_str);
828 if (ret.first != 0) {
829 Alert::error(_("Conversion script failed"),
830 bformat(_("%1$s is from a different version"
831 " of LyX, but the lyx2lyx script"
832 " failed to convert it."),
833 from_utf8(filename.absFilename())));
836 bool const ret = readFile(tmpfile);
837 // Do stuff with tmpfile name and buffer name here.
838 return ret ? success : failure;
843 if (readDocument(lex)) {
844 Alert::error(_("Document format failure"),
845 bformat(_("%1$s ended unexpectedly, which means"
846 " that it is probably corrupted."),
847 from_utf8(filename.absFilename())));
850 d->file_fully_loaded = true;
855 // Should probably be moved to somewhere else: BufferView? LyXView?
856 bool Buffer::save() const
858 // We don't need autosaves in the immediate future. (Asger)
859 resetAutosaveTimers();
861 string const encodedFilename = d->filename.toFilesystemEncoding();
864 bool madeBackup = false;
866 // make a backup if the file already exists
867 if (lyxrc.make_backup && fileName().exists()) {
868 backupName = FileName(absFileName() + '~');
869 if (!lyxrc.backupdir_path.empty()) {
870 string const mangledName =
871 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
872 backupName = FileName(addName(lyxrc.backupdir_path,
875 if (fileName().copyTo(backupName)) {
878 Alert::error(_("Backup failure"),
879 bformat(_("Cannot create backup file %1$s.\n"
880 "Please check whether the directory exists and is writeable."),
881 from_utf8(backupName.absFilename())));
882 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
886 // ask if the disk file has been externally modified (use checksum method)
887 if (fileName().exists() && isExternallyModified(checksum_method)) {
888 docstring const file = makeDisplayPath(absFileName(), 20);
889 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
890 "you want to overwrite this file?"), file);
891 int const ret = Alert::prompt(_("Overwrite modified file?"),
892 text, 1, 1, _("&Overwrite"), _("&Cancel"));
897 if (writeFile(d->filename)) {
901 // Saving failed, so backup is not backup
903 backupName.moveTo(d->filename);
909 bool Buffer::writeFile(FileName const & fname) const
911 if (d->read_only && fname == d->filename)
916 docstring const str = bformat(_("Saving document %1$s..."),
917 makeDisplayPath(fname.absFilename()));
920 if (params().compressed) {
921 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
922 retval = ofs && write(ofs);
924 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
925 retval = ofs && write(ofs);
929 message(str + _(" could not write file!"));
933 removeAutosaveFile();
935 saveCheckSum(d->filename);
936 message(str + _(" done."));
942 bool Buffer::write(ostream & ofs) const
945 // Use the standard "C" locale for file output.
946 ofs.imbue(locale::classic());
949 // The top of the file should not be written by params().
951 // write out a comment in the top of the file
952 ofs << "#LyX " << lyx_version
953 << " created this file. For more info see http://www.lyx.org/\n"
954 << "\\lyxformat " << LYX_FORMAT << "\n"
955 << "\\begin_document\n";
957 /// For each author, set 'used' to true if there is a change
958 /// by this author in the document; otherwise set it to 'false'.
959 AuthorList::Authors::const_iterator a_it = params().authors().begin();
960 AuthorList::Authors::const_iterator a_end = params().authors().end();
961 for (; a_it != a_end; ++a_it)
962 a_it->second.setUsed(false);
964 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
965 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
966 for ( ; it != end; ++it)
967 it->checkAuthors(params().authors());
969 // now write out the buffer parameters.
970 ofs << "\\begin_header\n";
971 params().writeFile(ofs);
972 ofs << "\\end_header\n";
975 ofs << "\n\\begin_body\n";
976 text().write(*this, ofs);
977 ofs << "\n\\end_body\n";
979 // Write marker that shows file is complete
980 ofs << "\\end_document" << endl;
982 // Shouldn't really be needed....
985 // how to check if close went ok?
986 // Following is an attempt... (BE 20001011)
988 // good() returns false if any error occured, including some
990 // bad() returns true if something bad happened in the buffer,
991 // which should include file system full errors.
996 lyxerr << "File was not closed properly." << endl;
1003 bool Buffer::makeLaTeXFile(FileName const & fname,
1004 string const & original_path,
1005 OutputParams const & runparams,
1006 bool output_preamble, bool output_body) const
1008 string const encoding = runparams.encoding->iconvName();
1009 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1012 try { ofs.reset(encoding); }
1013 catch (iconv_codecvt_facet_exception & e) {
1014 lyxerr << "Caught iconv exception: " << e.what() << endl;
1015 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1016 "verify that the support software for your encoding (%1$s) is "
1017 "properly installed"), from_ascii(encoding)));
1020 if (!openFileWrite(ofs, fname))
1023 //TexStream ts(ofs.rdbuf(), &texrow());
1024 ErrorList & errorList = d->errorLists["Export"];
1026 bool failed_export = false;
1029 writeLaTeXSource(ofs, original_path,
1030 runparams, output_preamble, output_body);
1032 catch (EncodingException & e) {
1033 odocstringstream ods;
1034 ods.put(e.failed_char);
1036 oss << "0x" << hex << e.failed_char << dec;
1037 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1038 " (code point %2$s)"),
1039 ods.str(), from_utf8(oss.str()));
1040 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1041 "representable in the chosen encoding.\n"
1042 "Changing the document encoding to utf8 could help."),
1043 e.par_id, e.pos, e.pos + 1));
1044 failed_export = true;
1046 catch (iconv_codecvt_facet_exception & e) {
1047 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1048 _(e.what()), -1, 0, 0));
1049 failed_export = true;
1051 catch (exception const & e) {
1052 errorList.push_back(ErrorItem(_("conversion failed"),
1053 _(e.what()), -1, 0, 0));
1054 failed_export = true;
1057 lyxerr << "Caught some really weird exception..." << endl;
1063 failed_export = true;
1064 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1068 return !failed_export;
1072 void Buffer::writeLaTeXSource(odocstream & os,
1073 string const & original_path,
1074 OutputParams const & runparams_in,
1075 bool const output_preamble, bool const output_body) const
1077 // The child documents, if any, shall be already loaded at this point.
1079 OutputParams runparams = runparams_in;
1081 // Classify the unicode characters appearing in math insets
1082 Encodings::initUnicodeMath(*this);
1084 // validate the buffer.
1085 LYXERR(Debug::LATEX, " Validating buffer...");
1086 LaTeXFeatures features(*this, params(), runparams);
1088 LYXERR(Debug::LATEX, " Buffer validation done.");
1090 // The starting paragraph of the coming rows is the
1091 // first paragraph of the document. (Asger)
1092 if (output_preamble && runparams.nice) {
1093 os << "%% LyX " << lyx_version << " created this file. "
1094 "For more info, see http://www.lyx.org/.\n"
1095 "%% Do not edit unless you really know what "
1097 d->texrow.newline();
1098 d->texrow.newline();
1100 LYXERR(Debug::INFO, "lyx document header finished");
1102 // Don't move this behind the parent_buffer=0 code below,
1103 // because then the macros will not get the right "redefinition"
1104 // flag as they don't see the parent macros which are output before.
1107 // fold macros if possible, still with parent buffer as the
1108 // macros will be put in the prefix anyway.
1109 updateMacroInstances();
1111 // There are a few differences between nice LaTeX and usual files:
1112 // usual is \batchmode and has a
1113 // special input@path to allow the including of figures
1114 // with either \input or \includegraphics (what figinsets do).
1115 // input@path is set when the actual parameter
1116 // original_path is set. This is done for usual tex-file, but not
1117 // for nice-latex-file. (Matthias 250696)
1118 // Note that input@path is only needed for something the user does
1119 // in the preamble, included .tex files or ERT, files included by
1120 // LyX work without it.
1121 if (output_preamble) {
1122 if (!runparams.nice) {
1123 // code for usual, NOT nice-latex-file
1124 os << "\\batchmode\n"; // changed
1125 // from \nonstopmode
1126 d->texrow.newline();
1128 if (!original_path.empty()) {
1130 // We don't know the encoding of inputpath
1131 docstring const inputpath = from_utf8(latex_path(original_path));
1132 os << "\\makeatletter\n"
1133 << "\\def\\input@path{{"
1134 << inputpath << "/}}\n"
1135 << "\\makeatother\n";
1136 d->texrow.newline();
1137 d->texrow.newline();
1138 d->texrow.newline();
1141 // get parent macros (if this buffer has a parent) which will be
1142 // written at the document begin further down.
1143 MacroSet parentMacros;
1144 listParentMacros(parentMacros, features);
1146 // Write the preamble
1147 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1149 runparams.use_japanese = features.isRequired("japanese");
1155 os << "\\begin{document}\n";
1156 d->texrow.newline();
1158 // output the parent macros
1159 MacroSet::iterator it = parentMacros.begin();
1160 MacroSet::iterator end = parentMacros.end();
1161 for (; it != end; ++it)
1162 (*it)->write(os, true);
1163 } // output_preamble
1165 d->texrow.start(paragraphs().begin()->id(), 0);
1167 LYXERR(Debug::INFO, "preamble finished, now the body.");
1169 // if we are doing a real file with body, even if this is the
1170 // child of some other buffer, let's cut the link here.
1171 // This happens for example if only a child document is printed.
1172 Buffer const * save_parent = 0;
1173 if (output_preamble) {
1174 save_parent = d->parent();
1179 latexParagraphs(*this, text(), os, d->texrow, runparams);
1181 // Restore the parenthood if needed
1182 if (output_preamble)
1183 d->setParent(save_parent);
1185 // add this just in case after all the paragraphs
1187 d->texrow.newline();
1189 if (output_preamble) {
1190 os << "\\end{document}\n";
1191 d->texrow.newline();
1192 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1194 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1196 runparams_in.encoding = runparams.encoding;
1198 // Just to be sure. (Asger)
1199 d->texrow.newline();
1201 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1202 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1206 bool Buffer::isLatex() const
1208 return params().documentClass().outputType() == LATEX;
1212 bool Buffer::isLiterate() const
1214 return params().documentClass().outputType() == LITERATE;
1218 bool Buffer::isDocBook() const
1220 return params().documentClass().outputType() == DOCBOOK;
1224 void Buffer::makeDocBookFile(FileName const & fname,
1225 OutputParams const & runparams,
1226 bool const body_only) const
1228 LYXERR(Debug::LATEX, "makeDocBookFile...");
1231 if (!openFileWrite(ofs, fname))
1234 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1238 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1242 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1243 OutputParams const & runparams,
1244 bool const only_body) const
1246 LaTeXFeatures features(*this, params(), runparams);
1251 DocumentClass const & tclass = params().documentClass();
1252 string const top_element = tclass.latexname();
1255 if (runparams.flavor == OutputParams::XML)
1256 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1259 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1262 if (! tclass.class_header().empty())
1263 os << from_ascii(tclass.class_header());
1264 else if (runparams.flavor == OutputParams::XML)
1265 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1266 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1268 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1270 docstring preamble = from_utf8(params().preamble);
1271 if (runparams.flavor != OutputParams::XML ) {
1272 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1273 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1274 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1275 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1278 string const name = runparams.nice
1279 ? changeExtension(absFileName(), ".sgml") : fname;
1280 preamble += features.getIncludedFiles(name);
1281 preamble += features.getLyXSGMLEntities();
1283 if (!preamble.empty()) {
1284 os << "\n [ " << preamble << " ]";
1289 string top = top_element;
1291 if (runparams.flavor == OutputParams::XML)
1292 top += params().language->code();
1294 top += params().language->code().substr(0, 2);
1297 if (!params().options.empty()) {
1299 top += params().options;
1302 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1303 << " file was created by LyX " << lyx_version
1304 << "\n See http://www.lyx.org/ for more information -->\n";
1306 params().documentClass().counters().reset();
1310 sgml::openTag(os, top);
1312 docbookParagraphs(paragraphs(), *this, os, runparams);
1313 sgml::closeTag(os, top_element);
1317 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1318 // Other flags: -wall -v0 -x
1319 int Buffer::runChktex()
1323 // get LaTeX-Filename
1324 FileName const path(temppath());
1325 string const name = addName(path.absFilename(), latexName());
1326 string const org_path = filePath();
1328 PathChanger p(path); // path to LaTeX file
1329 message(_("Running chktex..."));
1331 // Generate the LaTeX file if neccessary
1332 OutputParams runparams(¶ms().encoding());
1333 runparams.flavor = OutputParams::LATEX;
1334 runparams.nice = false;
1335 makeLaTeXFile(FileName(name), org_path, runparams);
1338 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1339 int const res = chktex.run(terr); // run chktex
1342 Alert::error(_("chktex failure"),
1343 _("Could not run chktex successfully."));
1344 } else if (res > 0) {
1345 ErrorList & errlist = d->errorLists["ChkTeX"];
1347 bufferErrors(terr, errlist);
1358 void Buffer::validate(LaTeXFeatures & features) const
1360 params().validate(features);
1364 for_each(paragraphs().begin(), paragraphs().end(),
1365 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1367 if (lyxerr.debugging(Debug::LATEX)) {
1368 features.showStruct();
1373 void Buffer::getLabelList(vector<docstring> & list) const
1375 // If this is a child document, use the parent's list instead.
1376 Buffer const * const pbuf = d->parent();
1378 pbuf->getLabelList(list);
1383 Toc & toc = d->toc_backend.toc("label");
1384 TocIterator toc_it = toc.begin();
1385 TocIterator end = toc.end();
1386 for (; toc_it != end; ++toc_it) {
1387 if (toc_it->depth() == 0)
1388 list.push_back(toc_it->str());
1393 void Buffer::updateBibfilesCache(UpdateScope scope) const
1395 // If this is a child document, use the parent's cache instead.
1396 Buffer const * const pbuf = d->parent();
1397 if (pbuf && scope != UpdateChildOnly) {
1398 pbuf->updateBibfilesCache();
1402 d->bibfilesCache_.clear();
1403 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1404 if (it->lyxCode() == BIBTEX_CODE) {
1405 InsetBibtex const & inset =
1406 static_cast<InsetBibtex const &>(*it);
1407 support::FileNameList const bibfiles = inset.getBibFiles();
1408 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1411 } else if (it->lyxCode() == INCLUDE_CODE) {
1412 InsetInclude & inset =
1413 static_cast<InsetInclude &>(*it);
1414 inset.updateBibfilesCache();
1415 support::FileNameList const & bibfiles =
1416 inset.getBibfilesCache();
1417 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1422 // the bibinfo cache is now invalid
1423 d->bibinfoCacheValid_ = false;
1427 void Buffer::invalidateBibinfoCache()
1429 d->bibinfoCacheValid_ = false;
1433 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1435 // If this is a child document, use the parent's cache instead.
1436 Buffer const * const pbuf = d->parent();
1437 if (pbuf && scope != UpdateChildOnly)
1438 return pbuf->getBibfilesCache();
1440 // We update the cache when first used instead of at loading time.
1441 if (d->bibfilesCache_.empty())
1442 const_cast<Buffer *>(this)->updateBibfilesCache(scope);
1444 return d->bibfilesCache_;
1448 BiblioInfo const & Buffer::masterBibInfo() const
1450 // if this is a child document and the parent is already loaded
1451 // use the parent's list instead [ale990412]
1452 Buffer const * const tmp = masterBuffer();
1455 return tmp->masterBibInfo();
1456 return localBibInfo();
1460 BiblioInfo const & Buffer::localBibInfo() const
1462 if (d->bibinfoCacheValid_) {
1463 support::FileNameList const & bibfilesCache = getBibfilesCache();
1464 // compare the cached timestamps with the actual ones.
1465 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1466 support::FileNameList::const_iterator en = bibfilesCache.end();
1467 for (; ei != en; ++ ei) {
1468 time_t lastw = ei->lastModified();
1469 if (lastw != d->bibfileStatus_[*ei]) {
1470 d->bibinfoCacheValid_ = false;
1471 d->bibfileStatus_[*ei] = lastw;
1477 if (!d->bibinfoCacheValid_) {
1478 d->bibinfo_.clear();
1479 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1480 it->fillWithBibKeys(d->bibinfo_, it);
1481 d->bibinfoCacheValid_ = true;
1487 bool Buffer::isDepClean(string const & name) const
1489 DepClean::const_iterator const it = d->dep_clean.find(name);
1490 if (it == d->dep_clean.end())
1496 void Buffer::markDepClean(string const & name)
1498 d->dep_clean[name] = true;
1502 bool Buffer::dispatch(string const & command, bool * result)
1504 return dispatch(lyxaction.lookupFunc(command), result);
1508 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1510 bool dispatched = true;
1512 switch (func.action) {
1513 case LFUN_BUFFER_EXPORT: {
1514 bool const tmp = doExport(to_utf8(func.argument()), false);
1520 case LFUN_BRANCH_ACTIVATE:
1521 case LFUN_BRANCH_DEACTIVATE: {
1522 BranchList & branchList = params().branchlist();
1523 docstring const branchName = func.argument();
1524 // the case without a branch name is handled elsewhere
1525 if (branchName.empty()) {
1529 Branch * branch = branchList.find(branchName);
1531 LYXERR0("Branch " << branchName << " does not exist.");
1533 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1545 void Buffer::changeLanguage(Language const * from, Language const * to)
1547 LASSERT(from, /**/);
1550 for_each(par_iterator_begin(),
1552 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1556 bool Buffer::isMultiLingual() const
1558 ParConstIterator end = par_iterator_end();
1559 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1560 if (it->isMultiLingual(params()))
1567 DocIterator Buffer::getParFromID(int const id) const
1569 Buffer * buf = const_cast<Buffer *>(this);
1571 // John says this is called with id == -1 from undo
1572 lyxerr << "getParFromID(), id: " << id << endl;
1573 return doc_iterator_end(buf);
1576 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
1577 if (it.paragraph().id() == id)
1580 return doc_iterator_end(buf);
1584 bool Buffer::hasParWithID(int const id) const
1586 return !getParFromID(id).atEnd();
1590 ParIterator Buffer::par_iterator_begin()
1592 return ParIterator(doc_iterator_begin(this));
1596 ParIterator Buffer::par_iterator_end()
1598 return ParIterator(doc_iterator_end(this));
1602 ParConstIterator Buffer::par_iterator_begin() const
1604 return ParConstIterator(doc_iterator_begin(this));
1608 ParConstIterator Buffer::par_iterator_end() const
1610 return ParConstIterator(doc_iterator_end(this));
1614 Language const * Buffer::language() const
1616 return params().language;
1620 docstring const Buffer::B_(string const & l10n) const
1622 return params().B_(l10n);
1626 bool Buffer::isClean() const
1628 return d->lyx_clean;
1632 bool Buffer::isBakClean() const
1634 return d->bak_clean;
1638 bool Buffer::isExternallyModified(CheckMethod method) const
1640 LASSERT(d->filename.exists(), /**/);
1641 // if method == timestamp, check timestamp before checksum
1642 return (method == checksum_method
1643 || d->timestamp_ != d->filename.lastModified())
1644 && d->checksum_ != d->filename.checksum();
1648 void Buffer::saveCheckSum(FileName const & file) const
1650 if (file.exists()) {
1651 d->timestamp_ = file.lastModified();
1652 d->checksum_ = file.checksum();
1654 // in the case of save to a new file.
1661 void Buffer::markClean() const
1663 if (!d->lyx_clean) {
1664 d->lyx_clean = true;
1667 // if the .lyx file has been saved, we don't need an
1669 d->bak_clean = true;
1673 void Buffer::markBakClean() const
1675 d->bak_clean = true;
1679 void Buffer::setUnnamed(bool flag)
1685 bool Buffer::isUnnamed() const
1691 // FIXME: this function should be moved to buffer_pimpl.C
1692 void Buffer::markDirty()
1695 d->lyx_clean = false;
1698 d->bak_clean = false;
1700 DepClean::iterator it = d->dep_clean.begin();
1701 DepClean::const_iterator const end = d->dep_clean.end();
1703 for (; it != end; ++it)
1708 FileName Buffer::fileName() const
1714 string Buffer::absFileName() const
1716 return d->filename.absFilename();
1720 string Buffer::filePath() const
1722 return d->filename.onlyPath().absFilename() + "/";
1726 bool Buffer::isReadonly() const
1728 return d->read_only;
1732 void Buffer::setParent(Buffer const * buffer)
1734 // Avoids recursive include.
1735 d->setParent(buffer == this ? 0 : buffer);
1740 Buffer const * Buffer::parent() const
1746 void Buffer::collectRelatives(BufferSet & bufs) const
1750 parent()->collectRelatives(bufs);
1752 // loop over children
1753 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
1754 Impl::BufferPositionMap::iterator end = d->children_positions.end();
1755 for (; it != end; ++it)
1756 bufs.insert(const_cast<Buffer *>(it->first));
1760 std::vector<Buffer const *> Buffer::allRelatives() const
1763 collectRelatives(bufs);
1764 BufferSet::iterator it = bufs.begin();
1765 std::vector<Buffer const *> ret;
1766 for (; it != bufs.end(); ++it)
1772 Buffer const * Buffer::masterBuffer() const
1774 Buffer const * const pbuf = d->parent();
1778 return pbuf->masterBuffer();
1782 bool Buffer::isChild(Buffer * child) const
1784 return d->children_positions.find(child) != d->children_positions.end();
1788 DocIterator Buffer::firstChildPosition(Buffer const * child)
1790 Impl::BufferPositionMap::iterator it;
1791 it = d->children_positions.find(child);
1792 if (it == d->children_positions.end())
1793 return DocIterator(this);
1798 std::vector<Buffer *> Buffer::getChildren() const
1800 std::vector<Buffer *> clist;
1801 // loop over children
1802 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
1803 Impl::BufferPositionMap::iterator end = d->children_positions.end();
1804 for (; it != end; ++it) {
1805 Buffer * child = const_cast<Buffer *>(it->first);
1806 clist.push_back(child);
1807 // there might be grandchildren
1808 std::vector<Buffer *> glist = child->getChildren();
1809 for (vector<Buffer *>::const_iterator git = glist.begin();
1810 git != glist.end(); ++git)
1811 clist.push_back(*git);
1817 template<typename M>
1818 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
1823 typename M::iterator it = m.lower_bound(x);
1824 if (it == m.begin())
1832 MacroData const * Buffer::getBufferMacro(docstring const & name,
1833 DocIterator const & pos) const
1835 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
1837 // if paragraphs have no macro context set, pos will be empty
1841 // we haven't found anything yet
1842 DocIterator bestPos = par_iterator_begin();
1843 MacroData const * bestData = 0;
1845 // find macro definitions for name
1846 Impl::NamePositionScopeMacroMap::iterator nameIt
1847 = d->macros.find(name);
1848 if (nameIt != d->macros.end()) {
1849 // find last definition in front of pos or at pos itself
1850 Impl::PositionScopeMacroMap::const_iterator it
1851 = greatest_below(nameIt->second, pos);
1852 if (it != nameIt->second.end()) {
1854 // scope ends behind pos?
1855 if (pos < it->second.first) {
1856 // Looks good, remember this. If there
1857 // is no external macro behind this,
1858 // we found the right one already.
1859 bestPos = it->first;
1860 bestData = &it->second.second;
1864 // try previous macro if there is one
1865 if (it == nameIt->second.begin())
1872 // find macros in included files
1873 Impl::PositionScopeBufferMap::const_iterator it
1874 = greatest_below(d->position_to_children, pos);
1875 if (it == d->position_to_children.end())
1876 // no children before
1880 // do we know something better (i.e. later) already?
1881 if (it->first < bestPos )
1884 // scope ends behind pos?
1885 if (pos < it->second.first) {
1886 // look for macro in external file
1887 d->macro_lock = true;
1888 MacroData const * data
1889 = it->second.second->getMacro(name, false);
1890 d->macro_lock = false;
1892 bestPos = it->first;
1898 // try previous file if there is one
1899 if (it == d->position_to_children.begin())
1904 // return the best macro we have found
1909 MacroData const * Buffer::getMacro(docstring const & name,
1910 DocIterator const & pos, bool global) const
1915 // query buffer macros
1916 MacroData const * data = getBufferMacro(name, pos);
1920 // If there is a master buffer, query that
1921 Buffer const * const pbuf = d->parent();
1923 d->macro_lock = true;
1924 MacroData const * macro = pbuf->getMacro(
1925 name, *this, false);
1926 d->macro_lock = false;
1932 data = MacroTable::globalMacros().get(name);
1941 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
1943 // set scope end behind the last paragraph
1944 DocIterator scope = par_iterator_begin();
1945 scope.pit() = scope.lastpit() + 1;
1947 return getMacro(name, scope, global);
1951 MacroData const * Buffer::getMacro(docstring const & name,
1952 Buffer const & child, bool global) const
1954 // look where the child buffer is included first
1955 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
1956 if (it == d->children_positions.end())
1959 // check for macros at the inclusion position
1960 return getMacro(name, it->second, global);
1964 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
1966 pit_type lastpit = it.lastpit();
1968 // look for macros in each paragraph
1969 while (it.pit() <= lastpit) {
1970 Paragraph & par = it.paragraph();
1972 // iterate over the insets of the current paragraph
1973 InsetList const & insets = par.insetList();
1974 InsetList::const_iterator iit = insets.begin();
1975 InsetList::const_iterator end = insets.end();
1976 for (; iit != end; ++iit) {
1977 it.pos() = iit->pos;
1979 // is it a nested text inset?
1980 if (iit->inset->asInsetText()) {
1981 // Inset needs its own scope?
1982 InsetText const * itext = iit->inset->asInsetText();
1983 bool newScope = itext->isMacroScope();
1985 // scope which ends just behind the inset
1986 DocIterator insetScope = it;
1989 // collect macros in inset
1990 it.push_back(CursorSlice(*iit->inset));
1991 updateMacros(it, newScope ? insetScope : scope);
1996 // is it an external file?
1997 if (iit->inset->lyxCode() == INCLUDE_CODE) {
1998 // get buffer of external file
1999 InsetInclude const & inset =
2000 static_cast<InsetInclude const &>(*iit->inset);
2001 d->macro_lock = true;
2002 Buffer * child = inset.getChildBuffer();
2003 d->macro_lock = false;
2007 // register its position, but only when it is
2008 // included first in the buffer
2009 if (d->children_positions.find(child) ==
2010 d->children_positions.end())
2011 d->children_positions[child] = it;
2013 // register child with its scope
2014 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
2018 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2022 MathMacroTemplate & macroTemplate =
2023 static_cast<MathMacroTemplate &>(*iit->inset);
2024 MacroContext mc(*this, it);
2025 macroTemplate.updateToContext(mc);
2028 bool valid = macroTemplate.validMacro();
2029 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2030 // then the BufferView's cursor will be invalid in
2031 // some cases which leads to crashes.
2036 d->macros[macroTemplate.name()][it] =
2037 Impl::ScopeMacro(scope, MacroData(*this, it));
2047 void Buffer::updateMacros() const
2052 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2054 // start with empty table
2056 d->children_positions.clear();
2057 d->position_to_children.clear();
2059 // Iterate over buffer, starting with first paragraph
2060 // The scope must be bigger than any lookup DocIterator
2061 // later. For the global lookup, lastpit+1 is used, hence
2062 // we use lastpit+2 here.
2063 DocIterator it = par_iterator_begin();
2064 DocIterator outerScope = it;
2065 outerScope.pit() = outerScope.lastpit() + 2;
2066 updateMacros(it, outerScope);
2070 void Buffer::updateMacroInstances() const
2072 LYXERR(Debug::MACROS, "updateMacroInstances for "
2073 << d->filename.onlyFileName());
2074 DocIterator it = doc_iterator_begin(this);
2075 DocIterator end = doc_iterator_end(this);
2076 for (; it != end; it.forwardPos()) {
2077 // look for MathData cells in InsetMathNest insets
2078 Inset * inset = it.nextInset();
2082 InsetMath * minset = inset->asInsetMath();
2086 // update macro in all cells of the InsetMathNest
2087 DocIterator::idx_type n = minset->nargs();
2088 MacroContext mc = MacroContext(*this, it);
2089 for (DocIterator::idx_type i = 0; i < n; ++i) {
2090 MathData & data = minset->cell(i);
2091 data.updateMacros(0, mc);
2097 void Buffer::listMacroNames(MacroNameSet & macros) const
2102 d->macro_lock = true;
2104 // loop over macro names
2105 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2106 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2107 for (; nameIt != nameEnd; ++nameIt)
2108 macros.insert(nameIt->first);
2110 // loop over children
2111 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2112 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2113 for (; it != end; ++it)
2114 it->first->listMacroNames(macros);
2117 Buffer const * const pbuf = d->parent();
2119 pbuf->listMacroNames(macros);
2121 d->macro_lock = false;
2125 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2127 Buffer const * const pbuf = d->parent();
2132 pbuf->listMacroNames(names);
2135 MacroNameSet::iterator it = names.begin();
2136 MacroNameSet::iterator end = names.end();
2137 for (; it != end; ++it) {
2139 MacroData const * data =
2140 pbuf->getMacro(*it, *this, false);
2142 macros.insert(data);
2144 // we cannot access the original MathMacroTemplate anymore
2145 // here to calls validate method. So we do its work here manually.
2146 // FIXME: somehow make the template accessible here.
2147 if (data->optionals() > 0)
2148 features.require("xargs");
2154 Buffer::References & Buffer::references(docstring const & label)
2157 return const_cast<Buffer *>(masterBuffer())->references(label);
2159 RefCache::iterator it = d->ref_cache_.find(label);
2160 if (it != d->ref_cache_.end())
2161 return it->second.second;
2163 static InsetLabel const * dummy_il = 0;
2164 static References const dummy_refs;
2165 it = d->ref_cache_.insert(
2166 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2167 return it->second.second;
2171 Buffer::References const & Buffer::references(docstring const & label) const
2173 return const_cast<Buffer *>(this)->references(label);
2177 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2179 masterBuffer()->d->ref_cache_[label].first = il;
2183 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2185 return masterBuffer()->d->ref_cache_[label].first;
2189 void Buffer::clearReferenceCache() const
2192 d->ref_cache_.clear();
2196 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2199 //FIXME: This does not work for child documents yet.
2200 LASSERT(code == CITE_CODE, /**/);
2201 // Check if the label 'from' appears more than once
2202 vector<docstring> labels;
2204 BiblioInfo const & keys = masterBibInfo();
2205 BiblioInfo::const_iterator bit = keys.begin();
2206 BiblioInfo::const_iterator bend = keys.end();
2208 for (; bit != bend; ++bit)
2210 labels.push_back(bit->first);
2213 if (count(labels.begin(), labels.end(), from) > 1)
2216 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2217 if (it->lyxCode() == code) {
2218 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2219 docstring const oldValue = inset.getParam(paramName);
2220 if (oldValue == from)
2221 inset.setParam(paramName, to);
2227 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2228 pit_type par_end, bool full_source) const
2230 OutputParams runparams(¶ms().encoding());
2231 runparams.nice = true;
2232 runparams.flavor = OutputParams::LATEX;
2233 runparams.linelen = lyxrc.plaintext_linelen;
2234 // No side effect of file copying and image conversion
2235 runparams.dryrun = true;
2239 os << "% " << _("Preview source code") << "\n\n";
2240 d->texrow.newline();
2241 d->texrow.newline();
2243 writeDocBookSource(os, absFileName(), runparams, false);
2245 // latex or literate
2246 writeLaTeXSource(os, string(), runparams, true, true);
2248 runparams.par_begin = par_begin;
2249 runparams.par_end = par_end;
2250 if (par_begin + 1 == par_end) {
2252 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2256 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2257 convert<docstring>(par_begin),
2258 convert<docstring>(par_end - 1))
2261 d->texrow.newline();
2262 d->texrow.newline();
2263 // output paragraphs
2265 docbookParagraphs(paragraphs(), *this, os, runparams);
2267 // latex or literate
2268 latexParagraphs(*this, text(), os, d->texrow, runparams);
2273 ErrorList & Buffer::errorList(string const & type) const
2275 static ErrorList emptyErrorList;
2276 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2277 if (I == d->errorLists.end())
2278 return emptyErrorList;
2284 void Buffer::updateTocItem(std::string const & type,
2285 DocIterator const & dit) const
2288 gui_->updateTocItem(type, dit);
2292 void Buffer::structureChanged() const
2295 gui_->structureChanged();
2299 void Buffer::errors(string const & err) const
2306 void Buffer::message(docstring const & msg) const
2313 void Buffer::setBusy(bool on) const
2320 void Buffer::setReadOnly(bool on) const
2323 d->wa_->setReadOnly(on);
2327 void Buffer::updateTitles() const
2330 d->wa_->updateTitles();
2334 void Buffer::resetAutosaveTimers() const
2337 gui_->resetAutosaveTimers();
2341 bool Buffer::hasGuiDelegate() const
2347 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2356 class AutoSaveBuffer : public ForkedProcess {
2359 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2360 : buffer_(buffer), fname_(fname) {}
2362 virtual boost::shared_ptr<ForkedProcess> clone() const
2364 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2369 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2370 from_utf8(fname_.absFilename())));
2371 return run(DontWait);
2375 virtual int generateChild();
2377 Buffer const & buffer_;
2382 int AutoSaveBuffer::generateChild()
2384 // tmp_ret will be located (usually) in /tmp
2385 // will that be a problem?
2386 // Note that this calls ForkedCalls::fork(), so it's
2387 // ok cross-platform.
2388 pid_t const pid = fork();
2389 // If you want to debug the autosave
2390 // you should set pid to -1, and comment out the fork.
2391 if (pid != 0 && pid != -1)
2394 // pid = -1 signifies that lyx was unable
2395 // to fork. But we will do the save
2397 bool failed = false;
2398 FileName const tmp_ret = FileName::tempName("lyxauto");
2399 if (!tmp_ret.empty()) {
2400 buffer_.writeFile(tmp_ret);
2401 // assume successful write of tmp_ret
2402 if (!tmp_ret.moveTo(fname_))
2408 // failed to write/rename tmp_ret so try writing direct
2409 if (!buffer_.writeFile(fname_)) {
2410 // It is dangerous to do this in the child,
2411 // but safe in the parent, so...
2412 if (pid == -1) // emit message signal.
2413 buffer_.message(_("Autosave failed!"));
2417 if (pid == 0) // we are the child so...
2426 FileName Buffer::getAutosaveFilename() const
2428 string const fpath = isUnnamed() ? lyxrc.document_path : filePath();
2429 string const fname = "#" + d->filename.onlyFileName() + "#";
2430 return makeAbsPath(fname, fpath);
2434 void Buffer::removeAutosaveFile() const
2436 FileName const f = getAutosaveFilename();
2442 // Perfect target for a thread...
2443 void Buffer::autoSave() const
2445 if (isBakClean() || isReadonly()) {
2446 // We don't save now, but we'll try again later
2447 resetAutosaveTimers();
2451 // emit message signal.
2452 message(_("Autosaving current document..."));
2453 AutoSaveBuffer autosave(*this, getAutosaveFilename());
2457 resetAutosaveTimers();
2461 string Buffer::bufferFormat() const
2467 if (params().encoding().package() == Encoding::japanese)
2473 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2474 string & result_file) const
2476 string backend_format;
2477 OutputParams runparams(¶ms().encoding());
2478 runparams.flavor = OutputParams::LATEX;
2479 runparams.linelen = lyxrc.plaintext_linelen;
2480 vector<string> backs = backends();
2481 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2482 // Get shortest path to format
2483 Graph::EdgePath path;
2484 for (vector<string>::const_iterator it = backs.begin();
2485 it != backs.end(); ++it) {
2486 Graph::EdgePath p = theConverters().getPath(*it, format);
2487 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2488 backend_format = *it;
2493 runparams.flavor = theConverters().getFlavor(path);
2495 Alert::error(_("Couldn't export file"),
2496 bformat(_("No information for exporting the format %1$s."),
2497 formats.prettyName(format)));
2501 backend_format = format;
2502 // FIXME: Don't hardcode format names here, but use a flag
2503 if (backend_format == "pdflatex")
2504 runparams.flavor = OutputParams::PDFLATEX;
2507 string filename = latexName(false);
2508 filename = addName(temppath(), filename);
2509 filename = changeExtension(filename,
2510 formats.extension(backend_format));
2513 updateMacroInstances();
2515 // Plain text backend
2516 if (backend_format == "text")
2517 writePlaintextFile(*this, FileName(filename), runparams);
2519 else if (backend_format == "lyx")
2520 writeFile(FileName(filename));
2522 else if (isDocBook()) {
2523 runparams.nice = !put_in_tempdir;
2524 makeDocBookFile(FileName(filename), runparams);
2527 else if (backend_format == format) {
2528 runparams.nice = true;
2529 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2531 } else if (!lyxrc.tex_allows_spaces
2532 && contains(filePath(), ' ')) {
2533 Alert::error(_("File name error"),
2534 _("The directory path to the document cannot contain spaces."));
2537 runparams.nice = false;
2538 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2542 string const error_type = (format == "program")
2543 ? "Build" : bufferFormat();
2544 ErrorList & error_list = d->errorLists[error_type];
2545 string const ext = formats.extension(format);
2546 FileName const tmp_result_file(changeExtension(filename, ext));
2547 bool const success = theConverters().convert(this, FileName(filename),
2548 tmp_result_file, FileName(absFileName()), backend_format, format,
2550 // Emit the signal to show the error list.
2551 if (format != backend_format)
2556 if (put_in_tempdir) {
2557 result_file = tmp_result_file.absFilename();
2561 result_file = changeExtension(absFileName(), ext);
2562 // We need to copy referenced files (e. g. included graphics
2563 // if format == "dvi") to the result dir.
2564 vector<ExportedFile> const files =
2565 runparams.exportdata->externalFiles(format);
2566 string const dest = onlyPath(result_file);
2567 CopyStatus status = SUCCESS;
2568 for (vector<ExportedFile>::const_iterator it = files.begin();
2569 it != files.end() && status != CANCEL; ++it) {
2570 string const fmt = formats.getFormatFromFile(it->sourceName);
2571 status = copyFile(fmt, it->sourceName,
2572 makeAbsPath(it->exportName, dest),
2573 it->exportName, status == FORCE);
2575 if (status == CANCEL) {
2576 message(_("Document export cancelled."));
2577 } else if (tmp_result_file.exists()) {
2578 // Finally copy the main file
2579 status = copyFile(format, tmp_result_file,
2580 FileName(result_file), result_file,
2582 message(bformat(_("Document exported as %1$s "
2584 formats.prettyName(format),
2585 makeDisplayPath(result_file)));
2587 // This must be a dummy converter like fax (bug 1888)
2588 message(bformat(_("Document exported as %1$s"),
2589 formats.prettyName(format)));
2596 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2599 return doExport(format, put_in_tempdir, result_file);
2603 bool Buffer::preview(string const & format) const
2606 if (!doExport(format, true, result_file))
2608 return formats.view(*this, FileName(result_file), format);
2612 bool Buffer::isExportable(string const & format) const
2614 vector<string> backs = backends();
2615 for (vector<string>::const_iterator it = backs.begin();
2616 it != backs.end(); ++it)
2617 if (theConverters().isReachable(*it, format))
2623 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2625 vector<string> backs = backends();
2626 vector<Format const *> result =
2627 theConverters().getReachable(backs[0], only_viewable, true);
2628 for (vector<string>::const_iterator it = backs.begin() + 1;
2629 it != backs.end(); ++it) {
2630 vector<Format const *> r =
2631 theConverters().getReachable(*it, only_viewable, false);
2632 result.insert(result.end(), r.begin(), r.end());
2638 vector<string> Buffer::backends() const
2641 if (params().baseClass()->isTeXClassAvailable()) {
2642 v.push_back(bufferFormat());
2643 // FIXME: Don't hardcode format names here, but use a flag
2644 if (v.back() == "latex")
2645 v.push_back("pdflatex");
2647 v.push_back("text");
2653 bool Buffer::readFileHelper(FileName const & s)
2655 // File information about normal file
2657 docstring const file = makeDisplayPath(s.absFilename(), 50);
2658 docstring text = bformat(_("The specified document\n%1$s"
2659 "\ncould not be read."), file);
2660 Alert::error(_("Could not read document"), text);
2664 // Check if emergency save file exists and is newer.
2665 FileName const e(s.absFilename() + ".emergency");
2667 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2668 docstring const file = makeDisplayPath(s.absFilename(), 20);
2669 docstring const text =
2670 bformat(_("An emergency save of the document "
2672 "Recover emergency save?"), file);
2673 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2674 _("&Recover"), _("&Load Original"),
2678 // the file is not saved if we load the emergency file.
2688 // Now check if autosave file is newer.
2689 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2691 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2692 docstring const file = makeDisplayPath(s.absFilename(), 20);
2693 docstring const text =
2694 bformat(_("The backup of the document "
2695 "%1$s is newer.\n\nLoad the "
2696 "backup instead?"), file);
2697 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2698 _("&Load backup"), _("Load &original"),
2702 // the file is not saved if we load the autosave file.
2706 // Here we delete the autosave
2717 bool Buffer::loadLyXFile(FileName const & s)
2719 if (s.isReadableFile()) {
2720 if (readFileHelper(s)) {
2721 lyxvc().file_found_hook(s);
2722 if (!s.isWritable())
2727 docstring const file = makeDisplayPath(s.absFilename(), 20);
2728 // Here we probably should run
2729 if (LyXVC::file_not_found_hook(s)) {
2730 docstring const text =
2731 bformat(_("Do you want to retrieve the document"
2732 " %1$s from version control?"), file);
2733 int const ret = Alert::prompt(_("Retrieve from version control?"),
2734 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2737 // How can we know _how_ to do the checkout?
2738 // With the current VC support it has to be,
2739 // a RCS file since CVS do not have special ,v files.
2741 return loadLyXFile(s);
2749 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2751 TeXErrors::Errors::const_iterator cit = terr.begin();
2752 TeXErrors::Errors::const_iterator end = terr.end();
2754 for (; cit != end; ++cit) {
2757 int errorRow = cit->error_in_line;
2758 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2764 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2765 } while (found && id_start == id_end && pos_start == pos_end);
2767 errorList.push_back(ErrorItem(cit->error_desc,
2768 cit->error_text, id_start, pos_start, pos_end));
2773 void Buffer::setBuffersForInsets() const
2775 inset().setBuffer(const_cast<Buffer &>(*this));
2779 void Buffer::updateLabels(UpdateScope scope) const
2781 // Use the master text class also for child documents
2782 Buffer const * const master = masterBuffer();
2783 DocumentClass const & textclass = master->params().documentClass();
2785 // keep the buffers to be children in this set. If the call from the
2786 // master comes back we can see which of them were actually seen (i.e.
2787 // via an InsetInclude). The remaining ones in the set need still be updated.
2788 static std::set<Buffer const *> bufToUpdate;
2789 if (scope == UpdateMaster) {
2790 // If this is a child document start with the master
2791 if (master != this) {
2792 bufToUpdate.insert(this);
2793 master->updateLabels();
2794 // Do this here in case the master has no gui associated with it. Then,
2795 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
2799 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
2800 if (bufToUpdate.find(this) == bufToUpdate.end())
2804 // start over the counters in the master
2805 textclass.counters().reset();
2808 // update will be done below for this buffer
2809 bufToUpdate.erase(this);
2811 // update all caches
2812 clearReferenceCache();
2815 Buffer & cbuf = const_cast<Buffer &>(*this);
2817 LASSERT(!text().paragraphs().empty(), /**/);
2820 ParIterator parit = cbuf.par_iterator_begin();
2821 updateLabels(parit);
2824 // TocBackend update will be done later.
2827 cbuf.tocBackend().update();
2828 if (scope == UpdateMaster)
2829 cbuf.structureChanged();
2833 static depth_type getDepth(DocIterator const & it)
2835 depth_type depth = 0;
2836 for (size_t i = 0 ; i < it.depth() ; ++i)
2837 if (!it[i].inset().inMathed())
2838 depth += it[i].paragraph().getDepth() + 1;
2839 // remove 1 since the outer inset does not count
2843 static depth_type getItemDepth(ParIterator const & it)
2845 Paragraph const & par = *it;
2846 LabelType const labeltype = par.layout().labeltype;
2848 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
2851 // this will hold the lowest depth encountered up to now.
2852 depth_type min_depth = getDepth(it);
2853 ParIterator prev_it = it;
2856 --prev_it.top().pit();
2858 // start of nested inset: go to outer par
2860 if (prev_it.empty()) {
2861 // start of document: nothing to do
2866 // We search for the first paragraph with same label
2867 // that is not more deeply nested.
2868 Paragraph & prev_par = *prev_it;
2869 depth_type const prev_depth = getDepth(prev_it);
2870 if (labeltype == prev_par.layout().labeltype) {
2871 if (prev_depth < min_depth)
2872 return prev_par.itemdepth + 1;
2873 if (prev_depth == min_depth)
2874 return prev_par.itemdepth;
2876 min_depth = min(min_depth, prev_depth);
2877 // small optimization: if we are at depth 0, we won't
2878 // find anything else
2879 if (prev_depth == 0)
2885 static bool needEnumCounterReset(ParIterator const & it)
2887 Paragraph const & par = *it;
2888 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
2889 depth_type const cur_depth = par.getDepth();
2890 ParIterator prev_it = it;
2891 while (prev_it.pit()) {
2892 --prev_it.top().pit();
2893 Paragraph const & prev_par = *prev_it;
2894 if (prev_par.getDepth() <= cur_depth)
2895 return prev_par.layout().labeltype != LABEL_ENUMERATE;
2897 // start of nested inset: reset
2902 // set the label of a paragraph. This includes the counters.
2903 static void setLabel(Buffer const & buf, ParIterator & it)
2905 BufferParams const & bp = buf.masterBuffer()->params();
2906 DocumentClass const & textclass = bp.documentClass();
2907 Paragraph & par = it.paragraph();
2908 Layout const & layout = par.layout();
2909 Counters & counters = textclass.counters();
2911 if (par.params().startOfAppendix()) {
2912 // FIXME: only the counter corresponding to toplevel
2913 // sectionning should be reset
2915 counters.appendix(true);
2917 par.params().appendix(counters.appendix());
2919 // Compute the item depth of the paragraph
2920 par.itemdepth = getItemDepth(it);
2922 if (layout.margintype == MARGIN_MANUAL) {
2923 if (par.params().labelWidthString().empty())
2924 par.params().labelWidthString(par.translateIfPossible(layout.labelstring(), bp));
2926 par.params().labelWidthString(docstring());
2929 switch(layout.labeltype) {
2931 if (layout.toclevel <= bp.secnumdepth
2932 && (layout.latextype != LATEX_ENVIRONMENT
2933 || isFirstInSequence(it.pit(), it.plist()))) {
2934 counters.step(layout.counter);
2935 par.params().labelString(
2936 par.expandLabel(layout, bp));
2938 par.params().labelString(docstring());
2941 case LABEL_ITEMIZE: {
2942 // At some point of time we should do something more
2943 // clever here, like:
2944 // par.params().labelString(
2945 // bp.user_defined_bullet(par.itemdepth).getText());
2946 // for now, use a simple hardcoded label
2947 docstring itemlabel;
2948 switch (par.itemdepth) {
2950 itemlabel = char_type(0x2022);
2953 itemlabel = char_type(0x2013);
2956 itemlabel = char_type(0x2217);
2959 itemlabel = char_type(0x2219); // or 0x00b7
2962 par.params().labelString(itemlabel);
2966 case LABEL_ENUMERATE: {
2967 // FIXME: Yes I know this is a really, really! bad solution
2969 docstring enumcounter = from_ascii("enum");
2971 switch (par.itemdepth) {
2980 enumcounter += "iv";
2983 // not a valid enumdepth...
2987 // Maybe we have to reset the enumeration counter.
2988 if (needEnumCounterReset(it))
2989 counters.reset(enumcounter);
2991 counters.step(enumcounter);
2995 switch (par.itemdepth) {
2997 format = N_("\\arabic{enumi}.");
3000 format = N_("(\\alph{enumii})");
3003 format = N_("\\roman{enumiii}.");
3006 format = N_("\\Alph{enumiv}.");
3009 // not a valid enumdepth...
3013 par.params().labelString(counters.counterLabel(
3014 par.translateIfPossible(from_ascii(format), bp)));
3019 case LABEL_SENSITIVE: {
3020 string const & type = counters.current_float();
3021 docstring full_label;
3023 full_label = buf.B_("Senseless!!! ");
3025 docstring name = buf.B_(textclass.floats().getType(type).name());
3026 if (counters.hasCounter(from_utf8(type))) {
3027 counters.step(from_utf8(type));
3028 full_label = bformat(from_ascii("%1$s %2$s:"),
3030 counters.theCounter(from_utf8(type)));
3032 full_label = bformat(from_ascii("%1$s #:"), name);
3034 par.params().labelString(full_label);
3038 case LABEL_NO_LABEL:
3039 par.params().labelString(docstring());
3043 case LABEL_TOP_ENVIRONMENT:
3044 case LABEL_CENTERED_TOP_ENVIRONMENT:
3047 par.params().labelString(
3048 par.translateIfPossible(layout.labelstring(), bp));
3054 void Buffer::updateLabels(ParIterator & parit) const
3056 LASSERT(parit.pit() == 0, /**/);
3058 // set the position of the text in the buffer to be able
3059 // to resolve macros in it. This has nothing to do with
3060 // labels, but by putting it here we avoid implementing
3061 // a whole bunch of traversal routines just for this call.
3062 parit.text()->setMacrocontextPosition(parit);
3064 depth_type maxdepth = 0;
3065 pit_type const lastpit = parit.lastpit();
3066 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3067 // reduce depth if necessary
3068 parit->params().depth(min(parit->params().depth(), maxdepth));
3069 maxdepth = parit->getMaxDepthAfter();
3071 // set the counter for this paragraph
3072 setLabel(*this, parit);
3075 InsetList::const_iterator iit = parit->insetList().begin();
3076 InsetList::const_iterator end = parit->insetList().end();
3077 for (; iit != end; ++iit) {
3078 parit.pos() = iit->pos;
3079 iit->inset->updateLabels(parit);
3085 bool Buffer::nextWord(DocIterator & from, DocIterator & to,
3086 docstring & word) const
3088 bool inword = false;
3089 bool ignoreword = false;
3093 while (to.depth()) {
3100 lang_code = to.paragraph().getFontSettings(params(),
3101 to.pos()).language()->code();
3103 // Insets like optional hyphens and ligature
3104 // break are part of a word.
3105 if (!to.paragraph().isInset(to.pos())) {
3106 char_type const c = to.paragraph().getChar(to.pos());
3111 } else { // !isLetter(cur)
3112 if (inword && !word.empty() && !ignoreword)