# Heading number in margin using titlesec and/or komascript

Using titlesec and/or komascript how do I format all headings so the number is left aligned in the margin, the title to the right, with a horizontal rule underneath it all (from margin to text width edge).

What's left of my hair is about to come out :(

 _____________________________
|                             |
| 3.1  Section Title          |
| -------------------------   |
|      Text width paragraph   |
|      Blah blah blah blah    |
|                             |

>-<  >------------------<
|                |
-- Margin        Text


Here's one possibility using titlesec:

\documentclass{article}
\usepackage[calcwidth]{titlesec}
\usepackage{lipsum}

\newlength\mylen
\setlength\mylen{\dimexpr\oddsidemargin+1in+\hoffset\relax}

\titleformat{\section}
{\normalfont\Large\bfseries}
{\llap{\hspace*{-\mylen}\thesection\hfill}}{0em}{}
[{\makebox[\linewidth][l]{%
\hspace*{-\mylen}\rule{\dimexpr\textwidth+\mylen\relax}{1pt}}}]

\begin{document}

\section{A Test Section with a Short Title}
\lipsum[4]
\section{A Test Section with a Long Title Spanning More than One Line}
\lipsum[4]

\end{document}


Of course, you can adjust the value for \mylen to get the desired positioning for the numbers; for example, using

\setlength\mylen{\dimexpr\oddsidemargin+\hoffset\relax}


you get

• To understand your answer better, would you kindly elaborate how your solution works (except the rule part)? – blackened Sep 15 '15 at 17:33

Caveat: margin box size for number is not dynamic.

\documentclass[10pt,twoside,letterpaper,openright]{scrbook}
\usepackage{lipsum}
\usepackage{titlesec}
\titleformat{\section}[block]%
{\normalfont\scshape\filright}%
{\makebox[2em][l]{\thesection}}%
{1em}
{}[\titlerule]
\titlespacing{\section}{-3em}{3.5ex plus 1ex minus .2ex}{2.3ex plus .2ex}
\begin{document}
\chapter{Lorem Ipsem}
\section{Lorem Ipsum}
\lipsum[1]
\section{Lorem Ipsum}
\lipsum[1]
\end{document}

• Also consider using \titlespacing*{...} if you wish to prevent the paragraph following the section from being indented. – davidg Dec 13 '13 at 5:22