elixir-writing-docs
Skill91 starsChanged 4 days agoApache-2.0View on GitHub
Guides writing Elixir documentation with @moduledoc, @doc, @typedoc, @spec, doctests, cross-references, and metadata. Use when adding or improving documentation in .ex files.
In this repository85 other files it gives its agents.
- AGENTS.mdAGENTS.md
- llms.txtllms.txt
- agent-architecture-analysisSkill
- app-intents-code-reviewSkill
- artifact-analysisSkill
- axum-code-reviewSkill
- brainstorm-beagleSkill
- bubbletea-code-reviewSkill
- cloudkit-code-reviewSkill
- elixir-performance-reviewSkill
- elixir-security-reviewSkill
- exdoc-configSkill
- exunit-code-reviewSkill
- fastapi-code-reviewSkill
- fetch-pr-feedbackSkill
- ffi-code-reviewSkill
- fix-llm-artifactsSkill
- fowler-refactoringSkill
- gen-test-planSkill
- go-architectSkill
- go-code-reviewSkill
- go-data-persistenceSkill
- go-testing-code-reviewSkill
- healthkit-code-reviewSkill
- humanize-beagleSkill
- improve-docSkill
- ios-animation-code-reviewSkill
- liveview-code-reviewSkill
- llm-artifacts-detectionSkill
- llm-judgeSkill
- macros-code-reviewSkill
- phoenix-code-reviewSkill
- postgres-code-reviewSkill
- prfaq-beagleSkill
- prometheus-go-code-reviewSkill
- pytest-code-reviewSkill
- quick-planSkill
- react-flow-code-reviewSkill
- react-flowSkill
- react-router-code-reviewSkill
- react-router-v7Skill
- receive-feedbackSkill
- refactor-repoSkill
- resolve-beagleSkill
- respond-pr-feedbackSkill
- review-ai-writingSkill
- review-elixirSkill
- review-frontendSkill
- review-goSkill
- review-iosSkill
- review-llm-artifactsSkill
- review-planSkill
- review-pythonSkill
- review-remix-v2Skill
- review-rustSkill
- review-skillSkill
- review-structureSkill
- review-tuiSkill
- review-verification-protocolSkill
- run-test-planSkill
- The first 60 shown.
The file
We split this skill into the rules it gives an agent
10 rules. About 0 are common, 1 is distinctive, and 9 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈1
Distinctive · estimate
This author's own choices. Worth a look.
9
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 90
Use second-level headings (##) only.
- Distinctive: line 94
When defining a behaviour, document the expected callbacks:
- Very specific: line 155
Document each option in a bulleted ## Options section when the function accepts a keyword list.
- Very specific: line 156
Place @spec between @doc and def.
- Very specific: line 161
Document custom types defined with @type or @opaque:
- Very specific: line 186
Avoid overly broad term(), any(), or untyped list() when concrete domain types (User.t(), [User.t()], {:ok, t()} | {:error, reason()}) are …
- Very specific: line 187
Use String.t() instead of binary() for UTF-8 text to communicate intent in ExDoc.
- Very specific: line 257
Do NOT use
@doc falseon genuinely public functions: If a function is exported and callers depend on it, document it. - Very specific: line 288
Doctests added or changed?: Run the project’s doctest verification (usually mix test for affected modules or the full suite).
- Very specific: line 289
Cross-references, backticks, or
m:links added or edited?: Run mix docs. Pass: the command completes.
≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Elixir Writing Docs
Quick Reference
| Topic | Reference |
| Doctests: syntax, gotchas, when to use | references/doctests.md |
| Cross-references and linking syntax | references/cross-references.md |
| Admonitions, formatting, tabs | references/admonitions-and-formatting.md |
First-Line Summary Rule
ExDoc and tools like mix docs extract the first paragraph of @moduledoc and @doc as a summary. Keep the opening line concise and self-contained.
# GOOD - first line works as a standalone summary
@moduledoc """
Handles payment processing through Stripe and local ledger reconciliation.
Wraps the Stripe API client and ensures each charge is recorded in the
local ledger before returning a confirmation to the caller.
"""
# BAD - first line is vague, forces reader to continue
@moduledoc """
This module contains various functions related to payments.
It uses Stripe and also updates the ledger.
"""The same rule applies to @doc:
# GOOD
@doc """
Charges a customer's default payment method for the given amount in cents.
Returns `{:ok, charge}` on success or `{:error, reason}` when the payment
gateway rejects the request.
"""
# BAD
@doc """
This function is used to charge a customer.
"""@moduledoc Structure
A well-structured @moduledoc follows this pattern:
defmodule MyApp.Inventory do
@moduledoc """
Tracks warehouse stock levels and triggers replenishment orders.
This module maintains an ETS-backed cache of current quantities and
exposes functions for atomic stock adjustments. It is designed to be
started under a supervisor and will restore state from the database
on init.
## Examples
iex> {:ok, pid} = MyApp.Inventory.start_link(warehouse: :east)
iex> MyApp.Inventory.current_stock(pid, "SKU-1042")
{:ok, 350}
## Configuration
Expects the following in `config/runtime.exs`:
config :my_app, MyApp.Inventory,
repo: MyApp.Repo,
low_stock_threshold: 50
"""
endKey points:
- First paragraph is the summary (one to two sentences).
## Examplesshows realistic usage. Use doctests when the example is runnable.## Configurationdocuments required config keys. Omit this section if the module takes no config.- Use second-level headings (
##) only. First-level (#) is reserved for the module name in ExDoc output.
Documenting Behaviour Modules
When defining a behaviour, document the expected callbacks:
defmodule MyApp.PaymentGateway do
@moduledoc """
Behaviour for payment gateway integrations.
Implementations must handle charging, refunding, and status checks.
See `MyApp.PaymentGateway.Stripe` for a reference implementation.
## Callbacks
* `charge/2` - Initiate a charge for a given amount
* `refund/2` - Refund a previously completed charge
* `status/1` - Check the status of a transaction
"""
@callback charge(amount :: pos_integer(), currency :: atom()) ::
{:ok, transaction_id :: String.t()} | {:error, term()}
@callback refund(transaction_id :: String.t(), amount :: pos_integer()) ::
:ok | {:error, term()}
@callback status(transaction_id :: String.t()) ::
{:pending | :completed | :failed, map()}
end@doc Structure
@doc """
Reserves the given quantity of an item, decrementing available stock.
Returns `{:ok, reservation_id}` when stock is available, or
`{:error, :insufficient_stock}` when the requested quantity exceeds
what is on hand.
## Examples
iex> MyApp.Inventory.reserve("SKU-1042", 5)
{:ok, "res_abc123"}
iex> MyApp.Inventory.reserve("SKU-9999", 1)
{:error, :not_found}
## Options
* `:warehouse` - Target warehouse atom. Defaults to `:primary`.
* `:timeout` - Timeout in milliseconds. Defaults to `5_000`.
"""
@spec reserve(String.t(), pos_integer(), keyword()) ::
{:ok, String.t()} | {:error, :insufficient_stock | :not_found}
def reserve(sku, quantity, opts \\ []) do
# ...
endGuidelines:
- State what the function does, then what it returns.
- Document each option in a bulleted
## Optionssection when the function accepts a keyword list. - Place
@specbetween@docanddef. This is the conventional ordering. - Include doctests for pure functions. Skip them for side-effecting functions (see references/doctests.md).
@typedoc, @spec, and Dialyzer Precision
Document custom types defined with @type or @opaque:
@typedoc """
A positive integer representing an amount in the smallest currency unit (e.g., cents).
"""
@type amount :: pos_integer()
@typedoc """
Reservation status returned by `status/1`.
* `:held` - Stock is reserved but not yet shipped
* `:released` - Reservation was cancelled and stock restored
* `:fulfilled` - Items have shipped
"""
@type reservation_status :: :held | :released | :fulfilled
@typedoc """
Opaque handle returned by `connect/1`. Do not pattern-match on this value.
"""
@opaque connection :: %__MODULE__{socket: port(), buffer: binary()}@spec & Dialyzer vs Elixir 1.17–1.18 gradual types:
- Note that Elixir 1.17–1.18's gradual set-theoretic type system checks patterns, guards, structs, and calls from inferred types and does not consume
@specattributes, whereas Dialyzer and ExDoc rely on@spec/@type/@opaque. - Avoid overly broad
term(),any(), or untypedlist()when concrete domain types (User.t(),[User.t()],{:ok, t()} | {:error, reason()}) are known, and include all union return branches (e.g.| nilor{:error, :not_found}). - Use
String.t()instead ofbinary()for UTF-8 text to communicate intent in ExDoc. - Declare
@opaquewhen internal struct/tuple fields must not leak into caller pattern matches, and pair@opaquewith a@typedocexplaining intended usage.
Metadata
@doc since and @doc deprecated
@doc since: "1.3.0"
@doc """
Transfers stock between two warehouses.
"""
def transfer(from, to, sku, quantity), do: # ...
@doc deprecated: "Use transfer/4 instead"
@doc """
Moves items between locations. Deprecated in favor of `transfer/4`
which supports cross-region transfers.
"""
def move_stock(from, to, sku, quantity), do: # ...You can combine metadata and the docstring in one attribute:
@doc since: "2.0.0", deprecated: "Use bulk_reserve/2 instead"
@doc """
Reserves multiple items in a single call.
"""
def batch_reserve(items), do: # ...@moduledoc since: works the same way for modules:
@moduledoc since: "1.2.0"
@moduledoc """
Handles webhook signature verification for Stripe events.
"""When to Use @doc false / @moduledoc false
Suppress documentation when the module or function is not part of the public API:
# Private implementation module — internal to the application
defmodule MyApp.Inventory.StockCache do
@moduledoc false
# ...
end
# Protocol implementation — documented at the protocol level
defimpl String.Chars, for: MyApp.Money do
@moduledoc false
# ...
end
# Callback implementation — documented at the behaviour level
@doc false
def handle_info(:refresh, state) do
# ...
end
# Helper used only inside the module
@doc false
def do_format(value), do: # ...- Avoid
@moduledoc ""(empty string) to hide modules — ExDoc still generates a blank page entry in the sidebar and search results; always use@moduledoc false. - Do NOT use
@doc falseon genuinely public functions. If a function is exported and callers depend on it, document it. If it should not be called externally, make it private withdefp.
Documentation vs Code Comments
Documentation (@moduledoc, @doc) | Code Comments (#) | |
| Audience | Users of your API | Developers reading source |
| Purpose | Contract: what it does, what it returns | Why a particular implementation choice was made |
| Rendered | Yes, by ExDoc in HTML/epub | No, visible only in source |
| Required | All public modules and functions | Only where code intent is non-obvious |
@doc """
Validates that the given coupon code is active and has remaining uses.
"""
@spec validate_coupon(String.t()) :: {:ok, Coupon.t()} | {:error, :expired | :exhausted}
def validate_coupon(code) do
# We query the read replica here to avoid adding load to the
# primary during high-traffic discount events.
Repo.replica().get_by(Coupon, code: code)
|> check_expiry()
|> check_remaining_uses()
endThe @doc tells the caller what validate_coupon/1 does and returns. The inline comment explains an implementation decision that would otherwise be surprising.
Completing documentation (gates)
Finish with these sequenced checks. Skip a step when it does not apply.
- Doctests added or changed? Run the project’s doctest verification (usually
mix testfor affected modules or the full suite). Pass: no doctest failures. - Cross-references, backticks, or
m:links added or edited? Runmix docs. Pass: the command completes; resolve ExDoc warnings about missing modules, callbacks, or bad links. - New or changed public API? Pass: every exported
def/defmacrohas an intentional@docor@doc false, and every public module has@moduledocor@moduledoc false(never@moduledoc ""), consistent with your project’s policy.
When to Load References
- Writing doctests or debugging doctest failures --> references/doctests.md
- Adding links between modules, functions, types --> references/cross-references.md
- Using admonition blocks, tabs, or formatting in docs --> references/admonitions-and-formatting.md
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

