[[KOReader]] supports a user patch system that allows modifying or extending its behavior without editing the source code directly. Patches survive application updates (unlike direct file edits) and can be safely removed at any time.
Patches are [[Lua]] scripts placed in the `koreader/patches/` directory on the device. On each startup, [[KOReader]] scans this folder and executes the scripts in order.
## When do patches run?
The **first digit** of the filename controls when the patch runs:
| Prefix | Timing |
|---|---|
| `0-` | Very early, only once after an update |
| `1-` | Very early, every start |
| `2-` | After UIManager is ready (most common) |
| `3-7` | Reserved |
| `8-` | Before exit, before settings are saved |
| `9-` | Right before exit |
Patches with the same first digit run in natural sort order.
```
<digit><number>-<descriptive-name>.lua
```
## Developing a Patch
Patches are standard Lua with full access to KOReader's module system. The typical pattern is **monkey-patching**: requiring an existing module and wrapping its functions.
```lua
-- Require the module you want to modify
local SomeModule = require("apps/reader/modules/somefile")
-- Wrap an existing function
local orig_function = SomeModule.someFunction
SomeModule.someFunction = function(self, ...)
-- Custom behavior before
local result = orig_function(self, ...)
-- Custom behavior after
return result
end
```
### Key Techniques
- **Wrapping functions**: save a reference to the original, replace it with a new function that calls the original plus your additions
- **Injecting into tables**: modules often expose configuration tables (like `default_settings` or `textGeneratorMap`) that can be modified directly
- **Adding menu entries**: wrap `addToMainMenu()` to inject items into existing menus
## Installing
1. Connect the device via USB
2. Navigate to `.adds/koreader/` (on Kobo) or the equivalent KOReader directory
3. Create a `patches/` folder if it doesn't exist
4. Place the `.lua` file inside
5. Eject and reboot the device
## Uninstalling
Delete the `.lua` file from `patches/` and reboot. No other cleanup is needed since patches don't modify any files on disk.