Package peppy :: Module major :: Class MajorMode
[frames] | no frames]

Class MajorMode

               object --+    
                        |    
lib.userparams.ClassPrefs --+
                            |
               object --+   |
                        |   |
         debug.debugmixin --+
                            |
                           MajorMode
Known Subclasses:

Mixin class for all major modes.

Major modes are associated with some type (or types) of file, and provide a way to edit them. Most major modes that edit text will actually want to be a subclass of FundamentalMode, as that class uses the wx.stc.StyledTextControl as its base class and provides a lot of additional text editing support by default. See PythonMode, ChangeLogMode, and MakefileMode for examples of modes that use FundamentalMode as a basis.

If a major mode isn't for a text file, however, it should use this mixin class along with some other subclass of wx.Window to provide the editing interface. This mixin is required because it provides a lot of the boilerplate stuff that peppy needs to manage the major mode. See HexEditMode and DiredMode for modes that don't use an stc for their user window.

Associating the Major Mode with a File Type

When a file is opened, peppy uses the MajorModeMatcherDriver class to determine which major mode to use to edit the file. The MajorModeMatcherDriver.match method loops over all major modes and uses the heuristics to determine the best match by calling the verify* class methods of the major modes. There are default implementations of the verify methods that use class attributes of the major mode to identify the mode.

There are several ways to tell peppy to associate the major mode with a particular type of file.

MIME Type

The simplest is to specify the MIME type in the class attribute mimetype. The MIME type returned from the vfs.get_metadata call will be used to match against the MIME type specified here; or alternatively you can override the verifyMimetype class method and perform matching on the MIME type of each file as it's opened by peppy.

However, not all MIME types are known by default to the VFS, so you may need to provide other ways to match the file.

Filename

If your file always has a certain extension, you can specify a regular expression is the regex class attribute. This uses the verifyFilename method to return a match. You can also override the verifyFilename method directly.

Note that only the filename is passed to the verifyFilename method as it should be independent of the scheme used to retrieve the URL. If you actually want to match on the scheme, use the verifyProtocol method.

Magic Bytes

If there's no easy way to tell the file type, you may need to check some bytes in the file to see if it matches some "magic number" that will identify the file that peppy is trying to load as one that your major mode supports.

The class method verifyMagic is called if there's no exact match by earlier methods. In order to reduce the expense of this operation, a certain number of bytes (a minimum of 1024) are read from the file before the call to verifyMagic so that every major mode isn't trying to read the same file over and over. If your file can't be uniquely determined in the first 1024 bytes, there is still a way to determine the file type: see the IPeppyPlugin.attemptOpen method.

Backend Storage

Once the major mode has been selected for that file, it is loaded into a Buffer for storage. There is only one Buffer instance per copy of a file that's loaded. Multiple views of the same file always point back to the same Buffer.

The major mode uses the Buffer as the backend storage for the data. The Buffer uses a class that implements the STCInterface as the actual storage space for the loaded file. Major modes declare what type of STCInterface is used for the backend storage by setting the class attribute stc_class.

Peppy is not limited to editing files that can fit in physical memory. However, the wx.stc.StyledTextCtrl (the Scintilla control, abbreviated 'STC' here) does require that the file be held in physical memory. So, if you're going to use an stc to display your file, you're limited to files that can fit in memory. Files larger than physical memory should extend from NonResidentSTC, but currently the extra steps required to make a major mode for extremely large files are not documented. See hsi_major_mode if you're interested, until better documentation is written.

For a major mode that focuses on files that can be held in memory, the backend storage should be implemented by a PeppySTC instance.

STC Backend Storage and STC Used for Display

If your major mode also uses an STC for displaying the text to the user, you should consider extending your major mode from FundamentalMode, as the details will be taken care of for you. But be aware that the STC used for backend storage is not the same as the STC presented to the user.

The backend storage is the root document, and this root document does not get displayed. The STC that is used for display will be linked to the Buffer's STC using the document pointer capability of Scintilla. This means that multiple views of the same file are possible, and all share the same backend storage because they all point to the same buffer.

STC Backend Storage without using an STC for Display

It is also possible to use a real STC for backend storage, but use some different wx.Window subclass for display. See the HexEditMode for an example that uses a wx.Grid control to present the file as a string of binary bytes.

