Commits

Henning Schröder  committed 1a99bc3

idea about emacs mode starts with list of emacs functions
simple python highlighting

  • Participants
  • Parent commits 6dfb131

Comments (0)

Files changed (6)

File codeaide/modes/_simple_highlighter.py

+#!/usr/bin/env python
+
+"""
+highlightedtextedit.py
+
+A PyQt custom widget example for Qt Designer.
+
+Copyright (C) 2006 David Boddie <david@boddie.org.uk>
+Copyright (C) 2005-2006 Trolltech ASA. All rights reserved.
+
+This program is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+"""
+
+from PyQt4 import QtCore, QtGui
+
+
+
+
+
+class PythonHighlighter(QtGui.QSyntaxHighlighter):
+
+    keywords = (
+        "and",       "del",       "for",       "is",        "raise",
+        "assert",    "elif",      "from",      "lambda",    "return",
+        "break",     "else",      "global",    "not",       "try",
+        "class",     "except",    "if",        "or",        "while",
+        "continue",  "exec",      "import",    "pass",      "yield",
+        "def",       "finally",   "in",        "print"
+        )
+    
+    def __init__(self, edit):
+        document = edit.document()
+        QtGui.QSyntaxHighlighter.__init__(self, document)
+
+        base_format = QtGui.QTextCharFormat()
+        base_format.setFont(edit.font())
+        
+        self.base_format = base_format
+        self.document = document
+        
+        self.updateHighlighter(base_format.font())
+    
+    def highlightBlock(self, text):
+    
+        self.setCurrentBlockState(0)
+        
+        if text.trimmed().isEmpty():
+            self.setFormat(0, len(text), self.empty_format)
+            return
+        
+        self.setFormat(0, len(text), self.base_format)
+        
+        startIndex = 0
+        if self.previousBlockState() != 1:
+            startIndex = text.indexOf(self.multiLineStringBegin)
+        
+        if startIndex > -1:
+            self.highlightRules(text, 0, startIndex)
+        else:
+            self.highlightRules(text, 0, len(text))
+        
+        while startIndex >= 0:
+        
+            endIndex = text.indexOf(self.multiLineStringEnd,
+                startIndex + len(self.multiLineStringBegin.pattern()))
+            if endIndex == -1:
+                self.setCurrentBlockState(1)
+                commentLength = text.length() - startIndex
+            else:
+                commentLength = endIndex - startIndex + \
+                                self.multiLineStringEnd.matchedLength()
+                self.highlightRules(text, endIndex, len(text))
+            
+            self.setFormat(startIndex, commentLength, self.multiLineStringFormat)
+            startIndex = text.indexOf(self.multiLineStringBegin,
+                                      startIndex + commentLength)
+    
+    def highlightRules(self, text, start, finish):
+    
+        for expression, format in self.rules:
+        
+            index = text.indexOf(expression, start)
+            while index >= start and index < finish:
+                length = expression.matchedLength()
+                self.setFormat(index, min(length, finish - index), format)
+                index = text.indexOf(expression, index + length)
+    
+    def updateFonts(self, font):
+    
+        self.base_format.setFont(font)
+        self.empty_format = QtGui.QTextCharFormat(self.base_format)
+        #self.empty_format.setFontPointSize(font.pointSize()/4.0)
+        
+        self.keywordFormat = QtGui.QTextCharFormat(self.base_format)
+        self.keywordFormat.setForeground(QtCore.Qt.darkBlue)
+        self.keywordFormat.setFontWeight(QtGui.QFont.Bold)
+        self.callableFormat = QtGui.QTextCharFormat(self.base_format)
+        self.callableFormat.setForeground(QtCore.Qt.darkBlue)
+        self.magicFormat = QtGui.QTextCharFormat(self.base_format)
+        self.magicFormat.setForeground(QtGui.QColor(224,128,0))
+        self.qtFormat = QtGui.QTextCharFormat(self.base_format)
+        self.qtFormat.setForeground(QtCore.Qt.blue)
+        self.qtFormat.setFontWeight(QtGui.QFont.Bold)
+        self.selfFormat = QtGui.QTextCharFormat(self.base_format)
+        self.selfFormat.setForeground(QtCore.Qt.red)
+        #self.selfFormat.setFontItalic(True)
+        self.singleLineCommentFormat = QtGui.QTextCharFormat(self.base_format)
+        self.singleLineCommentFormat.setForeground(QtCore.Qt.darkGreen)
+        self.multiLineStringFormat = QtGui.QTextCharFormat(self.base_format)
+        self.multiLineStringFormat.setBackground(
+            QtGui.QBrush(QtGui.QColor(127,127,255)))
+        self.quotationFormat1 = QtGui.QTextCharFormat(self.base_format)
+        self.quotationFormat1.setForeground(QtCore.Qt.blue)
+        self.quotationFormat2 = QtGui.QTextCharFormat(self.base_format)
+        self.quotationFormat2.setForeground(QtCore.Qt.blue)
+    
+    def updateRules(self):
+    
+        self.rules = []
+        self.rules += map(lambda s: (QtCore.QRegExp(r"\b"+s+r"\b"),
+                          self.keywordFormat), self.keywords)
+        
+        self.rules.append((QtCore.QRegExp(r"\b[A-Za-z_]+\(.*\)"), self.callableFormat))
+        self.rules.append((QtCore.QRegExp(r"\b__[a-z]+__\b"), self.magicFormat))
+        self.rules.append((QtCore.QRegExp(r"\bself\b"), self.selfFormat))
+        self.rules.append((QtCore.QRegExp(r"\bQ([A-Z][a-z]*)+\b"), self.qtFormat))
+        
+        self.rules.append((QtCore.QRegExp(r"#[^\n]*"), self.singleLineCommentFormat))
+        
+        self.multiLineStringBegin = QtCore.QRegExp(r'\"\"\"')
+        self.multiLineStringEnd = QtCore.QRegExp(r'\"\"\"')
+        
+        self.rules.append((QtCore.QRegExp(r'\"[^\n]*\"'), self.quotationFormat1))
+        self.rules.append((QtCore.QRegExp(r"'[^\n]*'"), self.quotationFormat2))
+    
+    def updateHighlighter(self, font):
+    
+        self.updateFonts(font)
+        self.updateRules()
+        self.setDocument(self.document)
+
+
+
+class QtScriptHighlighter(PythonHighlighter):
+
+    keywords = """"
+        break  	for  	throw case 	function 	try
+        catch 	if 	typeof continue 	in 	var default 	instanceof 	void
+        delete 	new 	undefined do 	return 	while  else 	switch 	with
+        finally 	this 	 """.split() + \
+        ['NaN', 'Infinity', 'undefined', 'print', 'parseInt', 
+         'parseFloat', 'isNaN', 'isFinite', 'decodeURI', 
+         'decodeURIComponent', 'encodeURI', 'encodeURIComponent', 
+         'escape', 'unescape', 'version', 'gc', 'Object', 
+         'Function', 'Number', 'Boolean', 'String', 'Date', 'Array', 
+         'RegExp', 'Error', 'EvalError','RangeError', 'ReferenceError', 
+         'SyntaxError', 'TypeError', 'URIError', 'eval', 'Math', 
+         'Enumeration', 'Variant', 'QObject', 'QMetaObject']
+    
+    def __init__(self, edit):
+         PythonHighlighter.__init__(self,  edit)
+
+
+    def updateRules(self):
+    
+        self.rules = []
+        self.rules += map(lambda s: (QtCore.QRegExp(r"\b"+s+r"\b"),
+                          self.keywordFormat), self.keywords)
+
+        self.rules.append((QtCore.QRegExp(r"\b[A-Za-z_]+\(.*\)"), self.callableFormat))
+        #self.rules.append((QtCore.QRegExp(r"\b__[a-z]+__\b"), self.magicFormat))
+        self.rules.append((QtCore.QRegExp(r"\bthis\b"), self.selfFormat))
+        self.rules.append((QtCore.QRegExp(r"\bQ([A-Z][a-z]*)+\b"), self.qtFormat))
+        
+        self.rules.append((QtCore.QRegExp(r"//[^\n]*"), self.singleLineCommentFormat))
+        
+        # XXX quick hack to support QtScript syntax
+        self.multiLineStringBegin = QtCore.QRegExp(r'/\*')
+        self.multiLineStringEnd = QtCore.QRegExp(r'\*/')
+        self.multiLineStringFormat = self.singleLineCommentFormat
+        self.rules.append((QtCore.QRegExp(r'\"[^\n]*\"'), self.quotationFormat1))
+        self.rules.append((QtCore.QRegExp(r"'[^\n]*'"), self.quotationFormat2))
+    

