# -*- coding: utf-8 -*-
# Copyright: Damien Elmes <anki@ichi2.net>
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html

"""\
Hooks - hook management and tools for extending Anki
==============================================================================

To find available hooks, grep for runHook and runFilter in the source code.

Instrumenting allows you to modify functions that don't have hooks available.
If you call wrap() with pos='around', the original function will not be called
automatically but can be called with _old().
"""

# Hooks
##############################################################################

_hooks = {}

def runHook(hook, *args):
    "Run all functions on hook."
    hook = _hooks.get(hook, None)
    if hook:
        for func in hook:
            func(*args)

def runFilter(hook, arg, *args):
    hook = _hooks.get(hook, None)
    if hook:
        for func in hook:
            arg = func(arg, *args)
    return arg

def addHook(hook, func):
    "Add a function to hook. Ignore if already on hook."
    if not _hooks.get(hook, None):
        _hooks[hook] = []
    if func not in _hooks[hook]:
        _hooks[hook].append(func)

def remHook(hook, func):
    "Remove a function if is on hook."
    hook = _hooks.get(hook, [])
    if func in hook:
        hook.remove(func)

# Instrumenting
##############################################################################

def wrap(old, new, pos="after"):
    "Override an existing function."
    def repl(*args, **kwargs):
        if pos == "after":
            old(*args, **kwargs)
            return new(*args, **kwargs)
        elif pos == "before":
            new(*args, **kwargs)
            return old(*args, **kwargs)
        else:
            return new(_old=old, *args, **kwargs)
    return repl

@@ -663,16 +663,17 @@
 s = %7B%7D%0A%0A
+%0A
 def runH
@@ -694,16 +694,18 @@
 s):%0A    
+%22%22
 %22Run all
@@ -716,32 +716,34 @@
 ctions on hook.%22
+%22%22
 %0A    hook = _hoo
@@ -745,38 +745,32 @@
  _hooks.get(hook
-, None
 )%0A    if hook:%0A 
@@ -819,16 +819,17 @@
 *args)%0A%0A
+%0A
 def runF
@@ -879,22 +879,16 @@
 get(hook
-, None
 )%0A    if
@@ -971,16 +971,17 @@
 rn arg%0A%0A
+%0A
 def addH
@@ -1001,16 +1001,18 @@
 c):%0A    
+%22%22
 %22Add a f
@@ -1051,24 +1051,26 @@
 dy on hook.%22
+%22%22
 %0A    if not 
@@ -1088,14 +1088,8 @@
 hook
-, None
 ):%0A 
@@ -1181,16 +1181,17 @@
 (func)%0A%0A
+%0A
 def remH
@@ -1211,16 +1211,18 @@
 c):%0A    
+%22%22
 %22Remove 
@@ -1247,16 +1247,18 @@
 n hook.%22
+%22%22
 %0A    hoo
@@ -1330,16 +1330,17 @@
 (func)%0A%0A
+%0A
 # Instru
@@ -1427,16 +1427,17 @@
 ######%0A%0A
+%0A
 def wrap
@@ -1465,16 +1465,18 @@
 %22):%0A    
+%22%22
 %22Overrid
@@ -1499,16 +1499,19 @@
 nction.%22
+%22%22%0A
 %0A    def
@@ -1751,16 +1751,16 @@
   else:%0A
-
         
@@ -1797,24 +1797,25 @@
 , **kwargs)%0A
+%0A
     return r

remove redundant none. partial pep-8