There are complications to using this approach, however. Because multiple views are possible, there could be a text view of a file at the same time as a hex edit view. If both views were STCs, the changes in one would be automatically propagated to the other. But, because one of the views is a wx.Grid, we must catch modification events and update the wx.Grid as bytes change in the other view. See the HexEditMode for more information.

Fundamental Text Editing

Most major modes for text editing will use a real STC for user interaction. The best way to make a major mode that uses a real STC is to extend from FundamentalMode. Fundamental mode uses a bunch of mixins that extend the functionality of the STC, and provide the places for customized enhancements like brace highlighting, region commenting, paragraph finding, and a lot of other features. Examining one of the subclasses of Fundamental mode is probably the best place to start if you're interested in extending peppy to handle a file that is currently unsupported.

Nested Classes
  stc_class
stc_class is used to associate this major mode with a storage mechanism (implementing the STCInterface).

Inherited from lib.userparams.ClassPrefs: __metaclass__

Instance Methods
 
OnContextMenu(self, evt)
Hook to display a context menu relevant to this major mode.
 
OnUpdateUI(self, evt)
Callback to update user interface elements.
 
OnUpdateUIHook(self, evt)
 
__del__(self)
 
__init__(self, parent, wrapper, buffer, frame)
x.__init__(...) initializes x; see x.__class__.__doc__ for signature
 
applySettings(self)
Apply settings to the view
 
createEditWindow(self, parent)
 
createEventBindings(self)
 
createEventBindingsPostHook(self)
 
createListeners(self)
Required wx.lib.pubsub listeners are created here.
 
createListenersPostHook(self)
Hook to add custom listeners.
 
createPostHook(self)
Hook called when everything has been created.
 
createStatusBarInfo(self)
Create the status bar exstrinsic information storage.
 
createStatusIcons(self)
Create any icons in the status bar.
 
createWindowPostHook(self)
User hook to add resources after the edit window is created.
 
deleteWindow(self)
 
deleteWindowPostHook(self)
Hook after all widgets are deleted.
 
deleteWindowPre(self)
Manager routine to delete resources before the main window is deleted.
 
deleteWindowPreHook(self)
Hook to remove resources before windows are deleted.
 
findMinorMode(self, name)
Proxy the minor mode requests up to the wrapper
 
focus(self)
 
focusPostHook(self)
 
getIcon(self)
 
getPopupActions(self, x, y)
Return the list of action classes to use as a context menu.
 
getStatusBarWidths(self)
Returns a list of status bar field widths.
 
getTabName(self)
 
getTitle(self)
 
getWelcomeMessage(self)
 
idleHandler(self)
 
idlePostHook(self)
Hook for subclasses to process during idle time.
 
loadMinorModesPostHook(self)
User hook after all minor modes have been loaded.
 
removeListeners(self)
Required wx.lib.pubsub listeners are removed here.
 
removeListenersPostHook(self)
Hook to remove custom listeners.
 
removeMinibuffer(self, specific=None, detach_only=False)
Proxy the minibuffer requests up to the wrapper
 
resetStatusBar(self, message=None)
Updates the status bar.
 
save(self, url=None)
 
savePostHook(self)
Hook to perform any housekeeping after a save
 
savePreHook(self, url=None)
Hook before the buffer is saved.
 
setMinibuffer(self, minibuffer=None)
Proxy the minibuffer requests up to the wrapper
 
setStatusText(self, text, field=0)
 
settingsChanged(self, message=None)
 
showBusy(self, busy)
 
showInitialPosition(self, url)
Hook to scroll to a non-default initial position if desired.
 
showModified(self, modified)
 
tabActivatedHook(self)
Hook to update some user interface parameters after the tab has been made the current tab.
 
updateAui(self)

Inherited from object: __delattr__, __getattribute__, __hash__, __new__, __reduce__, __reduce_ex__, __repr__, __setattr__, __str__

Class Methods
 
verifyEditraType(cls, ext, file_type)
Hook to verify the mode can handle the specified Editra type.
 
verifyFilename(cls, filename)
Hook to verify filename matches the default regular expression for this mode.
 
verifyMagic(cls, header)
Hook to verify the file is acceptable to this mode.
 
verifyMetadata(cls, metadata)
Hook to allow the major mode to determine compatibility by file metadata.
 
verifyMimetype(cls, mimetype)
Hook to allow the major mode to determine compatibility by mimetype.
 
