]> git.lyx.org Git - lyx.git/blob - src/Buffer.h
Allow MTag to take attributes.
[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 #include "update_flags.h"
17
18 #include "insets/InsetCode.h"
19
20 #include "support/strfwd.h"
21 #include "support/types.h"
22 #include "support/SignalSlot.h"
23
24 #include <list>
25 #include <set>
26 #include <string>
27 #include <vector>
28
29
30 namespace lyx {
31
32 class BiblioInfo;
33 class BufferParams;
34 class BufferSet;
35 class DispatchResult;
36 class DocIterator;
37 class docstring_list;
38 class ErrorItem;
39 class ErrorList;
40 class FuncRequest;
41 class FuncStatus;
42 class Inset;
43 class InsetRef;
44 class InsetLabel;
45 class Font;
46 class Format;
47 class Lexer;
48 class LyXRC;
49 class Text;
50 class LyXVC;
51 class LaTeXFeatures;
52 class Language;
53 class MacroData;
54 class MacroNameSet;
55 class MacroSet;
56 class OutputParams;
57 class Paragraph;
58 class ParConstIterator;
59 class ParIterator;
60 class ParagraphList;
61 class TeXErrors;
62 class TexRow;
63 class TocBackend;
64 class Undo;
65 class WordLangTuple;
66
67 namespace frontend {
68 class GuiBufferDelegate;
69 class WorkAreaManager;
70 }
71
72 namespace support {
73 class FileName;
74 class FileNameList;
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                 failure, ///< The file could not be read
99                 success, ///< The file could not be read
100                 wrongversion ///< The version of the file does not match ours
101         };
102
103
104         /// Method to check if a file is externally modified, used by
105         /// isExternallyModified()
106         /**
107          * timestamp is fast but inaccurate. For example, the granularity
108          * of timestamp on a FAT filesystem is 2 second. Also, various operations
109          * may touch the timestamp of a file even when its content is unchanged.
110          *
111          * checksum is accurate but slow, which can be a problem when it is
112          * frequently used, or used for a large file on a slow (network) file
113          * system.
114          *
115          * FIXME: replace this method with support/FileMonitor.
116          */
117         enum CheckMethod {
118                 checksum_method,  ///< Use file checksum
119                 timestamp_method, ///< Use timestamp, and checksum if timestamp has changed
120         };
121
122         ///
123         enum UpdateScope {
124                 UpdateMaster,
125                 UpdateChildOnly
126         };
127
128         /// Constructor
129         explicit Buffer(std::string const & file, bool readonly = false,
130                 Buffer const * cloned_buffer = 0);
131
132         /// Destructor
133         ~Buffer();
134
135         ///
136         Buffer * clone() const;
137         ///
138         bool isClone() const;
139
140         /** High-level interface to buffer functionality.
141             This function parses a command string and executes it.
142         */
143         void dispatch(std::string const & command, DispatchResult & result);
144
145         /// Maybe we know the function already by number...
146         void dispatch(FuncRequest const & func, DispatchResult & result);
147
148         /// Can this function be exectued?
149         /// \return true if we made a decision
150         bool getStatus(FuncRequest const & cmd, FuncStatus & flag);
151
152         /// read a new document from a string
153         bool readString(std::string const &);
154         /// load a new file
155         bool readFile(support::FileName const & filename);
156
157         /// read the header, returns number of unknown tokens
158         int readHeader(Lexer & lex);
159
160         /** Reads a file without header.
161             \param par if != 0 insert the file.
162             \return \c true if file is not completely read.
163         */
164         bool readDocument(Lexer &);
165
166         ///
167         DocIterator getParFromID(int id) const;
168         /// do we have a paragraph with this id?
169         bool hasParWithID(int id) const;
170
171         ///
172         frontend::WorkAreaManager & workAreaManager() const;
173
174         /** Save file.
175             Takes care of auto-save files and backup file if requested.
176             Returns \c true if the save is successful, \c false otherwise.
177         */
178         bool save() const;
179
180         /// Write document to stream. Returns \c false if unsuccesful.
181         bool write(std::ostream &) const;
182         /// save emergency file
183         /// \return a status message towards the user.
184         docstring emergencyWrite();
185         /// Write file. Returns \c false if unsuccesful.
186         bool writeFile(support::FileName const &) const;
187
188         /// Loads LyX file \c filename into buffer, *  and return success
189         bool loadLyXFile(support::FileName const & s);
190         /// Reloads the LyX file
191         bool reload();
192
193         /// Fill in the ErrorList with the TeXErrors
194         void bufferErrors(TeXErrors const &, ErrorList &) const;
195
196         /// Just a wrapper for writeLaTeXSource, first creating the ofstream.
197         bool makeLaTeXFile(support::FileName const & filename,
198                            std::string const & original_path,
199                            OutputParams const &,
200                            bool output_preamble = true,
201                            bool output_body = true) const;
202         /** Export the buffer to LaTeX.
203             If \p os is a file stream, and params().inputenc is "auto" or
204             "default", and the buffer contains text in different languages
205             with more than one encoding, then this method will change the
206             encoding associated to \p os. Therefore you must not call this
207             method with a string stream if the output is supposed to go to a
208             file. \code
209             ofdocstream ofs;
210             ofs.open("test.tex");
211             writeLaTeXSource(ofs, ...);
212             ofs.close();
213             \endcode is NOT equivalent to \code
214             odocstringstream oss;
215             writeLaTeXSource(oss, ...);
216             ofdocstream ofs;
217             ofs.open("test.tex");
218             ofs << oss.str();
219             ofs.close();
220             \endcode
221          */
222         void writeLaTeXSource(odocstream & os,
223                            std::string const & original_path,
224                            OutputParams const &,
225                            bool output_preamble = true,
226                            bool output_body = true) const;
227         ///
228         void makeDocBookFile(support::FileName const & filename,
229                              OutputParams const & runparams_in,
230                              bool only_body = false) const;
231         ///
232         void writeDocBookSource(odocstream & os, std::string const & filename,
233                              OutputParams const & runparams_in,
234                              bool only_body = false) const;
235         ///
236         void makeLyXHTMLFile(support::FileName const & filename,
237                              OutputParams const & runparams_in,
238                              bool only_body = false) const;
239         ///
240         void writeLyXHTMLSource(odocstream & os,
241                              OutputParams const & runparams_in,
242                              bool only_body = false) const;
243         /// returns the main language for the buffer (document)
244         Language const * language() const;
245         /// get l10n translated to the buffers language
246         docstring const B_(std::string const & l10n) const;
247
248         ///
249         int runChktex();
250         /// return true if the main lyx file does not need saving
251         bool isClean() const;
252         ///
253         bool isBakClean() const;
254         ///
255         bool isDepClean(std::string const & name) const;
256
257         /// whether or not disk file has been externally modified
258         bool isExternallyModified(CheckMethod method) const;
259
260         /// save timestamp and checksum of the given file.
261         void saveCheckSum(support::FileName const & file) const;
262
263         /// mark the main lyx file as not needing saving
264         void markClean() const;
265
266         ///
267         void markBakClean() const;
268
269         ///
270         void markDepClean(std::string const & name);
271
272         ///
273         void setUnnamed(bool flag = true);
274
275         /// Whether or not a filename has been assigned to this buffer
276         bool isUnnamed() const;
277
278         /// Whether or not this buffer is internal.
279         ///
280         /// An internal buffer does not contain a real document, but some auxiliary text segment.
281         /// It is not associated with a filename, it is never saved, thus it does not need to be
282         /// automatically saved, nor it needs to trigger any "do you want to save ?" question.
283         bool isInternal() const;
284
285         /// Mark this buffer as dirty.
286         void markDirty();
287
288         /// Returns the buffer's filename. It is always an absolute path.
289         support::FileName fileName() const;
290
291         /// Returns the buffer's filename. It is always an absolute path.
292         std::string absFileName() const;
293
294         /// Returns the the path where the buffer lives.
295         /// It is always an absolute path.
296         std::string filePath() const;
297
298         /** A transformed version of the file name, adequate for LaTeX.
299             \param no_path optional if \c true then the path is stripped.
300         */
301         std::string latexName(bool no_path = true) const;
302
303         /// Get the name and type of the log.
304         std::string logName(LogType * type = 0) const;
305
306         /// Change name of buffer. Updates "read-only" flag.
307         void setFileName(std::string const & newfile);
308
309         /// Set document's parent Buffer.
310         void setParent(Buffer const *);
311         Buffer const * parent() const;
312
313         // Collect all relative buffer
314         std::vector<Buffer const *> allRelatives() const;
315
316         /** Get the document's master (or \c this if this is not a
317             child document)
318          */
319         Buffer const * masterBuffer() const;
320
321         /// \return true if \p child is a child of this \c Buffer.
322         bool isChild(Buffer * child) const;
323         
324         /// return a vector with all children (and grandchildren)
325         std::vector<Buffer *> getChildren(bool grand_children = true) const;
326
327         /// Add all children (and grandchildren) to supplied vector
328         void getChildren(std::vector<Buffer *> & children, bool grand_children = true) const;
329
330         /// Is buffer read-only?
331         bool isReadonly() const;
332
333         /// Set buffer read-only flag
334         void setReadonly(bool flag = true);
335
336         /// returns \c true if the buffer contains a LaTeX document
337         bool isLatex() const;
338         /// returns \c true if the buffer contains a DocBook document
339         bool isDocBook() const;
340         /// returns \c true if the buffer contains a Wed document
341         bool isLiterate() const;
342
343         /** Validate a buffer for LaTeX.
344             This validates the buffer, and returns a struct for use by
345             #makeLaTeX# and others. Its main use is to figure out what
346             commands and packages need to be included in the LaTeX file.
347             It (should) also check that the needed constructs are there
348             (i.e. that the \refs points to coresponding \labels). It
349             should perhaps inset "error" insets to help the user correct
350             obvious mistakes.
351         */
352         void validate(LaTeXFeatures &) const;
353
354         /// Update the list of all bibfiles in use (including bibfiles
355         /// of loaded child documents).
356         void updateBibfilesCache(UpdateScope scope = UpdateMaster) const;
357         /// Return the list with all bibfiles in use (including bibfiles
358         /// of loaded child documents).
359         support::FileNameList const & 
360                 getBibfilesCache(UpdateScope scope = UpdateMaster) const;
361         /// Information from BibTeX databases is cached in the Buffer, so
362         /// we do not have to read the file over and over. 
363         /// Calling this method invalidates the cache and so requires a
364         /// re-read.
365         void invalidateBibinfoCache();
366         /// Updates the cached bibliography information.
367         /// Note that you MUST call this method to update the cache. It will
368         /// not happen otherwise. (Currently, it is called at the start of
369         /// updateLabels() and from GuiCitation.)
370         void checkBibInfoCache() const;
371         /// \return the bibliography information for this buffer's master,
372         /// or just for it, if it isn't a child.
373         BiblioInfo const & masterBibInfo() const;
374         /// \return the bibliography information for this buffer ONLY.
375         BiblioInfo const & localBibInfo() const;
376         ///
377         void getLabelList(std::vector<docstring> &) const;
378
379         ///
380         void changeLanguage(Language const * from, Language const * to);
381
382         ///
383         bool isMultiLingual() const;
384
385         ///
386         BufferParams & params();
387         BufferParams const & params() const;
388
389         /** The list of paragraphs.
390             This is a linked list of paragraph, this list holds the
391             whole contents of the document.
392          */
393         ParagraphList & paragraphs();
394         ParagraphList const & paragraphs() const;
395
396         /// LyX version control object.
397         LyXVC & lyxvc();
398         LyXVC const & lyxvc() const;
399
400         /// Where to put temporary files.
401         std::string const temppath() const;
402
403         /// Used when typesetting to place errorboxes.
404         TexRow const & texrow() const;
405         TexRow & texrow();
406
407         ///
408         ParIterator par_iterator_begin();
409         ///
410         ParConstIterator par_iterator_begin() const;
411         ///
412         ParIterator par_iterator_end();
413         ///
414         ParConstIterator par_iterator_end() const;
415
416         // Position of the child buffer where it appears first in the master.
417         DocIterator firstChildPosition(Buffer const * child);
418
419         /** \returns true only when the file is fully loaded.
420          *  Used to prevent the premature generation of previews
421          *  and by the citation inset.
422          */
423         bool isFullyLoaded() const;
424         /// Set by buffer_funcs' newFile.
425         void setFullyLoaded(bool);
426
427         /// Our main text (inside the top InsetText)
428         Text & text() const;
429
430         /// Our top InsetText
431         Inset & inset() const;
432
433         //
434         // Macro handling
435         //
436         /// Collect macro definitions in paragraphs
437         void updateMacros() const;
438         /// Iterate through the whole buffer and try to resolve macros
439         void updateMacroInstances() const;
440
441         /// List macro names of this buffer, the parent and the children
442         void listMacroNames(MacroNameSet & macros) const;
443         /// Collect macros of the parent and its children in front of this buffer.
444         void listParentMacros(MacroSet & macros, LaTeXFeatures & features) const;
445
446         /// Return macro defined before pos (or in the master buffer)
447         MacroData const * getMacro(docstring const & name, DocIterator const & pos, bool global = true) const;
448         /// Return macro defined anywhere in the buffer (or in the master buffer)
449         MacroData const * getMacro(docstring const & name, bool global = true) const;
450         /// Return macro defined before the inclusion of the child
451         MacroData const * getMacro(docstring const & name, Buffer const & child, bool global = true) const;
452
453         /// Collect user macro names at loading time
454         typedef std::set<docstring> UserMacroSet;
455         UserMacroSet usermacros;
456
457         /// Replace the inset contents for insets which InsetCode is equal
458         /// to the passed \p inset_code.
459         void changeRefsIfUnique(docstring const & from, docstring const & to,
460                 InsetCode code);
461
462         /// get source code (latex/docbook) for some paragraphs, or all paragraphs
463         /// including preamble
464         void getSourceCode(odocstream & os, pit_type par_begin, pit_type par_end,
465                 bool full_source) const;
466
467         /// Access to error list.
468         /// This method is used only for GUI visualisation of Buffer related
469         /// errors (like parsing or LateX compilation). This method is const
470         /// because modifying the returned ErrorList does not touch the document
471         /// contents.
472         ErrorList & errorList(std::string const & type) const;
473
474         /// The Toc backend.
475         /// This is useful only for screen visualisation of the Buffer. This
476         /// method is const because modifying this backend does not touch
477         /// the document contents.
478         TocBackend & tocBackend() const;
479
480         ///
481         Undo & undo();
482
483         /// This function is called when the buffer is changed.
484         void changed(bool update_metrics) const;
485         ///
486         void setChild(DocIterator const & dit, Buffer * child);
487         ///
488         void updateTocItem(std::string const &, DocIterator const &) const;
489         /// This function is called when the buffer structure is changed.
490         void structureChanged() const;
491         /// This function is called when some parsing error shows up.
492         void errors(std::string const & err, bool from_master = false) const;
493         /// This function is called when the buffer busy status change.
494         void setBusy(bool on) const;
495         /// This function is called when the buffer readonly status change.
496         void setReadOnly(bool on) const;
497         /// Update window titles of all users.
498         void updateTitles() const;
499         /// Reset autosave timers for all users.
500         void resetAutosaveTimers() const;
501         ///
502         void message(docstring const & msg) const;
503
504         ///
505         void setGuiDelegate(frontend::GuiBufferDelegate * gui);
506         ///
507         bool hasGuiDelegate() const;
508
509         ///
510         void autoSave() const;
511         ///
512         void removeAutosaveFile() const;
513         ///
514         void moveAutosaveFile(support::FileName const & old) const;
515         ///
516         support::FileName getAutosaveFilename() const;
517
518         /// return the format of the buffer on a string
519         std::string bufferFormat() const;
520         /// return the default output format of the current backend
521         std::string getDefaultOutputFormat() const;
522
523         ///
524         bool doExport(std::string const & format, bool put_in_tempdir,
525                 bool includeall, std::string & result_file) const;
526         ///
527         bool doExport(std::string const & format, bool put_in_tempdir,
528                       bool includeall = false) const;
529         ///
530         bool preview(std::string const & format, bool includeall = false) const;
531         ///
532         bool isExportable(std::string const & format) const;
533         ///
534         std::vector<Format const *> exportableFormats(bool only_viewable) const;
535         ///
536         bool isExportableFormat(std::string const & format) const;
537
538         ///
539         typedef std::vector<std::pair<InsetRef *, ParIterator> > References;
540         References & references(docstring const & label);
541         References const & references(docstring const & label) const;
542         void clearReferenceCache() const;
543         void setInsetLabel(docstring const & label, InsetLabel const * il);
544         InsetLabel const * insetLabel(docstring const & label) const;
545
546         /// return a list of all used branches (also in children)
547         void getUsedBranches(std::list<docstring> &, bool const from_master = false) const;
548
549         /// sets the buffer_ member for every inset in this buffer.
550         // FIXME This really shouldn't be needed, but at the moment it's not
551         // clear how to do it just for the individual pieces we need.
552         void setBuffersForInsets() const;
553         /// Updates screen labels and some other information associated with
554         /// insets and paragraphs. Actually, it's more like a general "recurse
555         /// through the Buffer" routine, that visits all the insets and paragraphs.
556         void updateLabels() const { updateLabels(UpdateMaster, InternalUpdate); }
557         /// \param scope: whether to start with the master document or just
558         /// do this one.
559         /// \param output: whether we are preparing for output.
560         void updateLabels(UpdateScope scope, UpdateType utype) const;
561         /// 
562         void updateLabels(ParIterator & parit, UpdateType utype) const;
563
564         /// Spellcheck starting from \p from.
565         /// \p from initial position, will then points to the next misspelled
566         ///    word.
567         /// \p to will points to the end of the next misspelled word.
568         /// \p word_lang will contain the found misspelled word.
569         /// \return progress if a new word was found.
570         int spellCheck(DocIterator & from, DocIterator & to,
571                 WordLangTuple & word_lang, docstring_list & suggestions) const;
572
573 private:
574         /// search for macro in local (buffer) table or in children
575         MacroData const * getBufferMacro(docstring const & name,
576                                          DocIterator const & pos) const;
577         /** Update macro table starting with position of it
578             \param it in some text inset
579         */
580         void updateMacros(DocIterator & it,
581                                      DocIterator & scope) const;
582         ///
583         void setLabel(ParIterator & it, UpdateType utype) const;
584         ///
585         void collectRelatives(BufferSet & bufs) const;
586
587         ///
588         bool readFileHelper(support::FileName const & s);
589         ///
590         std::vector<std::string> backends() const;
591         /** Inserts a file into a document
592             \return \c false if method fails.
593         */
594         ReadStatus readFile(Lexer &, support::FileName const & filename,
595                             bool fromString = false);
596
597         /** If we have branches that use the file suffix
598             feature, return the file name with suffix appended.
599         */
600         support::FileName exportFileName() const;
601
602         /// Use the Pimpl idiom to hide the internals.
603         class Impl;
604         /// The pointer never changes although *pimpl_'s contents may.
605         Impl * const d;
606         ///
607         frontend::GuiBufferDelegate * gui_;
608
609         /// This function is called when the buffer structure is changed.
610         Signal structureChanged_;
611         /// This function is called when some parsing error shows up.
612         //Signal errors(std::string const &) = 0;
613         /// This function is called when some message shows up.
614         //Signal message(docstring const &) = 0;
615         /// This function is called when the buffer busy status change.
616         //Signal setBusy(bool) = 0;
617         /// Reset autosave timers for all users.
618         Signal resetAutosaveTimers_;
619 };
620
621
622 } // namespace lyx
623
624 #endif