File codeaide/modes/emacs.py

+from codeaide.base import *
+
+
+class EmacsBase(ModeBase):
+
+    """
+    mode
+    find_file
+    find_file_other_window
+    find_alternate_file
+    save_buffer
+    save_some_buffers
+    write_file
+    not_modified
+    set_visited_filename
+    revert_buffer
+    recover_file
+    list_directory
+    view_file
+    insert_file
+    write_region
+    dlete_file
+    rename_file
+    copy_file
+    make_symbolic_link
+
+    set_fill_column
+    fill_paragraph
+    fill_region
+    fill_region_as_paragraph
+    center_line
+    set_fill_prefix
+    
+    switch_to_buffer
+    switch_to_buffer_other_window
+    save_buffer
+    save_some_buffers
+    save_some_buffers_without_verfication
+    write_file
+    rename_buffer
+    toggle_read_only
+    kill_bufer
+    kill_some_buffers
+    narrorw_to_region
+    widen
+    view_buffer
+    insert_buffer
+    append_to_buffer
+    prepend_to_buffer
+    copy_to_buffer
+    append_to_file
+    revert_buffer
+    print_buffer
+    print_region
+
+
+    buffer_menu
+      next_line
+      buffer_menu_mark
+      buffer_menu_select
+      buffer_menu_1_window
+      buffer_menu_2_window
+      buffer_menu_this_window
+      buffer_menu_other_window
+      buffer_menu_not_modified
+      buffer_menu_delete
+      buffer_menu_delete_backwards
+      buffer_menu_save
+      buffer_menu_execute
+      buffer_menu_unmark
+      bufer_menu_backup_unmark
+
+
+    downcase_word
+    downcase_previous_word
+    upcase_word
+    upcase_previous_word
+    capitalize_word
+    capitalize_previous_word
+    downcase_region
+    upcase_region
+
+
+    backward_char
+    forward_char
+    begging_of_line
+    end_o_line
+    beginning_of_buffer
+    end_of_buffer
+    goto_line
+    previous_line
+    next_next
+    set_goal_column
+    unset_goal_column
+    backward_word
+    forward_word
+    backward_sentence
+    forward_sentence
+    backward_paragraph
+    forward_paragraph
+    sort_paragraphs
+    backward_page
+    forward_page
+    move_to_window_line
+    goto_char
+
+
+    delete_backward_char
+    delete_char
+    delete_blank_lines
+    delete_horizontal_space
+    just_one_space
+    delete_indention
+    
+    kill_line
+    kill_region
+    backward_kill_word
+    kill_word
+    backward_kill_sentence
+    kill_sentence
+    zap_to_char
+    copy_region_as_kill
+    append_next_kill
+    yank
+    yank-pop
+
+    what_cursor_position
+    what_line
+    count_lines_region
+    what_page
+    count_lines_page
+
+    dired
+      dired_other_window
+      dired_previous_line
+      dired_next_line
+      revert_buffer
+      dired_backup_unflag
+      dired_flag_file_deleted
+      dired_unflag
+      dired_to_deletions
+      dired_flag_auto_save_files
+      dired_flag_backup_files
+      dired_clean_directory
+      dired_find_file
+      dired_find_file_other_iwindow
+      dired_view_file
+      dired_copy_file
+      dired_rename_file
+      dired_print_file
+      dired_compress
+      dired_uncompress
+      dired_chmod
+      dired_chown
+      dired_chgrp
+      
+    scroll_up
+    scroll_down
+    recenter
+    scroll_left
+    scroll_right
+    set_selective_display
+    split_window_vertically
+    split_window_horizontally
+    scroll_other_window
+    delete_other_windows
+    kill_window
+    enlarge_window
+    enlarge_window_horizontally
+    compare_windows
+    
+    command_apropos
+    describe_keybindings
+    describe_key_briefly
+    describe_function
+    info
+    describe_key
+    view_lossage
+    describe_mode
+    view_emacs_news
+    describe_syntax
+    help_with_tutorial
+    describe_variable
+    where_is
+
+    set_variable
+    #make_local_variable
+    #kill_local_variable
+    #make_varible_buffer_local
+    customize
+    customize-option
+
+    indent_for_tab_command
+    tab_to_tab_stop # / c_indent_line / lisp_indent_line / ...
+    quoted_insert
+    newline_and_indent
+    open_line
+    delete_indention
+    split_line
+    back_to_indention
+    indent_region
+    indent_rigitly
+    edit_tab_stops
+    indent_relative
+    untabify
+    tabify
+    # indent_c_exp
+    
+    global_set_key
+    local_set_key
+    disable_command
+
+    repeat_complex_command
+    previous_complex_command
+    next_complex_command
+    list_command_history
+    
+    minibuffer_complete_and_xit
+    minibuffer_complete_word
+    minibuffer_complete
+    minibuffer_completition_help
+
+
+    clear_rectangle
+    delete_rectangle
+    kill_rectangle
+    yank_rectangle
+    open_rectangle
+    copy_region_to_rectangle
+    insert_register
+
+    set_mark_command
+    exchange_point_and_mark
+    mark_word
+    mark_page
+    mark_paragraph
+    mark_whole_buffer
+
+    point_to_register
+    copy_to_register
+    insert_register
+    copy_register_to_rectangle
+    copy_region_to_rectangle
+    view_register
+
+    isearch_forward
+    isearch_backward
+    isearch_forward_regexp
+    isearch_backward_regexp
+    search_forward
+    search_backward
+    word_search_forward
+    word_search_backward
+    re_search_forward
+    re_search_backward
+    query_replace
+    query_replace_regexp
+    replace_string
+    replace_regexp
+    set_mark_command
+    occur
+    occur_mode_goto_occurence
+    count_matches
+    delete_non_matching_lines
+    delete_matching_lines
+
+    shell_command
+    shell_command_on_region
+    shell
+    shell_send_input
+    shell_send_eof
+    shell_kill_input
+    interrupt_shell_job
+    stop_shell_subjob
+    quit_shell_subjob
+    kill_output_from_shell
+    show_output_from_shell
+    copy_last_shell_input
+
+    sort_lines
+    sort_fields
+    sort_numeric_fields
+    sort_columns
+    sort_paragraphs
+    sort_pages
+
+    spell_word
+    spell_string
+    spell_region
+    spell_buffer
+    ispell_word
+    ispell_region
+    ispell_buffer
+
+    transpose_chars
+    transpose_words
+    transpose_lines
+
+    undo
+    keyboard_quit # C-g
+    # abort_recursive_edit
+    # top_level
+    
+
+
+    
+    doctor
+    """