verifyProtocol(cls, url)
Hook to short-circuit the mode matching heuristics.

Inherited from debug.debugmixin: dprint

Class Variables
  allow_threaded_loading = True
If this mode allows threading loading, set this True
  classprefs = <peppy.lib.userparams.PrefsProxy object at 0x432a...
  debuglevel = 0
set to non-zero to activate debug printing for this class
  default_classprefs = StrParam('minor_modes', '', 'List of mino...
  emacs_synonyms = None
If there are additional emacs synonyms for this mode, list them here as a string for a single synonym, or in a list of strings for multiple.
  icon = 'icons/page_white.png'
Pointer to the icon representing this major mode
  keyword = 'Abstract_Major_Mode'
The single-word keyword representing this major mode
  localkeymaps = {}
  mimetype = None
The VFS also provides metadata, including MIME type, and the MIME types supported by the major mode can be listed here.
  preferences_tab = 'Modes'
The preferences tab that this mode will appear in
  regex = None
Filenames are matched against this regex in the class method verifyFilename when peppy tries to determine which mode to use to edit the file.
  temporary = False
If this mode represents a temporary view and should be replaced by a new tab, make this True

Inherited from lib.userparams.ClassPrefs: preferences_sort_weight

Properties

Inherited from object: __class__

Method Details

OnContextMenu(self, evt)

 

Hook to display a context menu relevant to this major mode.

For standard usage, subclasses should override getPopupActions to provide a list of actions to display in the popup menu. Nonstandard behaviour on a right click can be implemented by overriding this method instead.

Currently, this event gets triggered when it happens over the major mode AND the minor modes. So, that means the minor modes won't get their own EVT_CONTEXT_MENU events unless evt.Skip() is called here.

This may or may not be the best behavior to implement. I'll have to see as I get further into it.

OnUpdateUI(self, evt)

 

Callback to update user interface elements.

This event is called when the user interacts with the editing window, possibly creating a state change that would require some user interface elements to change state.

Don't depend on this coming from the STC, as non-STC based modes won't have the STC_EVT_UPDATEUI event and may be calling this using other events.

Parameters:
  • evt - some event of undetermined type

__init__(self, parent, wrapper, buffer, frame)
(Constructor)

 

x.__init__(...) initializes x; see x.__class__.__doc__ for signature

Overrides: object.__init__
(inherited documentation)

applySettings(self)

 

Apply settings to the view

This is the place where settings for the class show their effects. Calling this should update the view to reflect any changes in the settings.

createListeners(self)

 

Required wx.lib.pubsub listeners are created here.

Subclasses should override createListenersPostHook to add their own listeners.

createListenersPostHook(self)

 

Hook to add custom listeners.

Subclasses should override this method rather than createListeners to add their own listeners.

createPostHook(self)

 

Hook called when everything has been created.

This hook is called just before control is returned to the main application loop, i.e. after the edit window, minor modes, and all bindings and other hooks are called.

createStatusBarInfo(self)

 

Create the status bar exstrinsic information storage.

The appearance of the statusbar can depend on the major mode, so the individual major mode is responsible for creating whatever it needs.

createStatusIcons(self)

 

Create any icons in the status bar.

This is called after making the major mode the active mode in the frame. The status bar will be cleared to its initial empty state, so all this method has to do is add any icons that it needs.

deleteWindowPostHook(self)

 

Hook after all widgets are deleted.

This is called after all windows have been deleted, in case there are any non-window references to clean up.

deleteWindowPre(self)

 

Manager routine to delete resources before the main window is deleted.

Not called from user code; override deleteWindowPreHook to add user code to the delete process.

deleteWindowPreHook(self)

 

Hook to remove resources before windows are deleted.

This is called before anything is deleted. Don't try to delete any of the resources that are automatically managed (i.e. minor modes, windows, toolbars, etc.) or BadThings(tm) will happen.

getPopupActions(self, x, y)

 

Return the list of action classes to use as a context menu.

If the subclass is capable of displaying a popup menu, it needs to return a list of action classes. The x, y pixel coordinates (relative to the origin of major mode window) are included in case the subclass can display different popup items depending on the position in the editing window.

getStatusBarWidths(self)

 

Returns a list of status bar field widths.

Override this in subclasses to change the number of text fields in the status bar.

loadMinorModesPostHook(self)

 

User hook after all minor modes have been loaded.

Use this hook if you need to initialize the set of minor modes after all of them have been loaded.

removeListeners(self)

 

Required wx.lib.pubsub listeners are removed here.

Subclasses should override removeListenersPostHook to remove any listeners that were added. Normally, wx.lib.pubsub removes references to dead objects, and so this cleanup shouldn't be necessary. But, because the MajorMode is subclassed from the C++ object, the python part is removed but the C++ part isn't cleaned up immediately. So, we have to remove the listener references manually.

removeListenersPostHook(self)

 

Hook to remove custom listeners.

Any listeners added by subclasses in createListenersPostHook should be removed here.

resetStatusBar(self, message=None)

 

Updates the status bar.

This method clears and rebuilds the status bar, usually because something requests an icon change.

savePreHook(self, url=None)

 

Hook before the buffer is saved.

The save is vetoable by returning False. Returning True or None (None is also returned when you don't explicitly return anything) allows the save to continue.

verifyEditraType(cls, ext, file_type)
Class Method

 

Hook to verify the mode can handle the specified Editra type.

Parameters:
  • ext - filename extension without the '.', or an empty string
  • file_type - Editra file type string as given in the file peppy/editra/synglob.py, or None if not recognized by Editra
Returns:
either the boolean False, indicating Editra doesn't support this mode, or a string. The string can either be the same as the input value ext if it matches a specific type supported by this mode or 'generic' if Editra supports the mode but if the mode doesn't provide any additional functionality (this usually only happens in Fundamental mode).

verifyFilename(cls, filename)
Class Method

 

Hook to verify filename matches the default regular expression for this mode.

Parameters:
  • filename - the pathname part of the url (i.e. not the protocol, port number, query string, or anything else)
Returns:
True if the filename matches

verifyMagic(cls, header)
Class Method

 

Hook to verify the file is acceptable to this mode.

If the file can be identified by magic characters within the first n bytes (typically n < 1024), return a flag that indicates whether or not this file can be opened by this mode.

Parameters:
  • header - string with the first n characters of the file
Returns:
True if the magic was identified exactly, False if the file is not capable of being opened by this mode, or None if indeterminate.

verifyMetadata(cls, metadata)
Class Method

 

Hook to allow the major mode to determine compatibility by file metadata.

This method is more general than verifyMimetype, as it can operate on all the metadata passed to it rather than just the MIME type.

metadata: a dict containing the results of a call to vfs.get_metadata. The MIME type will be in a key called 'mimetype'.

return: True if the mode supports the MIME type specified by the metadata

verifyMimetype(cls, mimetype)
Class Method

 

Hook to allow the major mode to determine compatibility by mimetype.

mimetype: a string indicating the MIME type of the file

return: True if the mode supports the MIME type

verifyProtocol(cls, url)
Class Method

 

Hook to short-circuit the mode matching heuristics.

For non-editing applications and client applications that connect to a server, this hook provides the ability to short-circuit the matching process and open a mode immediately.

This method must not attempt to open the url and read any data. All modes' verifyProtocol methods are called before the file is attempted to be opened, and attempting to read data here could mess up streaming files.

Parameters:
  • url - vfs.Reference object
Returns:
True to short circuit and use this mode.

Class Variable Details

classprefs

Value:
<peppy.lib.userparams.PrefsProxy object at 0x432a450>

default_classprefs

Value:
StrParam('minor_modes', '', 'List of minor mode keywords that should b\
e\ndisplayed when starting this major mode'), IntParam('line_number_of\
fset', 1, 'Number to add to the line number reported\nby the mode\'s s\
tc in order to display'), IntParam('column_number_offset', 1, 'Number \
to add to the column number reported\nby the mode\'s stc in order to d\
isplay'),

emacs_synonyms

If there are additional emacs synonyms for this mode, list them here as a string for a single synonym, or in a list of strings for multiple. For instance, see hexedit_mode.py: in emacs the hex edit mode is called 'hexl', but in peppy, it's called 'HexEdit'. 'hexl' is listed as in emacs_synomyms in that file.

Value:
None

mimetype

The VFS also provides metadata, including MIME type, and the MIME types supported by the major mode can be listed here. The MIME types can be a single string or a list of strings for multiple types.

Value:
None

regex

Filenames are matched against this regex in the class method verifyFilename when peppy tries to determine which mode to use to edit the file. If no specific filenames, set to None

Value:
None