4 * This file is part of LyX, the document processor.
5 * Licence details can be found in the file COPYING.
7 * \author Lars Gullik Bjønnes
9 * Full author contact details are available in file CREDITS.
15 #include "OutputEnums.h"
17 #include "insets/InsetCode.h"
19 #include "support/strfwd.h"
20 #include "support/types.h"
53 class ParConstIterator;
63 class GuiBufferDelegate;
64 class WorkAreaManager;
74 typedef std::list<Buffer *> ListOfBuffers;
77 /** The buffer object.
78 * This is the buffer object. It contains all the informations about
79 * a document loaded into LyX.
80 * The buffer object owns the Text (wrapped in an InsetText), which
81 * contains the individual paragraphs of the document.
84 * I am not sure if the class is complete or
85 * minimal, probably not.
86 * \author Lars Gullik Bjønnes
90 /// What type of log will \c getLogName() return?
92 latexlog, ///< LaTeX log
93 buildlog ///< Literate build log
96 /// Result of \c readFile()
106 ReadEmergencyFailure,
119 /// Method to check if a file is externally modified, used by
120 /// isExternallyModified()
122 * timestamp is fast but inaccurate. For example, the granularity
123 * of timestamp on a FAT filesystem is 2 second. Also, various operations
124 * may touch the timestamp of a file even when its content is unchanged.
126 * checksum is accurate but slow, which can be a problem when it is
127 * frequently used, or used for a large file on a slow (network) file
130 * FIXME: replace this method with support/FileMonitor.
133 checksum_method, ///< Use file checksum
134 timestamp_method, ///< Use timestamp, and checksum if timestamp has changed
144 explicit Buffer(std::string const & file, bool readonly = false,
145 Buffer const * cloned_buffer = 0);
151 Buffer * clone() const;
153 bool isClone() const;
155 /** High-level interface to buffer functionality.
156 This function parses a command string and executes it.
158 void dispatch(std::string const & command, DispatchResult & result);
160 /// Maybe we know the function already by number...
161 void dispatch(FuncRequest const & func, DispatchResult & result);
163 /// Can this function be exectued?
164 /// \return true if we made a decision
165 bool getStatus(FuncRequest const & cmd, FuncStatus & flag);
167 /// read a new document from a string
168 bool readString(std::string const &);
170 /// Reads the first tag of a LyX File and
171 /// returns the file format number.
172 ReadStatus parseLyXFormat(Lexer & lex,
173 support::FileName const & fn, int & file_format) const;
174 /// read the header, returns number of unknown tokens
175 int readHeader(Lexer & lex);
176 /** Reads a file without header.
177 \param par if != 0 insert the file.
178 \return \c true if file is not completely read.
180 bool readDocument(Lexer &);
181 /// Convert the LyX file to the LYX_FORMAT using
182 /// the lyx2lyx script and returns the filename
183 /// of the temporary file to be read
184 ReadStatus convertLyXFormat(support::FileName const & fn,
185 support::FileName & tmpfile, int from_format);
188 DocIterator getParFromID(int id) const;
189 /// do we have a paragraph with this id?
190 bool hasParWithID(int id) const;
193 frontend::WorkAreaManager & workAreaManager() const;
196 Takes care of auto-save files and backup file if requested.
197 Returns \c true if the save is successful, \c false otherwise.
201 /// Write document to stream. Returns \c false if unsuccesful.
202 bool write(std::ostream &) const;
203 /// save emergency file
204 /// \return a status message towards the user.
205 docstring emergencyWrite();
206 /// Write file. Returns \c false if unsuccesful.
207 bool writeFile(support::FileName const &) const;
209 /// Loads a LyX file \c fn into the buffer. This function
210 /// tries to extract the file from version control if it
211 /// cannot be found. If it can be found, it will try to
212 /// read an emergency save file or an autosave file.
213 ReadStatus loadLyXFile(support::FileName const & fn);
215 ReadStatus readFile(support::FileName const & fn);
216 /// Try to extract the file from a version control container
217 /// before reading if the file cannot be found. This is only
218 /// implemented for RCS.
219 /// \sa LyXVC::file_not_found_hook
220 ReadStatus readFromVC(support::FileName const & fn);
221 /// Try to read an emergency file associated to \c fn.
222 ReadStatus readEmergency(support::FileName const & fn);
223 /// Try to read an autosave file associated to \c fn.
224 ReadStatus readAutosave(support::FileName const & fn);
226 /// Reloads the LyX file
229 /// Fill in the ErrorList with the TeXErrors
230 void bufferErrors(TeXErrors const &, ErrorList &) const;
232 /// Just a wrapper for writeLaTeXSource, first creating the ofstream.
233 bool makeLaTeXFile(support::FileName const & filename,
234 std::string const & original_path,
235 OutputParams const &,
236 bool output_preamble = true,
237 bool output_body = true) const;
238 /** Export the buffer to LaTeX.
239 If \p os is a file stream, and params().inputenc is "auto" or
240 "default", and the buffer contains text in different languages
241 with more than one encoding, then this method will change the
242 encoding associated to \p os. Therefore you must not call this
243 method with a string stream if the output is supposed to go to a
246 ofs.open("test.tex");
247 writeLaTeXSource(ofs, ...);
249 \endcode is NOT equivalent to \code
250 odocstringstream oss;
251 writeLaTeXSource(oss, ...);
253 ofs.open("test.tex");
258 void writeLaTeXSource(odocstream & os,
259 std::string const & original_path,
260 OutputParams const &,
261 bool output_preamble = true,
262 bool output_body = true) const;
264 void makeDocBookFile(support::FileName const & filename,
265 OutputParams const & runparams_in,
266 bool only_body = false) const;
268 void writeDocBookSource(odocstream & os, std::string const & filename,
269 OutputParams const & runparams_in,
270 bool only_body = false) const;
272 void makeLyXHTMLFile(support::FileName const & filename,
273 OutputParams const & runparams_in,
274 bool only_body = false) const;
276 void writeLyXHTMLSource(odocstream & os,
277 OutputParams const & runparams_in,
278 bool only_body = false) const;
279 /// returns the main language for the buffer (document)
280 Language const * language() const;
281 /// get l10n translated to the buffers language
282 docstring const B_(std::string const & l10n) const;
286 /// return true if the main lyx file does not need saving
287 bool isClean() const;
289 bool isDepClean(std::string const & name) const;
291 /// whether or not disk file has been externally modified
292 bool isExternallyModified(CheckMethod method) const;
294 /// save timestamp and checksum of the given file.
295 void saveCheckSum(support::FileName const & file) const;
297 /// mark the main lyx file as not needing saving
298 void markClean() const;
301 void markDepClean(std::string const & name);
304 void setUnnamed(bool flag = true);
306 /// Whether or not a filename has been assigned to this buffer
307 bool isUnnamed() const;
309 /// Whether or not this buffer is internal.
311 /// An internal buffer does not contain a real document, but some auxiliary text segment.
312 /// It is not associated with a filename, it is never saved, thus it does not need to be
313 /// automatically saved, nor it needs to trigger any "do you want to save ?" question.
314 bool isInternal() const;
316 /// Mark this buffer as dirty.
319 /// Returns the buffer's filename. It is always an absolute path.
320 support::FileName fileName() const;
322 /// Returns the buffer's filename. It is always an absolute path.
323 std::string absFileName() const;
325 /// Returns the the path where the buffer lives.
326 /// It is always an absolute path.
327 std::string filePath() const;
329 /** A transformed version of the file name, adequate for LaTeX.
330 \param no_path optional if \c true then the path is stripped.
332 std::string latexName(bool no_path = true) const;
334 /// Get the name and type of the log.
335 std::string logName(LogType * type = 0) const;
337 /// Change name of buffer. Updates "read-only" flag.
338 void setFileName(std::string const & newfile);
340 /// Set document's parent Buffer.
341 void setParent(Buffer const *);
342 Buffer const * parent() const;
344 /** Get the document's master (or \c this if this is not a
347 Buffer const * masterBuffer() const;
349 /// \return true if \p child is a child of this \c Buffer.
350 bool isChild(Buffer * child) const;
352 /// \return true if this \c Buffer has children
353 bool hasChildren() const;
355 /// \return a list of the direct children of this Buffer.
356 /// this list has no duplicates and is in the order in which
357 /// the children appear.
358 ListOfBuffers getChildren() const;
360 /// \return a list of all descendents of this Buffer (children,
361 /// grandchildren, etc). this list has no duplicates and is in
362 /// the order in which the children appear.
363 ListOfBuffers getDescendents() const;
365 /// Collect all relative buffers, in the order in which they appear.
366 /// I.e., the "root" Buffer is first, then its first child, then any
367 /// of its children, etc. However, there are no duplicates in this
369 /// This is "stable", too, in the sense that it returns the same
370 /// thing from whichever Buffer it is called.
371 ListOfBuffers allRelatives() const;
373 /// Is buffer read-only?
374 bool isReadonly() const;
376 /// Set buffer read-only flag
377 void setReadonly(bool flag = true);
379 /// returns \c true if the buffer contains a LaTeX document
380 bool isLatex() const;
381 /// returns \c true if the buffer contains a DocBook document
382 bool isDocBook() const;
383 /// returns \c true if the buffer contains a Wed document
384 bool isLiterate() const;
386 /** Validate a buffer for LaTeX.
387 This validates the buffer, and returns a struct for use by
388 #makeLaTeX# and others. Its main use is to figure out what
389 commands and packages need to be included in the LaTeX file.
390 It (should) also check that the needed constructs are there
391 (i.e. that the \refs points to coresponding \labels). It
392 should perhaps inset "error" insets to help the user correct
395 void validate(LaTeXFeatures &) const;
397 /// Reference information is cached in the Buffer, so we do not
398 /// have to check or read things over and over.
400 /// There are two caches.
402 /// One is a cache of the BibTeX files from which reference info is
403 /// being gathered. This cache is PER BUFFER, and the cache for the
404 /// master essentially includes the cache for its children. This gets
405 /// invalidated when an InsetBibtex is created, deleted, or modified.
407 /// The other is a cache of the reference information itself. This
408 /// exists only in the master buffer, and when it needs to be updated,
409 /// the children add their information to the master's cache.
411 /// Calling this method invalidates the cache and so requires a
413 void invalidateBibinfoCache() const;
414 /// This invalidates the cache of files we need to check.
415 void invalidateBibfileCache() const;
416 /// Updates the cached bibliography information.
417 /// Note that you MUST call this method to update the cache. It will
418 /// not happen otherwise. (Currently, it is called at the start of
419 /// updateBuffer() and from GuiCitation.)
420 /// Note that this operates on the master document.
421 void checkBibInfoCache() const;
422 /// \return the bibliography information for this buffer's master,
423 /// or just for it, if it isn't a child.
424 BiblioInfo const & masterBibInfo() const;
426 void fillWithBibKeys(BiblioInfo & keys) const;
428 void getLabelList(std::vector<docstring> &) const;
431 void changeLanguage(Language const * from, Language const * to);
434 bool isMultiLingual() const;
436 std::set<Language const *> getLanguages() const;
439 BufferParams & params();
440 BufferParams const & params() const;
442 /** The list of paragraphs.
443 This is a linked list of paragraph, this list holds the
444 whole contents of the document.
446 ParagraphList & paragraphs();
447 ParagraphList const & paragraphs() const;
449 /// LyX version control object.
451 LyXVC const & lyxvc() const;
453 /// Where to put temporary files.
454 std::string const temppath() const;
456 /// Used when typesetting to place errorboxes.
457 TexRow const & texrow() const;
461 ParIterator par_iterator_begin();
463 ParConstIterator par_iterator_begin() const;
465 ParIterator par_iterator_end();
467 ParConstIterator par_iterator_end() const;
469 // Position of the child buffer where it appears first in the master.
470 DocIterator firstChildPosition(Buffer const * child);
472 /** \returns true only when the file is fully loaded.
473 * Used to prevent the premature generation of previews
474 * and by the citation inset.
476 bool isFullyLoaded() const;
477 /// Set by buffer_funcs' newFile.
478 void setFullyLoaded(bool);
480 /// Our main text (inside the top InsetText)
483 /// Our top InsetText
484 Inset & inset() const;
489 /// Collect macro definitions in paragraphs
490 void updateMacros() const;
491 /// Iterate through the whole buffer and try to resolve macros
492 void updateMacroInstances() const;
494 /// List macro names of this buffer, the parent and the children
495 void listMacroNames(MacroNameSet & macros) const;
496 /// Collect macros of the parent and its children in front of this buffer.
497 void listParentMacros(MacroSet & macros, LaTeXFeatures & features) const;
499 /// Return macro defined before pos (or in the master buffer)
500 MacroData const * getMacro(docstring const & name, DocIterator const & pos, bool global = true) const;
501 /// Return macro defined anywhere in the buffer (or in the master buffer)
502 MacroData const * getMacro(docstring const & name, bool global = true) const;
503 /// Return macro defined before the inclusion of the child
504 MacroData const * getMacro(docstring const & name, Buffer const & child, bool global = true) const;
506 /// Collect user macro names at loading time
507 typedef std::set<docstring> UserMacroSet;
508 UserMacroSet usermacros;
510 /// Replace the inset contents for insets which InsetCode is equal
511 /// to the passed \p inset_code.
512 void changeRefsIfUnique(docstring const & from, docstring const & to,
515 /// get source code (latex/docbook) for some paragraphs, or all paragraphs
516 /// including preamble
517 void getSourceCode(odocstream & os, pit_type par_begin, pit_type par_end,
518 bool full_source) const;
520 /// Access to error list.
521 /// This method is used only for GUI visualisation of Buffer related
522 /// errors (like parsing or LateX compilation). This method is const
523 /// because modifying the returned ErrorList does not touch the document
525 ErrorList & errorList(std::string const & type) const;
528 /// This is useful only for screen visualisation of the Buffer. This
529 /// method is const because modifying this backend does not touch
530 /// the document contents.
531 TocBackend & tocBackend() const;
536 /// This function is called when the buffer is changed.
537 void changed(bool update_metrics) const;
539 void setChild(DocIterator const & dit, Buffer * child);
541 void updateTocItem(std::string const &, DocIterator const &) const;
542 /// This function is called when the buffer structure is changed.
543 void structureChanged() const;
544 /// This function is called when some parsing error shows up.
545 void errors(std::string const & err, bool from_master = false) const;
546 /// This function is called when the buffer busy status change.
547 void setBusy(bool on) const;
548 /// Update window titles of all users.
549 void updateTitles() const;
550 /// Reset autosave timers for all users.
551 void resetAutosaveTimers() const;
553 void message(docstring const & msg) const;
556 void setGuiDelegate(frontend::GuiBufferDelegate * gui);
558 bool hasGuiDelegate() const;
561 void autoSave() const;
563 void removeAutosaveFile() const;
565 void moveAutosaveFile(support::FileName const & old) const;
566 /// Get the filename of the autosave file associated with the Buffer
567 support::FileName getAutosaveFileName() const;
568 /// Get the filename of the autosave file associated with \c fn
569 support::FileName getAutosaveFileNameFor(support::FileName const & fn)
571 /// Get the filename of the emergency file associated with the Buffer
572 support::FileName getEmergencyFileName() const;
573 /// Get the filename of the emergency file associated with \c fn
574 support::FileName getEmergencyFileNameFor(support::FileName const & fn)
577 /// return the format of the buffer on a string
578 std::string bufferFormat() const;
579 /// return the default output format of the current backend
580 std::string getDefaultOutputFormat() const;
583 bool doExport(std::string const & format, bool put_in_tempdir,
584 bool includeall, std::string & result_file) const;
586 bool doExport(std::string const & format, bool put_in_tempdir,
587 bool includeall = false) const;
589 bool preview(std::string const & format, bool includeall = false) const;
591 bool isExportable(std::string const & format) const;
593 std::vector<Format const *> exportableFormats(bool only_viewable) const;
595 bool isExportableFormat(std::string const & format) const;
596 /// mark the buffer as busy exporting something, or not
597 void setExportStatus(bool e) const;
599 bool isExporting() const;
602 typedef std::vector<std::pair<Inset *, ParIterator> > References;
603 References & references(docstring const & label);
604 References const & references(docstring const & label) const;
605 void clearReferenceCache() const;
606 void setInsetLabel(docstring const & label, InsetLabel const * il);
607 InsetLabel const * insetLabel(docstring const & label) const;
609 /// return a list of all used branches (also in children)
610 void getUsedBranches(std::list<docstring> &, bool const from_master = false) const;
612 /// sets the buffer_ member for every inset in this buffer.
613 // FIXME This really shouldn't be needed, but at the moment it's not
614 // clear how to do it just for the individual pieces we need.
615 void setBuffersForInsets() const;
616 /// Updates screen labels and some other information associated with
617 /// insets and paragraphs. Actually, it's more like a general "recurse
618 /// through the Buffer" routine, that visits all the insets and paragraphs.
619 void updateBuffer() const { updateBuffer(UpdateMaster, InternalUpdate); }
620 /// \param scope: whether to start with the master document or just
622 /// \param output: whether we are preparing for output.
623 void updateBuffer(UpdateScope scope, UpdateType utype) const;
625 void updateBuffer(ParIterator & parit, UpdateType utype) const;
627 /// Spellcheck starting from \p from.
628 /// \p from initial position, will then points to the next misspelled
630 /// \p to will points to the end of the next misspelled word.
631 /// \p word_lang will contain the found misspelled word.
632 /// \return progress if a new word was found.
633 int spellCheck(DocIterator & from, DocIterator & to,
634 WordLangTuple & word_lang, docstring_list & suggestions) const;
636 void checkChildBuffers();
640 std::vector<std::string> backends() const;
642 void getLanguages(std::set<Language const *> &) const;
643 /// Update the list of all bibfiles in use (including bibfiles
644 /// of loaded child documents).
645 void updateBibfilesCache(UpdateScope scope = UpdateMaster) const;
646 /// Return the list with all bibfiles in use (including bibfiles
647 /// of loaded child documents).
648 support::FileNameList const &
649 getBibfilesCache(UpdateScope scope = UpdateMaster) const;
651 void collectChildren(ListOfBuffers & children, bool grand_children) const;
654 /// Use the Pimpl idiom to hide the internals.
656 /// The pointer never changes although *pimpl_'s contents may.