]> git.lyx.org Git - lyx.git/blob - src/Buffer.h
* ANNOUNCE
[lyx.git] / src / Buffer.h
1 // -*- C++ -*-
2 /**
3  * \file Buffer.h
4  * This file is part of LyX, the document processor.
5  * Licence details can be found in the file COPYING.
6  *
7  * \author Lars Gullik Bjønnes
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #ifndef BUFFER_H
13 #define BUFFER_H
14
15 #include "OutputEnums.h"
16
17 #include "insets/InsetCode.h"
18
19 #include "support/strfwd.h"
20 #include "support/types.h"
21
22 #include <list>
23 #include <set>
24 #include <string>
25 #include <vector>
26
27
28 namespace lyx {
29
30 class BiblioInfo;
31 class BufferParams;
32 class DispatchResult;
33 class DocIterator;
34 class docstring_list;
35 class ErrorList;
36 class FuncRequest;
37 class FuncStatus;
38 class Inset;
39 class InsetLabel;
40 class InsetRef;
41 class Font;
42 class Format;
43 class Lexer;
44 class Text;
45 class LyXVC;
46 class LaTeXFeatures;
47 class Language;
48 class MacroData;
49 class MacroNameSet;
50 class MacroSet;
51 class OutputParams;
52 class Paragraph;
53 class ParConstIterator;
54 class ParIterator;
55 class ParagraphList;
56 class TeXErrors;
57 class TexRow;
58 class TocBackend;
59 class Undo;
60 class WordLangTuple;
61
62 namespace frontend {
63 class GuiBufferDelegate;
64 class WorkAreaManager;
65 }
66
67 namespace support {
68 class FileName;
69 class FileNameList;
70 }
71
72
73 class Buffer;
74 typedef std::list<Buffer *> ListOfBuffers;
75
76
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.
82  *
83  *
84  * I am not sure if the class is complete or
85  * minimal, probably not.
86  * \author Lars Gullik Bjønnes
87  */
88 class Buffer {
89 public:
90         /// What type of log will \c getLogName() return?
91         enum LogType {
92                 latexlog, ///< LaTeX log
93                 buildlog  ///< Literate build log
94         };
95
96         /// Result of \c readFile()
97         enum ReadStatus {
98                 ReadSuccess,
99                 ReadCancel,
100                 // failures
101                 ReadFailure,
102                 ReadWrongVersion,
103                 ReadFileNotFound,
104                 ReadVCError,
105                 ReadAutosaveFailure,            
106                 ReadEmergencyFailure,
107                 ReadNoLyXFormat,
108                 ReadDocumentFailure,
109                 // lyx2lyx
110                 LyX2LyXNoTempFile,
111                 LyX2LyXNotFound,
112                 LyX2LyXOlderFormat,
113                 LyX2LyXNewerFormat,
114                 // other
115                 ReadOriginal
116         };
117
118
119         /// Method to check if a file is externally modified, used by
120         /// isExternallyModified()
121         /**
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.
125          *
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
128          * system.
129          *
130          * FIXME: replace this method with support/FileMonitor.
131          */
132         enum CheckMethod {
133                 checksum_method,  ///< Use file checksum
134                 timestamp_method, ///< Use timestamp, and checksum if timestamp has changed
135         };
136
137         ///
138         enum UpdateScope {
139                 UpdateMaster,
140                 UpdateChildOnly
141         };
142
143         /// Constructor
144         explicit Buffer(std::string const & file, bool readonly = false,
145                 Buffer const * cloned_buffer = 0);
146
147         /// Destructor
148         ~Buffer();
149
150         ///
151         Buffer * clone() const;
152         ///
153         bool isClone() const;
154
155         /** High-level interface to buffer functionality.
156             This function parses a command string and executes it.
157         */
158         void dispatch(std::string const & command, DispatchResult & result);
159
160         /// Maybe we know the function already by number...
161         void dispatch(FuncRequest const & func, DispatchResult & result);
162
163         /// Can this function be exectued?
164         /// \return true if we made a decision
165         bool getStatus(FuncRequest const & cmd, FuncStatus & flag);
166
167         ///
168         DocIterator getParFromID(int id) const;
169         /// do we have a paragraph with this id?
170         bool hasParWithID(int id) const;
171
172         ///
173         frontend::WorkAreaManager & workAreaManager() const;
174
175         /** Save file.
176             Takes care of auto-save files and backup file if requested.
177             Returns \c true if the save is successful, \c false otherwise.
178         */
179         bool save() const;
180
181         /// Write document to stream. Returns \c false if unsuccesful.
182         bool write(std::ostream &) const;
183         /// Write file. Returns \c false if unsuccesful.
184         bool writeFile(support::FileName const &) const;
185
186         /// \name Functions involved in reading files/strings.
187         //@{
188         /// Loads a LyX file \c fn into the buffer. This function
189         /// tries to extract the file from version control if it
190         /// cannot be found. If it can be found, it will try to
191         /// read an emergency save file or an autosave file.
192         /// \sa loadThisLyXFile
193         ReadStatus loadLyXFile(support::FileName const & fn);
194         /// Loads a LyX file \c fn into the buffer. If you want
195         /// to check for files in a version control container,
196         /// emergency or autosave files, one should use \c loadLyXFile.
197         /// /sa loadLyXFile
198         ReadStatus loadThisLyXFile(support::FileName const & fn);
199         /// read a new document from a string
200         bool readString(std::string const &);
201         /// Reloads the LyX file
202         ReadStatus reload();
203 //FIXME: The following two functions should be private
204 //private:
205         /// read the header, returns number of unknown tokens
206         int readHeader(Lexer & lex);
207         /// save timestamp and checksum of the given file.
208         void saveCheckSum() const;
209
210 private:
211         /// read a new file
212         ReadStatus readFile(support::FileName const & fn);
213         /// Reads a file without header.
214         /// \param par if != 0 insert the file.
215         /// \return \c true if file is not completely read.
216         bool readDocument(Lexer &);
217         /// Try to extract the file from a version control container
218         /// before reading if the file cannot be found. This is only
219         /// implemented for RCS.
220         /// \sa LyXVC::file_not_found_hook
221         ReadStatus extractFromVC(support::FileName const & fn);
222         /// Reads the first tag of a LyX File and 
223         /// returns the file format number.
224         ReadStatus parseLyXFormat(Lexer & lex, support::FileName const & fn,
225                 int & file_format) const;
226         /// Convert the LyX file to the LYX_FORMAT using
227         /// the lyx2lyx script and returns the filename
228         /// of the temporary file to be read
229         ReadStatus convertLyXFormat(support::FileName const & fn, 
230                 support::FileName & tmpfile, int from_format);
231         //@}
232
233 public:
234         /// \name Functions involved in autosave and emergency files.
235         //@{
236         ///
237         void autoSave() const;
238         /// save emergency file
239         /// \return a status message towards the user.
240         docstring emergencyWrite();
241
242 //FIXME:The following three functions should be private
243 //private:
244         ///
245         void removeAutosaveFile() const;
246         ///
247         void moveAutosaveFile(support::FileName const & old) const;
248         /// Get the filename of the autosave file associated with the Buffer
249         support::FileName getAutosaveFileName() const;
250         
251 private:
252         /// Try to load an autosave file associated to \c fn.
253         ReadStatus loadAutosave(support::FileName const & fn);
254         /// Get the filename of the autosave file associated with \c fn
255         support::FileName getAutosaveFileNameFor(support::FileName const & fn)
256                 const;
257
258         /// Try to load an emergency file associated to \c fn. 
259         ReadStatus loadEmergency(support::FileName const & fn);
260         /// Get the filename of the emergency file associated with the Buffer
261         support::FileName getEmergencyFileName() const;
262         /// Get the filename of the emergency file associated with \c fn
263         support::FileName getEmergencyFileNameFor(support::FileName const & fn)
264                 const;
265         //@}
266
267 public:
268         /// Fill in the ErrorList with the TeXErrors
269         void bufferErrors(TeXErrors const &, ErrorList &) const;
270
271         /// Just a wrapper for writeLaTeXSource, first creating the ofstream.
272         bool makeLaTeXFile(support::FileName const & filename,
273                            std::string const & original_path,
274                            OutputParams const &,
275                            bool output_preamble = true,
276                            bool output_body = true) const;
277         /** Export the buffer to LaTeX.
278             If \p os is a file stream, and params().inputenc is "auto" or
279             "default", and the buffer contains text in different languages
280             with more than one encoding, then this method will change the
281             encoding associated to \p os. Therefore you must not call this
282             method with a string stream if the output is supposed to go to a
283             file. \code
284             ofdocstream ofs;
285             ofs.open("test.tex");
286             writeLaTeXSource(ofs, ...);
287             ofs.close();
288             \endcode is NOT equivalent to \code
289             odocstringstream oss;
290             writeLaTeXSource(oss, ...);
291             ofdocstream ofs;
292             ofs.open("test.tex");
293             ofs << oss.str();
294             ofs.close();
295             \endcode
296          */
297         void writeLaTeXSource(odocstream & os,
298                            std::string const & original_path,
299                            OutputParams const &,
300                            bool output_preamble = true,
301                            bool output_body = true) const;
302         ///
303         void makeDocBookFile(support::FileName const & filename,
304                              OutputParams const & runparams_in,
305                              bool only_body = false) const;
306         ///
307         void writeDocBookSource(odocstream & os, std::string const & filename,
308                              OutputParams const & runparams_in,
309                              bool only_body = false) const;
310         ///
311         void makeLyXHTMLFile(support::FileName const & filename,
312                              OutputParams const & runparams_in,
313                              bool only_body = false) const;
314         ///
315         void writeLyXHTMLSource(odocstream & os,
316                              OutputParams const & runparams_in,
317                              bool only_body = false) const;
318         /// returns the main language for the buffer (document)
319         Language const * language() const;
320         /// get l10n translated to the buffers language
321         docstring const B_(std::string const & l10n) const;
322
323         ///
324         int runChktex();
325         /// return true if the main lyx file does not need saving
326         bool isClean() const;
327         ///
328         bool isDepClean(std::string const & name) const;
329
330         /// whether or not disk file has been externally modified
331         bool isExternallyModified(CheckMethod method) const;
332
333         /// mark the main lyx file as not needing saving
334         void markClean() const;
335
336         ///
337         void markDepClean(std::string const & name);
338
339         ///
340         void setUnnamed(bool flag = true);
341
342         /// Whether or not a filename has been assigned to this buffer
343         bool isUnnamed() const;
344
345         /// Whether or not this buffer is internal.
346         ///
347         /// An internal buffer does not contain a real document, but some auxiliary text segment.
348         /// It is not associated with a filename, it is never saved, thus it does not need to be
349         /// automatically saved, nor it needs to trigger any "do you want to save ?" question.
350         bool isInternal() const;
351
352         /// Mark this buffer as dirty.
353         void markDirty();
354
355         /// Returns the buffer's filename. It is always an absolute path.
356         support::FileName fileName() const;
357
358         /// Returns the buffer's filename. It is always an absolute path.
359         std::string absFileName() const;
360
361         /// Returns the the path where the buffer lives.
362         /// It is always an absolute path.
363         std::string filePath() const;
364
365         /** A transformed version of the file name, adequate for LaTeX.
366             \param no_path optional if \c true then the path is stripped.
367         */
368         std::string latexName(bool no_path = true) const;
369
370         /// Get the name and type of the log.
371         std::string logName(LogType * type = 0) const;
372
373         /// Change name of buffer. Updates "read-only" flag.
374         void setFileName(std::string const & newfile);
375
376         /// Set document's parent Buffer.
377         void setParent(Buffer const *);
378         Buffer const * parent() const;
379
380         /** Get the document's master (or \c this if this is not a
381             child document)
382          */
383         Buffer const * masterBuffer() const;
384
385         /// \return true if \p child is a child of this \c Buffer.
386         bool isChild(Buffer * child) const;
387         
388         /// \return true if this \c Buffer has children
389         bool hasChildren() const;
390         
391         /// \return a list of the direct children of this Buffer.
392         /// this list has no duplicates and is in the order in which
393         /// the children appear.
394         ListOfBuffers getChildren() const;
395         
396         /// \return a list of all descendents of this Buffer (children,
397         /// grandchildren, etc). this list has no duplicates and is in
398         /// the order in which the children appear.
399         ListOfBuffers getDescendents() const;
400
401         /// Collect all relative buffers, in the order in which they appear.
402         /// I.e., the "root" Buffer is first, then its first child, then any
403         /// of its children, etc. However, there are no duplicates in this
404         /// list.
405         /// This is "stable", too, in the sense that it returns the same
406         /// thing from whichever Buffer it is called.
407         ListOfBuffers allRelatives() const;
408
409         /// Is buffer read-only?
410         bool isReadonly() const;
411
412         /// Set buffer read-only flag
413         void setReadonly(bool flag = true);
414
415         /// returns \c true if the buffer contains a LaTeX document
416         bool isLatex() const;
417         /// returns \c true if the buffer contains a DocBook document
418         bool isDocBook() const;
419         /// returns \c true if the buffer contains a Wed document
420         bool isLiterate() const;
421
422         /** Validate a buffer for LaTeX.
423             This validates the buffer, and returns a struct for use by
424             #makeLaTeX# and others. Its main use is to figure out what
425             commands and packages need to be included in the LaTeX file.
426             It (should) also check that the needed constructs are there
427             (i.e. that the \refs points to coresponding \labels). It
428             should perhaps inset "error" insets to help the user correct
429             obvious mistakes.
430         */
431         void validate(LaTeXFeatures &) const;
432
433         /// Reference information is cached in the Buffer, so we do not
434         /// have to check or read things over and over. 
435         ///
436         /// There are two caches.
437         ///
438         /// One is a cache of the BibTeX files from which reference info is
439         /// being gathered. This cache is PER BUFFER, and the cache for the
440         /// master essentially includes the cache for its children. This gets
441         /// invalidated when an InsetBibtex is created, deleted, or modified.
442         /// 
443         /// The other is a cache of the reference information itself. This
444         /// exists only in the master buffer, and when it needs to be updated,
445         /// the children add their information to the master's cache.
446         
447         /// Calling this method invalidates the cache and so requires a
448         /// re-read.
449         void invalidateBibinfoCache() const;
450         /// This invalidates the cache of files we need to check.
451         void invalidateBibfileCache() const;
452         /// Updates the cached bibliography information.
453         /// Note that you MUST call this method to update the cache. It will
454         /// not happen otherwise. (Currently, it is called at the start of
455         /// updateBuffer() and from GuiCitation.)
456         /// Note that this operates on the master document.
457         void checkBibInfoCache() const;
458         /// \return the bibliography information for this buffer's master,
459         /// or just for it, if it isn't a child.
460         BiblioInfo const & masterBibInfo() const;
461         ///
462         void fillWithBibKeys(BiblioInfo & keys) const;
463         ///
464         void getLabelList(std::vector<docstring> &) const;
465
466         ///
467         void changeLanguage(Language const * from, Language const * to);
468
469         ///
470         bool isMultiLingual() const;
471         ///
472         std::set<Language const *> getLanguages() const;
473
474         ///
475         BufferParams & params();
476         BufferParams const & params() const;
477
478         /** The list of paragraphs.
479             This is a linked list of paragraph, this list holds the
480             whole contents of the document.
481          */
482         ParagraphList & paragraphs();
483         ParagraphList const & paragraphs() const;
484
485         /// LyX version control object.
486         LyXVC & lyxvc();
487         LyXVC const & lyxvc() const;
488
489         /// Where to put temporary files.
490         std::string const temppath() const;
491
492         /// Used when typesetting to place errorboxes.
493         TexRow const & texrow() const;
494         TexRow & texrow();
495
496         ///
497         ParIterator par_iterator_begin();
498         ///
499         ParConstIterator par_iterator_begin() const;
500         ///
501         ParIterator par_iterator_end();
502         ///
503         ParConstIterator par_iterator_end() const;
504
505         // Position of the child buffer where it appears first in the master.
506         DocIterator firstChildPosition(Buffer const * child);
507
508         /** \returns true only when the file is fully loaded.
509          *  Used to prevent the premature generation of previews
510          *  and by the citation inset.
511          */
512         bool isFullyLoaded() const;
513         /// Set by buffer_funcs' newFile.
514         void setFullyLoaded(bool);
515
516         /// Update the LaTeX preview snippets associated with this buffer
517         void updatePreviews() const;
518         /// Remove any previewed LaTeX snippets associated with this buffer
519         void removePreviews() const;
520
521         /// Our main text (inside the top InsetText)
522         Text & text() const;
523
524         /// Our top InsetText
525         Inset & inset() const;
526
527         //
528         // Macro handling
529         //
530         /// Collect macro definitions in paragraphs
531         void updateMacros() const;
532         /// Iterate through the whole buffer and try to resolve macros
533         void updateMacroInstances() const;
534
535         /// List macro names of this buffer, the parent and the children
536         void listMacroNames(MacroNameSet & macros) const;
537         /// Collect macros of the parent and its children in front of this buffer.
538         void listParentMacros(MacroSet & macros, LaTeXFeatures & features) const;
539
540         /// Return macro defined before pos (or in the master buffer)
541         MacroData const * getMacro(docstring const & name, DocIterator const & pos, bool global = true) const;
542         /// Return macro defined anywhere in the buffer (or in the master buffer)
543         MacroData const * getMacro(docstring const & name, bool global = true) const;
544         /// Return macro defined before the inclusion of the child
545         MacroData const * getMacro(docstring const & name, Buffer const & child, bool global = true) const;
546
547         /// Collect user macro names at loading time
548         typedef std::set<docstring> UserMacroSet;
549         UserMacroSet usermacros;
550
551         /// Replace the inset contents for insets which InsetCode is equal
552         /// to the passed \p inset_code.
553         void changeRefsIfUnique(docstring const & from, docstring const & to,
554                 InsetCode code);
555
556         /// get source code (latex/docbook) for some paragraphs, or all paragraphs
557         /// including preamble
558         void getSourceCode(odocstream & os, pit_type par_begin, pit_type par_end,
559                 bool full_source) const;
560
561         /// Access to error list.
562         /// This method is used only for GUI visualisation of Buffer related
563         /// errors (like parsing or LateX compilation). This method is const
564         /// because modifying the returned ErrorList does not touch the document
565         /// contents.
566         ErrorList & errorList(std::string const & type) const;
567
568         /// The Toc backend.
569         /// This is useful only for screen visualisation of the Buffer. This
570         /// method is const because modifying this backend does not touch
571         /// the document contents.
572         TocBackend & tocBackend() const;
573
574         ///
575         Undo & undo();
576
577         /// This function is called when the buffer is changed.
578         void changed(bool update_metrics) const;
579         ///
580         void setChild(DocIterator const & dit, Buffer * child);
581         ///
582         void updateTocItem(std::string const &, DocIterator const &) const;
583         /// This function is called when the buffer structure is changed.
584         void structureChanged() const;
585         /// This function is called when some parsing error shows up.
586         void errors(std::string const & err, bool from_master = false) const;
587         /// This function is called when the buffer busy status change.
588         void setBusy(bool on) const;
589         /// Update window titles of all users.
590         void updateTitles() const;
591         /// Reset autosave timers for all users.
592         void resetAutosaveTimers() const;
593         ///
594         void message(docstring const & msg) const;
595
596         ///
597         void setGuiDelegate(frontend::GuiBufferDelegate * gui);
598         ///
599         bool hasGuiDelegate() const;
600
601         
602
603         /// return the format of the buffer on a string
604         std::string bufferFormat() const;
605         /// return the default output format of the current backend
606         std::string getDefaultOutputFormat() const;
607
608         ///
609         bool doExport(std::string const & format, bool put_in_tempdir,
610                 bool includeall, std::string & result_file) const;
611         ///
612         bool doExport(std::string const & format, bool put_in_tempdir,
613                       bool includeall = false) const;
614         ///
615         bool preview(std::string const & format, bool includeall = false) const;
616         ///
617         bool isExportable(std::string const & format) const;
618         ///
619         std::vector<Format const *> exportableFormats(bool only_viewable) const;
620         ///
621         bool isExportableFormat(std::string const & format) const;
622         /// mark the buffer as busy exporting something, or not
623         void setExportStatus(bool e) const;
624         ///
625         bool isExporting() const;
626
627         ///
628         typedef std::vector<std::pair<Inset *, ParIterator> > References;
629         References & references(docstring const & label);
630         References const & references(docstring const & label) const;
631         void clearReferenceCache() const;
632         void setInsetLabel(docstring const & label, InsetLabel const * il);
633         InsetLabel const * insetLabel(docstring const & label) const;
634
635         /// return a list of all used branches (also in children)
636         void getUsedBranches(std::list<docstring> &, bool const from_master = false) const;
637
638         /// sets the buffer_ member for every inset in this buffer.
639         // FIXME This really shouldn't be needed, but at the moment it's not
640         // clear how to do it just for the individual pieces we need.
641         void setBuffersForInsets() const;
642         /// Updates screen labels and some other information associated with
643         /// insets and paragraphs. Actually, it's more like a general "recurse
644         /// through the Buffer" routine, that visits all the insets and paragraphs.
645         void updateBuffer() const { updateBuffer(UpdateMaster, InternalUpdate); }
646         /// \param scope: whether to start with the master document or just
647         /// do this one.
648         /// \param output: whether we are preparing for output.
649         void updateBuffer(UpdateScope scope, UpdateType utype) const;
650         /// 
651         void updateBuffer(ParIterator & parit, UpdateType utype) const;
652
653         /// Spellcheck starting from \p from.
654         /// \p from initial position, will then points to the next misspelled
655         ///    word.
656         /// \p to will points to the end of the next misspelled word.
657         /// \p word_lang will contain the found misspelled word.
658         /// \return progress if a new word was found.
659         int spellCheck(DocIterator & from, DocIterator & to,
660                 WordLangTuple & word_lang, docstring_list & suggestions) const;
661         ///
662         void checkChildBuffers();
663
664 private:
665         ///
666         std::vector<std::string> backends() const;
667         ///
668         void getLanguages(std::set<Language const *> &) const;
669         /// Update the list of all bibfiles in use (including bibfiles
670         /// of loaded child documents).
671         void updateBibfilesCache(UpdateScope scope = UpdateMaster) const;
672         /// Return the list with all bibfiles in use (including bibfiles
673         /// of loaded child documents).
674         support::FileNameList const & 
675                 getBibfilesCache(UpdateScope scope = UpdateMaster) const;
676         ///
677         void collectChildren(ListOfBuffers & children, bool grand_children) const;
678
679         
680         /// Use the Pimpl idiom to hide the internals.
681         class Impl;
682         /// The pointer never changes although *pimpl_'s contents may.
683         Impl * const d;
684 };
685
686
687 } // namespace lyx
688
689 #endif