File codeaide/modes/occurrences.py

         cursor.select(QTextCursor.WordUnderCursor)
         word = unicode(cursor.selectedText())
         if not word or not is_word(word):
+            self.textedit.remove_extra_selections(self.selections)
+            self.selections = []
             return
         self.highlight_word(word)
 

File codeaide/modes/python.py

+from codeaide.base import *
+
+from ._simple_highlighter import PythonHighlighter
+
+
+
+class Python(ModeBase):
+
+
+    def init(self):
+        self.highlighter = PythonHighlighter(self.textedit)

File codeaide/widget.py

                  selection_color="white",
                  selection_background="#437DCD",
                  font_name="Monospace",
-                 font_size=10,
+                 font_size=11,
                  line_number_color="#866D71",
                  line_number_background="#E1E1E1",
                  highlight_line_background="#E4EDF8",
 
 
 
+class Buffer(object):
+
+    killring = []
+    registers = []
+
+
+    def __init__(self, filename="", doc=None):
+        self.filename = filename
+        self.doc = doc or QTextDocument()
+
+
+
 class CodeAide(QPlainTextEdit):
 
 
         self.idle_timer_id = self.startTimer(2000)
         self.visible_blocks = []
         self.extra_selections = []
+        self.buffer = Buffer(filename="*scratch*", doc=self.document())
         self.connect(
             self, SIGNAL("blockCountChanged(int)"), self.on_blocks_changed)
         self.connect(self.verticalScrollBar(),
              selection-color: %(selection_color)s;
              selection-background-color: %(selection_background)s;
         }""" % scheme
+        print css
         self.setStyleSheet(css)
+        font = self.font()
+        font.setFamily(scheme.font_name)
+        font.setPointSize(scheme.font_size)
+        self.setFont(font)
         self.fm = self.fontMetrics()
         self.scheme = scheme
 
         h = self._keyboard_hooks = dict()
         for state in [self.state, -1]:
             for keys, callbacks in self.keyboard_hooks.get(state, {}).items():
-                print keys
                 h.setdefault(keys, []).extend(callbacks)
 
 

File test_editor.py

 import codeaide.modes
 
 
-codeaide.modes.load_all(verbose=True)
+codeaide.modes.load_all(verbose=False)
 
 
 
         "Snippets",
         "TextCompleter",
         "Occurrences",
+        "Python",
         )
     edit.resize(800,600)
+
+    def test(*args):
+        print "triggered", args
+    from PyQt4.QtGui import QAction, QKeySequence
+    a = QAction(edit)
+    a.setShortcut(QKeySequence("Ctrl+B,A"))
+    a.connect(a, SIGNAL("triggered(bool)"), test)
+    a.setShortcutContext(Qt.WidgetWithChildrenShortcut)
+    print a.shortcutContext()
+    edit.addAction(a)
+    print edit.actions()
+    
     edit.show()
     src = open(__file__).read()
     edit.setPlainText(src)
-
     app.exec_()