text:
Conjugation in Real Life
In @Adám's Dyalog APL Extended, the ⍢ (under) operator means conjugation:  apply one function, then a second function, then the inverse of the first. It's fun to think of real-life actions in terms of conjugation:

A problem is transformed by g into another domain where it more
  readily solved by f , and then transformed back into the original
  domain. An example from real life is “under anesthetics”:
apply anesthetics
    perform surgery
wake up from anesthetics

Challenge
The inverse of a line g is "un" prepended to g, and vice versa. Define any line between s and its inverse, in that order, as being "under" s. For each line f in input in order:

If f and its inverse both occur, do nothing
If f is not "under" any other action, print f
If f is "under" a line g, print f + " under " + g where + is concatenation.

Input
A nonempty multiline string, or list of strings, etc., consisting of spaces and lowercase letters (you may instead use uppercase). Exactly one line will begin with "un"; and it will be the inverse of some other line. No line will be empty.
Output
Output in the same format you took input in, or as allowed by Standard I/O.
Test cases:
Input:
apply anesthetics
perform surgery
unapply anesthetics

Output:
perform surgery under apply anesthetics

Input:
unite asia
establish the silk road
ite asia

Output:
establish the silk road under unite asia

Input:
desire a book
walk to store
take the book
pay for the book
unwalk to store
read the book

Output:
desire a book
take the book under walk to store
pay for the book under walk to store
read the book

Input:
drink excessively
undrink excessively

Output:
[empty string]

I, too, have no output when I drink excessively

shouldn't it be "take the book and pay for the book under walk to store"? otherwise it's not clear that the transform is equivalent to the original...

@Jonah The idea is in an ideal world w="walk to store" and w^-1="unwalk to store" are inverses, so mathematically wfw^-1wg^-1 = wfgw^-1.

Ah fair enough, @lirtosiast.

Brachylog, 90 bytes
;Ṡ{hhH↰₂gB&hb~c[A,B,C]&tT;C↔↰U∧" under ",H,T;A↔↰,U|tT&hh,TgJ&hb;T↰Q∧J,Q|h}
~↰₃|↰₃
∧"un";?c

I made this while being under the impression that this could be recursive and multiple unders could be stacked. Probably not optimized. Also as this is bracylog, plumbing takes quite some bytes.
Try it online!

Python 2, 106 bytes
s=input()
x=''
l=[]
for i in s:
 if'un'==i[:2]or'un'+i in s:x=(' under '+i)*(not x)
 else:l+=[i+x]
print l

Try it online!
If the input can be a list from STDIN and the output be newline-separated, we then have this 94-byte solution:
s=input()
x=''
for i in s:
 if'un'==i[:2]or'un'+i in s:x=(' under '+i)*(not x)
 else:print i+x

Retina, 82 bytes
m{A`^(un)?(.+)¶(?(1)|un)\2$
^((un)?(.+)¶)(.+)¶((.+¶)*(?(2)|un)\3)$
$4 under $1$1$5

Try it online! Link includes test cases. Explanation:
m{

Run the whole program in multiline mode (so that ^ and $ match the beginning and end of individual lines) and repeat until there are no changes.
A`^(un)?(.+)¶(?(1)|un)\2$

Look for lines that might begin with un and are followed by a line that begins with un only if the previous line does not while the rest of the line is the same, and delete both lines. (This is a change of behaviour from Retina 0.8.2, which splits the lines before trying to match and therefore can never delete lines if the match needs to span more than one line at once.)
^((un)?(.+)¶)(.+)¶((.+¶)*(?(2)|un)\3)$

Look for lines that might begin with un, followed by at least one line, followed by a line that begins with un only if the original line does not while the rest of the line is the same.
$4 under $1$1$5

Move the original line down one line, and also append it with under to the line just traversed. (Additional lines will be handled by the repeat.)

JavaScript (Babel Node), 91 bytes
Takes input as an array of strings in lowercase. Returns another array of strings.
a=>a.flatMap(s=>s==r|'un'+s==r?(u=u?'':' under '+s,[]):s+u,u='',r=a.find(s=>/^un/.test(s)))

Try it online!
Commented
a =>                     // a[] = input array
  a.flatMap(s =>         // for each string s in a[]:
    s == r |             //   if s matches the reference string
    'un' + s == r ? (    //   or its opposite:
      u =                //     update u:
        u ?              //       if u is not an empty string:
          ''             //         turn it to an empty string
        :                //       else:
          ' under ' + s, //         set it to s with the ' under ' prefix
      []                 //     yield an empty array so that this entry is removed
    ) :                  //   else:
      s + u,             //     yield s followed by u
    u = '',              //   initialize u to an empty string
    r = a.find(s =>      //   initialize r ...
      /^un/.test(s)      //     ... to the string beginning with 'un'
    )                    //
  )                      // end of flatMap()

Fail?

@l4m2 Fail indeed. Now fixed.

Clean, 147 bytes
import StdEnv,Data.List
a=inits;b=tails
$l=hd[w++[e++[' under ':u]\\e<-z]++y\\i<-a l&t<-b l,w<-a i&u<-i,z<-a t&[x:y]<-b t|u==['un':x]||x==['un':u]]

Try it online!

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Make a simple word wrapper
(Note: This is my first ever code golf question, but as far as I can tell, nobody else has done exactly this, so I should be good.)
Your task is to make a program or function that takes in a string s and an integer n, and returns or outputs that text wrapped into multiple lines. Each word must be wholly on a line; i.e. no words split in the middle. Each line can be no longer than n characters long, and you must fit as many words as possible on each line.
Example:
s = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget erat lectus. Morbi mi mi, fringilla sed suscipit ullamcorper, tristique at mauris. Morbi non commodo nibh. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed at iaculis mauris. Praesent a sem augue. Nulla lectus sapien, auctor nec pharetra eu, tincidunt ac diam. Sed ligula arcu, aliquam quis velit aliquam, dictum varius erat."
n = 50

output:
Lorem ipsum dolor sit amet, consectetur adipiscing
elit. Sed eget erat lectus. Morbi mi mi, fringilla
sed suscipit ullamcorper, tristique at mauris.
Morbi non commodo nibh. Pellentesque habitant
morbi tristique senectus et netus et malesuada
fames ac turpis egestas. Sed at iaculis mauris.
Praesent a sem augue. Nulla lectus sapien, auctor
nec pharetra eu, tincidunt ac diam. Sed ligula
arcu, aliquam quis velit aliquam, dictum varius
erat.

Your output can be an array of strings or a single string with line breaks. Also, you can assume no words will be longer than n, so don't worry about dealing with weird cases.
Standard I/O rules apply, and standard loopholes are prohibited. Trailing spaces are allowed.
Since this is code-golf, the shortes solution in bytes wins.
Here is an example program in Python that would work.

Format a list of words

n  is the max line length ? or the length we have to reach before line break ?

Partly related

@david, or the number of lines?

28 bytes Python is it relevant?

part of this

@ATMunn Please edit your rules so a simple split can't be acceptable! 18 bytes split Python

n is the max line length, sorry that that was not clear. I will clarify. Also, the rules have now been updated so a simple split doesn't work.

Corner cases: Lorem ipsum dolor 5 and 17.

Are spaces the only characters that divide words?

@KamilDrakari Yes.

@david It can be 9 bytes by the way.

But is not specified if new line char  is count in the line length... if yes your example has max length line 51 if not one char for line disappear to the final print... I suppose the last I say... for the other answers: you can write this as 0 bytes, this not means it is ok

Are allowed the new line chars in the input string?

Python 2, 26 bytes
from textwrap import*
fill

Try it online!
Meh... built-ins are boring... instead, have a nice 87-byte solution here:
s,n=input()
x=''
for i in s.split():c=n<len(x+i);exec'print x'*c;x=x*-~-c+i+' '
print x

Try it online!
Outputs trailing spaces.

JavaScript (ES6),  75 73  72 bytes
Takes input as (string)(n).
s=>n=>s.split` `.map(w=>r=(u=r?r+' '+w:w)[n]?(o+=r+`
`,w):u,o=r='')&&o+r

Try it online!
Variables
The formatted output is stored in \$o\$ (in green below).
The updated line \$u\$ is defined as the concatenation of:

the current line \$r\$ (in black below)
a space if \$r\$ is not empty, or nothing otherwise (in orange below)
the new word \$w\$ (in blue below)

We need to insert a line break whenever the \$n\$-th character of \$u\$ is set (0-indexed, in red below).
Example
\$n=16\$ and \$s\$ = "LOREM IPSUM DOLOR"
Adding "LOREM":
$$\small\begin{array}{|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|}
\hline
00&01&02&03&04&05&06&07&08&09&10&11&12&13&14&15&\color{red}{16}\\ \hline
\color{blue}L&\color{blue}O&\color{blue}R&\color{blue}E&\color{blue}M&&&&&&&&&&&&\\ \hline\end{array}
$$
Adding "IPSUM":
$$\small\begin{array}{|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|}
\hline
00&01&02&03&04&05&06&07&08&09&10&11&12&13&14&15&\color{red}{16}\\ \hline
L&O&R&E&M&\color{orange}\bullet&\color{blue}I&\color{blue}P&\color{blue}S&\color{blue}U&\color{blue}M&&&&&&\\ \hline\end{array}
$$
Adding "DOLOR":
$$\small\begin{array}{|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|}
\hline
00&01&02&03&04&05&06&07&08&09&10&11&12&13&14&15&\color{red}{16}\\ \hline
L&O&R&E&M&\bullet&I&P&S&U&M&\color{orange}\bullet&\color{blue}D&\color{blue}O&\color{blue}L&\color{blue}O&\color{blue}R\\ \hline\end{array}
$$
$$\small\begin{array}{|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|c|}
\hline
00&01&02&03&04&05&06&07&08&09&10&11&12&13&14&15&\color{red}{16}\\ \hline
\color{green}L&\color{green}O&\color{green}R&\color{green}E&\color{green}M&\color{green}\bullet&\color{green}I&\color{green}P&\color{green}S&\color{green}U&\color{green}M&\color{green}\hookleftarrow&&&&&\\ \hline
D&O&L&O&R&&&&&&&&&&&&\\ \hline\end{array}
$$

Trailing spaces are allowed. maybe r+w+' '?

PHP, 8 bytes
Admittedly not the most original solution, but PHP has a native function that matches your requirements perfectly!
wordwrap:

string wordwrap ( string $str [, int $width = 75 [, string $break = "\n" [, bool $cut = FALSE ]]] )
Wraps a string to a given number of characters using a string break character.

Use like so:
$str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget erat lectus. Morbi mi mi, fringilla sed suscipit ullamcorper, tristique at mauris. Morbi non commodo nibh. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed at iaculis mauris. Praesent a sem augue. Nulla lectus sapien, auctor nec pharetra eu, tincidunt ac diam. Sed ligula arcu, aliquam quis velit aliquam, dictum varius erat.";
echo wordwrap($str, 50);

Or Try it online!

Perl 6, 46 29 bytes
{;*.comb(/.**{1..$_}[\s|$]/)}

Try it online!
Regex based solution that takes input curried, like f(n)(s) and returns a list of lines. Each line except the last has a trailing whitespace
Explanation:
{;*                         }   # Anonymous code block that returns a Whatever lambda
   .comb(/                /)    # Split the string by
          .**{1..$_}            # Up to n characters
                    [\s|$]      # Terminated by a whitespace char or the end of the string

Vim, 15 bytes/keystrokes
DJ:se tw=<C-r>"
gq_

A text formatting question? I know just the tool for the job! And it even has my name in the first two keystrokes :D
<C-r> means ctrl-r.
This could ever so slightly shorter in V, but I prefer answering in vanilla vim for answers that really show off how concise vim can be for the right challenge. And the difference is so small anyway.
This could also be the following for 15 bytes as well:
:se tw=<C-r><C-w>
ddgq_

Try it online!

Explanation: DJ:: This program has been made by DJ, our favorite cat with a diamond around his neck. [...]

R, 36 27 bytes
R has this as a built-in (strwrap), we return a vector of split lines.
function(s,n)strwrap(s,n+1)

Try it online!

Yes, that should be allowed. Arrays of lines are allowed, so I don't see why this would be any different.

Haskell, 70 bytes
s!n|length s<=n=[s]|(t,_:d)<-splitAt(until((<'!').(s!!))pred n)s=t:d!n

Python 2, 74 bytes
s,n=input()
while s:i=n;exec"i-=' '<(s+' '*n)[i];"*n;print s[:i];s=s[i+1:]

Try it online!

Java (JDK), 46 44 bytes
Basically a pure regex solution in Java, almost certainly the shortest I've written.
Cheers to Kevin for helping to cut down the bytes in the regex even further!
n->s->s.replaceAll(".{1,"+n+"}( |$)","$0\n")

Try it online!
Using a curried lamdba, it creates a regex to greedily match up to n characters followed by either a space or end of string. It then replaces those characters with themselves followed by a newline.

@KevinCruijssen [ $] actually just matches a space or $ if I remember correctly, rather than the end of string. It does seem to work though, so it looks like it can just be golfed down to a single space for even fewer bytes.

Ah, it can indeed be just a space, since you add newlines and don't need to add an additional trailing newline at the end.

You can golf 2 more bytes removing the parenthesis in the regex, and use $0 instead of $1.

@KevinCruijssen Nice one! It's just a shame that replaceAll is so verbose!

For me it is wrong, appear if I modify the Latin phrase of the exercise in the way it end with"...dictum varius a b c erat." There is a unnecessary new line after c letter...

@RosLuP Good catch; it seems like it needs the end of String check after all. I've fixed it now.

Japt, 20 bytes
¸rÈ+Yi[X·ÌY]¸Ê>V?R:S

Try it online!
Thanks to Bubbler and Shaggy for their help
Explanation:
¸                       #Split into words
 r                      #For each word, add them to the output in this way:
     i                  # Choose a character using this process:
       X·Ì              #  Get the last line of the output
          Y             #  And the current word
      [    ]¸           #  Join them with a space
             Ê>V?       #  If the resulting line is greater than the allowed length:
                ?R      #   Choose "/n" (newline)
                  :S    #  Otherwise choose " " (space)
     i                  # Add the chosen character to the output
  È+Y                   # Add the current word to the output

24 bytes with [X,Y].join(...).

20 bytes

Powershell, 40 83 bytes
Test case with n=80 added.
param($s,$n)$s-split' '|%{if(($o+$_|% le*)-lt$n){$o+=' '*!!$o+$_}else{$o;$o=$_}}
$o

Test script:
$f = {

param($s,$n)$s-split' '|%{if(($o+$_|% le*)-lt$n){$o+=' '*!!$o+$_}else{$o;$o=$_}}
$o

}

@(
,(50, "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget erat lectus. Morbi mi mi, fringilla sed suscipit ullamcorper, tristique at mauris. Morbi non commodo nibh. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed at iaculis mauris. Praesent a sem augue. Nulla lectus sapien, auctor nec pharetra eu, tincidunt ac diam. Sed ligula arcu, aliquam quis velit aliquam, dictum varius erat.",
"Lorem ipsum dolor sit amet, consectetur adipiscing",
"elit. Sed eget erat lectus. Morbi mi mi, fringilla",
"sed suscipit ullamcorper, tristique at mauris.",
"Morbi non commodo nibh. Pellentesque habitant",
"morbi tristique senectus et netus et malesuada",
"fames ac turpis egestas. Sed at iaculis mauris.",
"Praesent a sem augue. Nulla lectus sapien, auctor",
"nec pharetra eu, tincidunt ac diam. Sed ligula",
"arcu, aliquam quis velit aliquam, dictum varius",
"erat.")
,(80, "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget erat lectus. Morbi mi mi, fringilla sed suscipit ullamcorper, tristique at mauris. Morbi non commodo nibh. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed at iaculis mauris. Praesent a sem augue. Nulla lectus sapien, auctor nec pharetra eu, tincidunt ac diam. Sed ligula arcu, aliquam quis velit aliquam, dictum varius erat.",
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget erat lectus.",
"Morbi mi mi, fringilla sed suscipit ullamcorper, tristique at mauris. Morbi non",
"commodo nibh. Pellentesque habitant morbi tristique senectus et netus et",
"malesuada fames ac turpis egestas. Sed at iaculis mauris. Praesent a sem augue.",
"Nulla lectus sapien, auctor nec pharetra eu, tincidunt ac diam. Sed ligula arcu,",
"aliquam quis velit aliquam, dictum varius erat.")
) | %{
    $n,$s,$expected = $_
    $result = &$f $s $n
    "$result"-eq"$expected"
    # $result   # uncomment this line to dispaly a result
}

Output:
True
True

Consider updating your if/else with the fake ternary

Thanks. The fake ternary is an expression. This script contains a implicit return in the else part and a statement in the then part.

Mathematica, 16 bytes
InsertLinebreaks

Built-in function. Takes a string and an integer as input and returns a string as output.

InsertLinebreaks["string", n]
   inserts newline characters to make no line longer than n characters.

C (gcc), 68 bytes
i;b(s,n,l)char*s,*l;{for(i=n;*++s;i--||(i=l-s+n,*l=10))l=*s-32?l:s;}

Try it online!
Thanks to ceilingcat, save 2 bytes by moving global char*l to parameter.

APL (Dyalog Unicode), 14 bytesSBCS
Infix function; left argument is n, right argument is n.
⎕CY'dfns'⋄wrap

Try it online!
⎕CY copy in the dfns library
⋄ then
wrap[c] use the wrap[n] function
[c] code of that function
[n] notes for that function

Golfed version of wrap, 59 bytesSBCS
{⍺≥≢⍵:⍵⋄(t↑⍵),2↓⎕TC,⍺∇⍵↓⍨t+b⊃⍨t←⊃⌽⍺,g/⍨⍺≥g←⍸(⍺+1)↑b←' '=⍵}

Try it online!
{…} dfn; ⍺ is left argument (width), ⍵ is right argument (string)
 ≢⍵ tally (number of characters) of string
 ⍺≥…: if width is greater than or equal to that, then:
  ⍵ return the string
 ⋄ otherwise:
  ' '=⍵ Boolean mask where blanks are equal to the string
  b← store in b (for blanks)
  (…)↑ take the following number of elements from that:
   ⍺+1 one more than the width
  ⍸ indices where true
  g← store in g (for gaps)
  ⍺≥ Boolean mask where the width is greater than or equal to that
  g/⍨ filter the gap indices by that
  ⍺, append that to the width
  ⊃⌽ pick the last element of that (lit. pick the first of the reversed)
  t← store in t (for take)
  b⊃⍨ use that to pick an element from the mask of blanks
  t+ add that to t
  ⍵↓⍨ drop that many characters from the string
  ⍺∇ recurse on that with the same left left argument
  ⎕TC, append that to the list of terminal control characters (8:HT, 10:NL, 13:CR)
  2↓ drop the first two character from that (leaving just a leading 13:CR)
  (…), append that to the following:
   t↑⍵ the first t characters of the string

JavaScript + HTML + CSS, 117 64 bytes
-53 bytes courtesy of @Neil

n=50
s="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget erat lectus. Morbi mi mi, fringilla sed suscipit ullamcorper, tristique at mauris. Morbi non commodo nibh. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed at iaculis mauris. Praesent a sem augue. Nulla lectus sapien, auctor nec pharetra eu, tincidunt ac diam. Sed ligula arcu, aliquam quis velit aliquam, dictum varius erat."
f=(n,s)=>document.body.innerHTML+=`<tt><p style=width:${n}ch>${s}`
f(n,s)

At least in my browser you can cut this down to (n,s)=>document.body.innerHTML+=`<p style=width:${n}ch><tt>${s}</tt></p>`  for 74 bytes. If you're willing to dig out old versions of Firefox you can save another 8 bytes with (n,s)=>document.body.innerHTML+=`<pre wrap width=${n}>${s}</pre>` .

@Neil Nice use of ch units. Firefox 65 computes 50ch as 500px; Chromium 70 computes 50ch as 400px

This answer is wrong. elit. Sed eget erat lectus. Morbi mi mi, fringilla sed (2nd line) is more than 50 characters. I'm using the newest Chrome.

I was able to tweak my original suggestion to work in Chrome by putting the <p> inside the <tt>.

@Neil Did not get expected result at Chromium. Can you create a plnkr to demonstrate?

https://next.plnkr.co/edit/fT2moRe5qgsxj48p?open=lib%2Fscript.js

Red, 125, 117, 114  112 bytes
func[s n][d: 0 parse s[any[to" "p:" "opt[[to" "| to end]q:(if(-1 - d + index? q)> n[p/1: #"^/"d: index? p])]]]s]

Try it online!

Retina 0.8.2, 37 bytes
.+$
$*
!`(?=\S.*¶(1)+)(?<-1>.)+(?=\s)

Try it online! Takes s and n on separate lines. Explanation:
.+$
$*

Convert n to unary.
(?=\S.*¶(1)+)(?<-1>.)+(?=\s)

Match non-whitespace, then look ahead to n and count it as $#1. Then go back and use a balancing group to match up to n characters followed by whitespace.
!`

Output the matches as a list of lines.

Is there a way in Retina to put the first input in a regex we use with the second input? So something like this: .{1,50}  and $0¶, but where 50 is received as input instead?

@KevinCruijssen In Retina 1 you can probably use an Eval stage to give a similar result, but that's boring, so I didn't bother.

Charcoal, 19 bytes
Ｎθ←Ｆ⪪Ｓ «¿‹⁺ＬιⅈθＭ→⸿ι

Try it online! Link is to verbose version of code. Takes input of n and s on separate lines. Explanation:
Ｎθ

Input n.
←

Move the cursor left one square to balance the right movement from the first iteration of the loop.
Ｆ⪪Ｓ «

Split the string on spaces and loop over the words.
¿‹⁺Ｌιⅈθ

Calculate whether the next word will reach the right edge.
Ｍ→

If it will not then move one square right.
⸿

If it will then start a new line.
ι

Output the word.

JavaScript, 40 bytes
s=>n=>eval(`s.match(/.{1,${n}}( |$)/g)`)

Try it online!

Fail at the end

@l4m2 fixed....

05AB1E, 18 bytes
õs#vDy«g²›i,}yðJ}?

Try it online.
Explanation:
õ                   # Push an empty string "" to the stack
 s                  # Swap to take the (implicit) string input
  #                 # Split it by spaces
   v            }   # For-each `y` over the words:
    D               #  Duplicate the top of the stack
                    #  (which is the empty string in the very first iteration)
     y«             #  Append the current word `y`
       g            #  Get its length
        ²›i }       #  If its lengthy is larger than the second input:
           ,        #   Pop and output the current duplicated value with trailing newline
             yð     #  Push the word `y` and a space " "
               J    #  Join the entire stack together
                 ?  # After the loop, output the last part as well (without newline)

Java 8, 135 bytes
n->s->{String r="",S[]=s.split(" "),t=r;for(int i=0;i<S.length;)if((t+S[i]).length()>n){r+=t+"\n";t="";}else t+=S[i++]+" ";return r+t;}

Try it online.
Explanation:
n->s->{                      // Method with integer & String parameters and String return
  String r="",               //  Result-String, starting empty
         S[]=s.split(" "),   //  Input-String split by spaces
         t=r;                //  Temp-String, starting empty as well
  for(int i=0;i<S.length;)   //  Loop `i` in the range [0, amount_of_words):
    if((t+S[i]).length()>n){ //   If `t` and the word are larger than the integer input:
      r+=t+"\n";             //    Add `t` and a newline to the result
      t="";}                 //    And reset `t` to an empty String
     else                    //   Else:
       t+=S[i++]+" ";        //    Append the word and a space to `t`
                             //    (and then increase `i` by 1 with `i++` for the next word
                             //     of the next iteration)
  return r+t;}               //  Return the result-String appended with `t` as result

Thanks to @Erik the Outgolfer, a golfed version :
Python 3, 94 bytes
def f(t,n):
 while t:i=n+(t[min(len(t)-1,n)]==" "or-t[n-1::-1].find(' '));print(t[:i]);t=t[i:]

Try it online!
# Python 3, 130 bytes
def f(t,n):
 l=[]
 while len(t):
  i=(n-t[:n][::-1].find(' '),n+1)[t[min(len(t)-1,n)]==" "]
  l.append(t[:i])
  t=t[i::]
 return l

Try it online!
Not so golfed version...

Some golfs. (prints to STDOUT, doesn't return).

C# (Visual C# Interactive Compiler), 78 bytes
s=>n=>System.Text.RegularExpressions.Regex.Replace(s,".{1,"+n+"}( |$)","$0\n")

Try it online!
Credit goes to @LukeStevens for coming up with the Java version... Apparently .NET makes you import the RegularExpressions namespace in order to do a replace :(
Here is my original version that splits on the space character and uses LINQ to join them back together:
C# (Visual C# Interactive Compiler), 91 bytes
s=>n=>s.Split(' ').Aggregate((a,w)=>a+(a.Length-a.LastIndexOf('\n')+w.Length>n?'\n':' ')+w)

Try it online!

Jelly, 12 bytes
ḲŒṖK€€ḣ€ƑƇṪY

Try it online!
Unfortunately, this is too slow to work for the provided test case in under a minute over TIO.

C# (.NET Core), 162 bytes
string[]t(string n,int a){var g="";for(int i=0;i++<Math.Floor((double)n.Length/a);)g+=$"^.{{{i*a-1}}}|";return Regex.Split(n,$@"(?n)(?<=({g.Trim('|')})\S*)\s");}}

This function uses a regex which matches the closest whitespace that is near the nth or multiple of nth character and splits the string based on it.
Try it online!
The TIO link is a full program, and the function has a static keyword so the function can be called from main.
Test Regex

This doesn't give the right output for the test case - some lines are longer than 50 characters. You want "before" not "near", and also the splitting at one point must depend on where it was split earlier.

Dart, 112 bytes
f(s,n){var l=[''];s.split(' ').forEach((w){if((l.last+w).length<=n)l.last+=w+' ';else l.add(w+' ');});return l;}

Try it online!

C, 63 bytes
b(a,n)char*a;{while(strlen(a)>n){for(a+=n;*a-32;--a);*a++=10;}}

The function of this exercise b(a,n) would break the line "a" as exercise said,
in the way not change its length (if we see the result as one string) because
change some spaces in \n or new line in place. The input string "a" should have no \n character too in it for b() function (it could have \n in input string for bs())
b(a,n) function would be ok only because the restriction of this exercise,
that impose each word of "a" string has length < n if this is not true, that function can go
to one infinite loop...(very wrong in my way of see so i copy too the function more good because
in that case would return -1 and not would go to one infinite loop; it is bs(a,n) below)I not exclude both functions are bugged...
#define R(x,y) if(x)return y
#define U unsigned
U bs(char*a,U n)
{U c,q,r=1,i,j;
 R(!a||n<1||n++>0xFFFF,-1);
 for(j=c=i=0;;++i,++c)
    {R(i==-1,-1);q=a[i];
     if(q==10)goto l;
     if(c>=n){R(i-j>n,-1);a[i=j]=10;l:c=-1;++r;}
     R(!q,r);
     if(q==32)j=i;
    }
}

result of b() passed on one function that add line lenght each line
Lorem ipsum dolor sit amet, consectetur adipiscing [50]
elit. Sed eget erat lectus. Morbi mi mi, fringilla [50]
sed suscipit ullamcorper, tristique at mauris. [46]
Morbi non commodo nibh. Pellentesque habitant [45]
morbi tristique senectus et netus et malesuada [46]
fames ac turpis egestas. Sed at iaculis mauris. [47]
Praesent a sem augue. Nulla lectus sapien, auctor [49]
nec pharetra eu, tincidunt ac diam. Sed ligula [46]
arcu, aliquam quis velit aliquam, dictum varius [47]
erat. [5]

@ceilingcat ok, above code would make in consideration the \n too... one bug I found with the code was that the last line was not correctly print... why do you not write your C answer as other? It would win on mine because it is more short... for say the true I use the first line(or statement ";") for the check of input only because for me input has to be checked even if that is a little more long; I unsuccessful try to write the function in APL...

@ceilingcat in the last answer, seen that question not say if the input string have or not have to have in it '\n' char and seen that example not has '\n' I suppose input string has no new line character in it...

Only 83 ... Yes I have to see if I gain 3 chars using old function definition...

Just 81 .... .... ....

@ceilingcat 78 the first recursive function... Here compile and the result on string proposed as execise seems ok...

60 bytes

APL(NARS), 48 chars, 96 bytes
{⊃⍵{⍺≥≢⍵:⊂⍵⋄k←1+⍺-' '⍳⍨⌽r←⍺↑⍵⋄(⊂k↑r),⍺∇k↓⍵}⍨⍺+1}

test:
  f←{⊃⍵{⍺≥≢⍵:⊂⍵⋄k←1+⍺-' '⍳⍨⌽r←⍺↑⍵⋄(⊂k↑r),⍺∇k↓⍵}⍨⍺+1}
  s←"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eget erat lectus. Morbi mi mi, fringilla sed suscipit ullamcorper, tristique at mauris. Morbi non commodo nibh. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed at iaculis mauris. Praesent a sem augue. Nulla lectus sapien, auctor nec pharetra eu, tincidunt ac diam. Sed ligula arcu, aliquam quis velit aliquam, dictum varius erat."
  50 f s
Lorem ipsum dolor sit amet, consectetur adipiscing
elit. Sed eget erat lectus. Morbi mi mi, fringilla
sed suscipit ullamcorper, tristique at mauris.
Morbi non commodo nibh. Pellentesque habitant
morbi tristique senectus et netus et malesuada
fames ac turpis egestas. Sed at iaculis mauris.
Praesent a sem augue. Nulla lectus sapien, auctor
nec pharetra eu, tincidunt ac diam. Sed ligula
arcu, aliquam quis velit aliquam, dictum varius
erat.

I don't know in "{⊃⍵{⍺≥≢⍵:⊂⍵⋄..." If it is right ≥ or it is right there >...

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Fully Modular C: Grading
You are a Computer Science professor teaching the C programming language. One principle you seek to impart to the students is modularity. Unfortunately, past classes have tended not to get the message, submitting assignments with the entire program inside main(). Therefore, for this semester you have issued strict modularity guidelines upon which students will be graded.
A subset of C grammar and rules for "well-formed" translation unit are defined below. Code that follows these rules should be valid C89, UNLESS an identifier that is a keyword is used.
Task
You will receive as input a string purportedly containing C code. You may assume that this string contains only spaces, newlines, and the characters abcdefghijklmnopqrstuvwxyz123456789(){},+-*/%;=.
Your code must output the number of points the student's assignment should receive according to the following rubric:

Input is not a valid translation-unit according to the grammar: 0 points
Input follows the grammar but is not "well-formed" according to the rules below: 1 point
Input is a well-formed translation unit but not fully modular: 2 points
Input is a fully modular well-formed translation unit: 3 points

Token definitions

identifier: Any sequence of 1 or more lowercase English letters. If an identifier is a C89 reserved word1, you may optionally return 0 instead of whatever the result would have been ignoring reserved words. You do not have to be consistent about detecting the use of reserved words as identifiers; you may flag them in some instances and let them pass in others.
integer-literal: A sequence of 1 or more of the digits 1-9 (recall that the character 0 is guaranteed not to appear in the input)
Other valid tokens are defined literally in the grammar.
A character must belong to a token if and only if it is not whitespace.
Two consecutive alphanumeric characters must be part of the same token.

EBNF grammar
var-expr = identifier
literal-expr = integer-literal
binary-op = "+" | "-" | "*" | "/" | "%"
binary-expr = expr binary-op expr
paren-expr = "(" expr ")"
call-expr = identifier "(" [ expr ( "," expr )* ] ")"
expr = var-expr | literal-expr | binary-expr | paren-expr | call-expr
assign-stmt = var-expr "=" expr ";"
if-stmt = "if" "(" expr ")" assign-stmt
return-stmt = "return" expr ";"
function-body = ( assign-stmt | if-stmt )* return-stmt
argument-list = [ identifier ( "," identifier )* ]
function-definition = identifier "(" argument-list ")" "{" function-body "}"
translation-unit = function-definition*

Well-formed program requirements

No two function definitions may have the same function name.
No two identifiers in an argument-list may be identical.
No identifier in an argument-list may be identical to a function name (whether from a function-definition or a call-expr).
The identifier in a var-expr must be included in the enclosing function's argument-list.
For a given function, all call-exprs and the function-definition (if any) must agree in number of arguments.

Fully modular

No more than 1 binary operator per function
No more than 1 assignment statement per function
No more than 1 function call per function

Examples (one per line)
Score 0
}}}}}
return 2;
f() { return -1; }
f() {}
f(x,) { return 1; }
f(x) { return 1 }
f(x) { returnx; }
f(x) { return1; }
f() { g(); return 1;}
f() { if(1) return 5; }
f(x) { if(1) if(1) x = 2; return x; }
f(x, y) { x = y = 2; return x; }

Score 1
f(){ return 1; } f(){ return 1; }
g(x, x) { return 1; }
g(f) { return 1; } f() { return 1; }
f(x) { x = write(); x = write(1); return 1; }
f() { return f(f); }
f() { return 1; } g() { return f(234567); }
f() { return(x); }
f() { j = 7; return 5; }

Score 2
f(x,y,zzzzz) { return x + y + zzzzz; }
f(x,a,b) { if(a) x = foo(); if(b) x = bar(); return x; }
f(j) { return g(h( i() / j, i() ), 1) ; }

Score 3
mod(x, y) { return ((x % y)); }
f() { return f(); }
f(c) { if(c) c = g(c) + 2; return c; }
fib(i){return bb(i,0,1);}aa(i,a,b){return bb(i,b,a+b);}bb(i,a,b){if(i)a=aa(i-1,a,b);return a;}

Score 0 or 1
h(auto, auto) { return 1; }

Score 0 or 3
if() { return 1; }

1  Reserved word list: auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void volatile while

May the input string be empty? (If so, I think it should score 3.)

@Arnauld Yes, that's correct.

How are we supposed to check the number of arguments of undeclared functions? Is the 4th example in "Score 1" not well-formed because write was called once with no argument and once with one argument?

@Arnauld Yes, you check that each call to a function which is not defined has the same number of arguments.

I see. Well, this is currently not compatible with my parser, so I'm deleting my answer for now. I may give it another try later.

Should it be well-formed to assign to variables not found in the argument list? The test cases don't cover that, and assign-stmt is currently defined using identifier, not var-expr which is required to be in the argument list.

@Pietu1998 Thanks, fixed. I changed the left side of an assignment to var-expr so this is no longer allowed by the spec.

What about the binary operators &&, ||, &, | and ^

@Rogem The characters &|^ are guaranteed not to appear in the input.

Also, suggest adding the empty program as a test case.

JavaScript (ES6), 599 598 593 581 580 576 574 593 591 579 565 563 562 524 521 515 513 511 506 503 502 bytes
After over 3 years I finally noticed "some" further golfs. I also found an edge case while re-golfing… +19 bytes. Sigh. That helped me notice a 38 byte golf. :P
M=p=>(P=I[i++])==p&&7
J=_=>/^[a-z]+$/.test(R=P)*7
O=(Z,a,n=R)=>M`)`?(L[n]|=2)&1|U[n]-(U[n]=a)?1:7:(a++?P==",":i--)&&Z()&O(Z,a,n)
E=_=>(M`(`?E()&M`)`:P-~P?7:J()&(M`(`?O(E,!++z):A[i--,R]|1))&(/[+*/%-]/.test(I[i])?E(++y+i++):7)
S=_=>M`return`?E()&M`;`&M`}`&((x|y|z)>1?3:7):P&&(P=="if"?M`(`&E()&M`)`+M():7)&J()&(A[R]|1)&M`=`&E()&M`;`&S(++x)
Q=_=>M()||J(A={})&(L[F=R]&5?1:7)&M`(`&O(_=>J(M())&(A[R]|(L[R]|=1)&6?1:A[R]=7),x=y=z=0)&M`{`&S()&Q(L[F]=6)
f=c=>Math.log2(Q(U={},L={},i=0,I=c.match(/\w+|\S/g)||[])+1)

Try it online! (comes with test cases)
Defines a function f that takes the code as argument.
Explanation
This monstrosity is essentially a huge recursive bitwise AND, which somehow happens to work as a parser for this C subset. Scores are stored as 0137 for 0123 respectively and converted in the end as log2(score+1); if any phase detects a problem in the code, it returns a score lower than 7, which in turn unsets bits from the final output and results in a lower score. All functions return a score.
If the code runs out of input, it will just continue happily reading undefineds from the token array. This is fine, since the only function that matches undefined is J, and anything will eventually finish recursing and return 0 due to not matching a closing }. (Except for S and Q which have explicit checks for end of input.)
// Globals:
//   I = input tokens
//   i = input position
//   P = last token consumed
//   R = last identifier consumed
//   x,y,z = number of assignments, binary ops, func calls
//   A = current function args
//   F = current function name
//   L = used identifiers as bitfields: 1=argument, 2=call, 4=definition
//   U = function arg counts

// M(p): Consume a token, store it in P, return 7 if P == p, otherwise false (0).
M = p => (P = I[i++]) == p && 7
// J(): Copy P to R, return 7 if valid identifier, otherwise 0.
J = _ => /^[a-z]+$/.test(R = P) * 7
// O(Z, 0): Parse args for R() using the function Z.
O = (Z, a, n = R) =>  // a = arg count, n = name of function (for nested calls)
  M`)` ?              // consume token, is it ")"?
    (L[n] |= 2)         // if yes, mark n() as a called function
    & 1                 // and see if n has been used as an arg
    | U[n] - (U[n] = a) // see if n() already has a different arg count, store new count
    ? 1 : 7             // if yes to either, cap score at 1
  :                   // token wasn't ")"
    (a++                // increment arg count, is this first arg?
    ? P == ","            // if not, truthy only if token was ","
    : i--)                // else, push token back & be truthy
    && Z()              // if truthy, parse the actual arg
    & O(Z,a,n)          // and recurse
// E(): Parse expression.
E = _ =>
                      // first, parse a primary expression:
  (M`(`                 // consume token, is it "("?
  ? E() & M`)`            // if yes, parse expr + ")"
  : P-~P ?              // else, is it numeric?
  7                       // if yes, it's a valid primary expr
  :                     // else,
  J() &                   // parse identifier into R
  (M`(`                   // consume token, is it "("?
  ? O(E, !++z)              // if yes, parse args for R()
  : A[i--, R] | 1)          // else, push token back and see if R is a valid variable
  ) & (               // now, handle infix operators:
  /[+*/%-]/.test(I[i])  // is the next token an operator?
  ? E(++y + i++)          // if yes, consume & parse another expr
  : 7)                    // else, we're done

// S(): Parse statement.
S = _ =>
  M`return` ?                // consume token, is it "return"?
  E() & M`;` & M`}`            // if yes, parse expr + expect ";}"
  & ((x | y | z) > 1 ? 3 : 7)  // and check modularity
  : P &&                     // else, if EOF, return undefined
  (P == "if"                 // else, is it "if"?
  ? M`(` & E() & M`)`          // if yes, parse "(" + expr + ")"
  + M()                        // and consume another token to P
  :                          // else,
  7)                           // just a normal assignment
  & J()                      // parse identifier into R
  & (A[R] | 1)               // check if R is a valid variable
  & M`=` & E() & M`;`        // parse "=" + expr + ";"
  & S(++x)                   // parse next statement

// Q(): Parse function.
Q = _ =>
  M() ||          // consume token, return undefined if EOF
  J(A = {})       // parse identifier into R
  & (L[F = R] & 5 ? 1 : 7)  // see if it's been used as arg or defined
  & M`(`          // expect "("
  & O(_ =>        // parse arg list with O(), name parsing func:
    J(M()) &        // consume & parse identifier into R
    (A[R] |         // see if R is already in this func's args
    (L[R] |= 1)     // mark R as a used arg name
    & 6             // see if R() is a called or defined func
    ? 1             // if yes to either, cap score to 1
    : A[R] = 7),    // else, add R to this func's args
  x = y = z = 0)  // reset modularity counters
  & M`{` & S()    // parse "{" + statement(s)
  & Q(L[F] = 6)   // parse next function, mark F() as defined

// f(c): Parse & score code c.
f = c =>
  Math.log2(Q(
    U = {}, L = {}, i = 0,
    I = c.match(/\w+|\S/g) || [])  // C lexer (:D)
  + 1)

Some of my favorites:

(L[n]|=2)&1|U[n]-(U[n]=a)?1:7 simultaneously exploits undefined, NaN and left-to-right evaluation order
There turned out to be a shorter "is numeric" check than x==+x, when used only as truthy/falsy: x-~x.


text:
Computer Cipher
Introduction:
I have loads of different ciphers stored in a document I once compiled as a kid, I picked a few of the ones I thought were best suitable for challenges (not too trivial, and not too hard) and transformed them into challenges. Most of them are still in the sandbox, and I'm not sure yet whether I'll post all of them, or only a few. But here is the first of them to start things of.

A Computer Cipher will encipher the given text into 'random' character groups of a given length. If such a group contains a digit, it will use that digit to index into its own group for the enciphered character. If no digit is present in the group, it means the first character is used.
For example, let's say we want to encipher the text this is a computer cipher with a given length of 5. This is a potential output (note: numbers are 1-indexed in the example below):
t     h     i     s     i     s     a     c     o     m     p     u     t     e     r     c     i     p     h     e     r       (without spaces of course, but added as clarification)
qu5dt hprit k3iqb osyw2 jii2o m5uzs akiwb hwpc4 eoo3j muxer z4lpc 4lsuw 2tsmp eirkr r3rsi b5nvc vid2o dmh5p hrptj oeh2l 4ngrv   (without spaces of course, but added as clarification)

Let's take a few groups as examples to explain how to decipher the group:

qu5dt: This group contains a digit 5, so the (1-indexed) 5th character of this group is the character used for the deciphered text: t.
hprit: This group contains no digits, so the first character of this group is used implicitly for the deciphered text: h.
osyw2: This groups contains a digit 2, so the (1-indexed) 2nd character of this group is the character used for the deciphered text: s.

Challenge:
Given an integer length and string word_to_encipher, output a random enciphered string as described above.
You only have to encipher given the length and word_to_encipher, so no need to create a deciphering program/function as well. I might make a part 2 challenge for the deciphering in the future however.
Challenge rules:

You can assume the length will be in the range [3,9].
You can assume the word_to_encipher will only contain letters.
You can use either full lowercase or full uppercase (please state which one you've used in your answer).
Your outputs, every group, and the positions of the digits in a group (if present) should be uniformly random. So all random letters of the alphabet have the same chance of occurring; the position of the enciphered letter in each group has the same chance of occurring; and the position of the digit has the same chance of occurring (except when it's the first character and no digit is present; and it obviously cannot be on the same position as the enciphered character).
You are also allowed to use 0-indexed digits instead of 1-indexed. Please state which of the two you've used in your answer.
The digit 1 (or 0 when 0-indexed) will never be present in the output. So b1ndh is not a valid group to encipher the character 'b'. However, b4tbw is valid, where the 4 enciphers the b at the 4th (1-indexed) position, and the other characters b,t,w are random (which coincidentally also contains a b). Other possible valid groups of length 5 to encipher the character 'b' are: abcd2, ab2de, babbk, hue5b, etc.

General rules:

This is code-golf, so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
Standard rules apply for your answer with default I/O rules, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
Default Loopholes are forbidden.
If possible, please add a link with a test for your code (i.e. TIO).
Also, adding an explanation for your answer is highly recommended.

Test cases:
Input:
 Length:           5
 Word to encipher: thisisacomputercipher
Possible output:
 qu5dthpritk3iqbosyw2jii2om5uzsakiwbhwpc4eoo3jmuxerz4lpc4lsuw2tsmpeirkrr3rsib5nvcvid2odmh5phrptjoeh2l4ngrv

Input:
 Length:           8
 Word to encipher: test
Possible output:
 ewetng4o6smptebyo6ontsrbtxten3qk

Input:
 Length:           3
 Word to encipher: three
Possible output:
 tomv3h2rvege3le

How does "uniform" mean

@l4m2 That there is an equal chance for any output. So all random letters of the alphabet have the same chance of occurring; the position of the enciphered letter in each group has the same chance of occurring; and the position of the digit has the same chance of occurring (except when it's the first character and no digit is present, and also not on the same position as the enciphered character).

So abcd2, ab2de, babbk all same? Also is b1akk valid?

@l4m2 Yep, all three are possible outputs enciphering the character 'b'. As for b1akk I'd say no. Will edit it in the challenge description to clarify. If the first character is the enciphered one, no digit should be present.

@KevinCruijssen If both abbc2 and abbc3 are valid encodings for b, are answers required to generate both with uniform probability?

@KamilDrakari Yes. Which is also stated in the fourth rule.

@KevinCruijssen I did not consider it clear from the 4th rule that "if the letter appears in multiple places, then any of those places could be the 'right' one". In that case, is b3bkk valid because b also appeared at the third index?

@KamilDrakari b3bkk is indeed valid because b appears at the 3rd (1-indexed) position. The other three characters can be any randomly (including a b). bbbbb or bb5bb are also valid, although the chances are very low of course.

For example, when length = 3, char = "a"; The form "a??" has 676 possible results, but "1a?", "?a1", "2?a", "?2a", has only104 results. So, if I'm trying to chose one result from all these 780 results, the distribution of "position of the enciphered letter" is 13:1:1, not 1:1:1. And I would consider this as how "uniformly random" work.

@tsh Hmm.. I guess either is fine. Although you're indeed right that a?? has of course more possible variations than 1a? or ?2a, etc., since there are two ? (676 ways to fill it in) instead of one ? (26 ways to fill it in; times four for the different positions), when I was writing the requirements I meant it in a way: 1. First determine a random position in the group of length=3: one of: a??; ?a?; ??a. 2. Then add the digit at a random position: a??; [1a?, ?a1]; [2?a, ?2a]. 3. Then fill in the remaining positions (marked with ?) with random letters from the alphabet.

@tsh Where there is a 1/3rd chance for either a??, ?a?, ??a in step 1; there is an equal chance of 1/2 for either 1a? or ?a1 in step 2 (for ?a?); and finally there is a 1/26th chance for any letter of the alphabet at the ? in step 3. But if you don't use these exact steps and do what you describe in your comment, it's fine as well. a?? will then have a higher chance to occur than ?a? or ??a, but it's still uniform in its own way as you describe it.

Pyth, 22 bytes
smsXWJOQXmOGQJdO-UQJJz

Try it online.
Uses lowercase and zero-indexing.
Explanation
Very straightforward algorithm.
                           Implicit: read word in z
                           Implicit: read number in Q
 m                   z     For each char d in z:
      OQ                     Choose a number 0..Q-1
     J                       and call it J.
         m  Q                Make an array of Q
          OG                 random letters.
        X     d              Place d in this string
             J               at position J.
    W                        If J is not 0,
   X                J        place J in this string
               O             at a random position from
                 UQ          0..Q-1
                -  J         except for J.
  s                          Concatenate the letters.
s                          Concatenate the results.

Perl 6, 125 bytes
->\n{*.&{S:g{.}=(65..90)>>.chr.roll(n).join.subst(/./,$/,:th($!=roll 1..n:)).subst(/./,$!,:th($!-1??(^n+1∖$!).roll!!n+1))}}

Try it online!
Takes input and output in uppercase. Takes input curried, like f(n)(string). Uses 1 indexing.
Explanation:
->\n{*.&{ ...  }}   # Anonymous code block that takes a number n and returns a function
     S:g{.}=        # That turns each character of the given string into
                          .roll(n)      # Randomly pick n times with replacement
            (65..90)>>.chr              # From the uppercase alphabet
                                  .join # And join
            .subst(                         ) # Then replace
                   /./,  ,:th($!=roll 1..n:)  # A random index (saving the number in $!)
                       $/               # With the original character
            .subst(                )    # Replace again
                   /./,$!,:th( ... )    # The xth character with $!, where x is:
                           $!-1??          # If $! is not 1
                                 (^n+1∖$!).roll       # A random index that isn't $!
                                               !!n+1  # Else an index out of range

Python 2, 187 177 176 156 154 148 bytes
lambda l,s:''.join([chr(choice(R(65,91))),c,`n`][(j==n)-(j==i)*(n>0)]for c in s for n,i in[sample(R(l),2)]for j in R(l))
from random import*
R=range

Try it online!
Uses uppercase letters, and 0-indexed numbers.
-3 bytes, thanks to Kevin Cruijssen

@KevinCruijssen Thanks :)

What does sample(R(l),2)[::1|-(random()<.5)] mean?

@l4m2 It takes 2 numbers from range(l), and shuffles them. But apparently sample does not guarantee order, so it's not needed :)

Can't you remove the parenthesis around (j==i)*(n>0)? The multiply has operator precedence over the subtract doesn't it?

@KevinCruijssen Yeah, I forgot to remove them, when i had some problems

JavaScript (Node.js), 135 bytes
n=>f=([c,...s])=>c?(g=n=>n?g(--n)+(n-p?n-q|!p?(r(26)+10).toString(36):p:c):'')(n,r=n=>Math.random()*n|0,p=r(n),q=r(n-1),q+=q>=p)+f(s):s

Try it online!
Thank Arnauld for 1B

R, 134 132 123 bytes
function(S,n,s=sample)for(k in utf8ToInt(S)){o=k+!1:n
P=s(n,1)
o[-P]=s(c(P[i<-P>1],s(17:42,n-1-i,T)))+48
cat(intToUtf8(o))}

Try it online!
Takes uppercase letters.
Explanation of old code (mostly the same approach):
function(S,n){s=sample				# alias
K=el(strsplit(S,""))				# split to characters
o=1:n						# output array
for(k in K){					# for each character in the string
P=s(n,1)					# pick a Position for that character
o[-P]=						# assign to everywhere besides P:
      s(					# a permutation of:
	c(P[i<-P>1],				# P if it's greater than 1
		s(letters,n-1-i,T)))		# and a random sample, with replacement, of lowercase letters
o[P]=k						# set k to position P
cat(o,sep="")}}					# and print

Japt, 29 bytes
;£=VöJ;CöV hUÎX hUÅÎUÎ?UÎs:Cö

Try it online!
Zero-indexed.
Explanation:
;                                :Set C = [a...z]
 £                               :For each character of the input:
  =VöJ;                          : Get two different random indexes from [0,length)
       CöV                       : Get 5 random letters
           hUÎX                  : Replace one at random with the character from the input
                hUÅÎ             : Replace a different random character with:
                    UÎ?          :  If the input character was not placed at 0:
                       UÎs       :   The index of the input character
                          :      :  Otherwise:
                           Cö    :   A random letter
                                 :Implicitly join back to a string

Java (JDK), 193 bytes
s->n->s.flatMap(c->{int a[]=new int[n],i=n,x=0;for(;i-->0;)a[i]+=Math.random()*26+97;a[i+=Math.random()*n+1]=c;x+=Math.random()*~-n;if(i>0)a[x<i?x:x+1]=48+i;return java.util.Arrays.stream(a);})

Try it online!

The index are 0-based.
This entry uses an IntStream (gotten through String::chars) as input, as well as a number and returns another IntStream.
Casts from double to int are unnecessary because of the += hack.

C, 115 bytes
g(_,n)char*_;{int i=rand(),j=i%~-n,k=0;for(i%=n;k<n;k++)putchar(k-i?!i|i<k^k-j?rand()%26+97:48+i:*_);*++_&&g(_,n);}

Try it online!
0-indexed, lowercase.
Slightly ungolfed and expanded:
g(char*_,int n) {
    int i = rand(), j = i%(n-1), k = 0;
    for(i = i%n; k<n; k++)
        putchar(k!=i ? i!=0 || k==j + (k>i)
                          ? rand()%26 + 'A'
                          : i + '0')
                    : *_);
    if (*++_!=0) g(_,n);
}

The code should be pretty straightforward.
The two randoms i,j generated in one rand() call are good as independent since gcd(n,~-n)=1 and RAND_MAX is large.

Welcome to PPCG! :)

Wolfram Language (Mathematica), 169 bytes
StringJoin@Table[While@FreeQ[a=RandomChoice[Alphabet[],#2],c];If[(p=Position[a,c][[1,1]])!=1,a[[RandomChoice@Complement[Range@#2,{p}]]]=ToString@p];a,{c,Characters@#1}]&

Try it online!
Thank you for the interesting challenge!
It turned out a pretty big program,
but I can not do less and at the same time meet the requirements (
Ungolfed explained:
str = "thisisacomputercipher"; len = 5;
StringJoin[Table[
  While[(*Get first random choice contained character*)
   FreeQ[arr = RandomChoice[Alphabet[], len], c]
   ];
  If[(pos = Position[arr, c][[1, 1]]) != 1,
   (*If char is at first position - keep it,
   else set random item to digit as index of char*)
   arr[[RandomChoice@Complement[Range@len, {pos}]]] = ToString@pos
   ]; arr,
  {c, Characters@str}]]

Charcoal, 35 30 bytes
ＮθＦＳ«≔‽θη≔∧η‽Φθ⁻κηζＦθ≡κζＩηηι‽β

Try it online! Link is to verbose version of code. 0-indexed. Explanation:
Ｎθ

Input the length.
ＦＳ«

Input the word and loop over the characters.
≔‽θη

Choose a random position for the deciphered letter.
≔∧η‽Φθ⁻κηζ

Choose a different random position for the digit, unless the letter is at position 0, in which case put the digit at position 0 as well.
Ｆθ≡κ

Loop once for each output character and switch on the position.
ζＩη

If this is the position of the digit then output the position of the deciphered letter.
ηι

But if this is the position of the deciphered letter then output the letter. This takes precedence over the position of the digit because Charcoal takes the last entry if multiple switch cases have the same value.
‽β

Otherwise output a random letter.

Clean, 256 bytes
import StdEnv
s::!Int->Int
s _=code {
ccall time "I:I"
ccall srand "I:I"
}
r::!Int->Int
r _=code {
ccall rand "I:I"
}
$n|s 0<1#k=map\e.r e rem n
=flatten o map\c.hd[map(\i|i==x=c=toChar if(i==y&&x>0)(x+48)(r i rem 26+97))[0..n-1]\\x<-k[0..]&y<-k[0..]|x<>y]

Try it online!
Chooses:

a random x (position of the character in the segment)
a random y that isn't equal to x (position of the digit in the segment)
a random lowercase letter for each position not equal to x and not equal to y unless x is zero

JavaScript, 134 bytes
l=>w=>w.replace(/./g,c=>eval("for(s=c;!s[l-1]||s[t?t-1||9:0]!=c;t=s.replace(/\\D/g,''))s=(p=Math.random()*36**l,p-p%1).toString(36)"))

Try it online!
This answer chose the encoded string from all possible encoded string uniformly. So it is more possible to make the encoded letter as the first one.

C# (Visual C# Interactive Compiler), 171 bytes
s=>n=>{var r=new Random();return s.SelectMany(c=>{int i=r.Next(n),j=r.Next(n-1);j+=j<i?0:1;return new int[n].Select((_,k)=>(char)(i==k?c:j==k&i>0?i+49:r.Next(26)+97));});}

Try it online!
Explanation...
// s is the input string
// n is the input length
s=>n=>{
  // we need to create an instance
  // of Random and use throughout
  var r=new Random();
  // iterate over s, each iteration
  // returns an array... flatten it
  return s.SelectMany(c=>{
    // i is the position of the letter
    // j is the position of the number
    int i=r.Next(n), j=r.Next(n-1);
    // ensure i and j are different
    j+=j<i?0:1;
    // create an iterable of size n
    return new int[n]
      // iterate over it with index k
      .Select((_,k)=>(char)(
        // return the letter
        i==k?c:
        // return the number
        j==k&i>0?i+49:
        // return a random letter
        r.Next(26)+97)
      );
  });
}

05AB1E, 26 bytes
ε²Ý¨Ω©A.r²£Šǝ®Āi®²Ý¨®KΩǝ]J

0-indexed.
Try it online or verify all test cases.
Explanation:
ε            # Map over the characters of the first (implicit) input-string:
 ²Ý¨         #  Create a list in the range [0, second input)
    Ω        #  Get a random item from this list
     ©       #  Store it in the register (without popping)
 A           #  Push the lowercase alphabet
  .r         #  Shuffle it
    ²£       #  Leave only the first second input amount of characters
      Š      #  Triple swap, so the stack order becomes:
             #  random index; random string; map-character
       ǝ     #  Insert the map-character at this random index into the random string
 ®Āi         #  If the random index was NOT 0:
    ®        #   Push the random index
    ²Ý¨      #   Push the list in the range [0, second input) again
       ®K    #   Remove the random index from this list
         Ω   #   Get a random item from this list
          ǝ  #   Insert the first random index at the second random index into the string
]            # Close both the if-else and map
 J           # Join all strings together (and output implicitly)


text:
Digital Sumorial
Given an input n, write a program or function that outputs/returns the sum of the digital sums of n for all the bases 1 to n.
$$n + \sum_{b=2}^n \sum_{i=0}^\infty \left\lfloor \frac{n}{b^i} \right\rfloor \bmod b$$
Example:
n = 5

Create the range [1...n]: [1,2,3,4,5]

For each element x, get an array of the base-x digits of n:  [[1,1,1,1,1],[1,0,1],[1,2],[1,1],[1,0]]
bijective base-1 of 5  is [1,1,1,1,1]
base-2 (binary) of 5  is [1,0,1]
base-3 of 5  is [1,2]
base-4 of 5  is [1,1]
base-5 of 5  is [1,0]

Sum the digits: 13

Test cases:
1    1
2    3
3    6
4    8
5    13
6    16
7    23
8    25
9    30
10   35

36   297
37   334

64   883
65   932

The sequence can be found on OEIS: A131383
Scoring:
code-golf: The submission with the lowest score wins.

A fun one: 227 -> 9999. And also: 1383 -> 345678.

Canvas, 3 bytes
┬］∑

Try it here!
Canvas beating Jelly?
{ ]   map over 1..input (implicit "{")
 ┬      decode input from that base
   ∑  sum the resulting (nested) array

Haskell, 46 bytes
f n=sum$do a<-[1..n];mapM(pure[0..a])[1..n]!!n

Try it online!
Explanation
The function \b n -> mapM(pure[0..b])[1..n], generates all strings \$[0 \dotsc b]^n\$ in lexicographic order. For example:
mapM(pure[0..2])[0..1] == [[0,0],[0,1],[0,2],[1,0],[1,1],[1,2],[2,0],[2,1],[2,2]]

By indexing into it with (!!n) this can be used to convert n to base b+1, however this won't work for unary (base-\$1\$), but we're summing the results.. We can even save some bytes with a <- [1..n] and using base-\$(n+1)\$ rather than a work-around for base-\$1\$ since we're missing \$[\underset{n\text{ times}}{\underbrace{1,\dotsc,1}}]\$ which is the same as \$[n]\$ when summing.
Using do-notation just concatenates all the lists instead of nesting them:
λ [ mapM (pure [0..a]) [1..5] !! n | a <- [1..5] ]
[[0,0,1,0,1],[0,0,0,1,2],[0,0,0,1,1],[0,0,0,1,0],[0,0,0,0,5]]

λ do a <- [1..5]; mapM (pure [0..a]) [1..5] !! n
[0,0,1,0,1,0,0,0,1,2,0,0,0,1,1,0,0,0,1,0,0,0,0,0,5]

Ruby, 39 37
->n{(2..n).sum{|b|n.digits(b).sum}+n}

The only golfing here is removing some whitespace. Try it online

@Giuseppe The OP starts with: " Given an input n,(...)" . I haven' t been around here for a long time. Is there a list somewhere of requirements to a solution?

Usually it must be a full program or a function (named or unnamed), here's more information: loopholes and i/o defaults. I don't know ruby, but this seems the shortest fix.

@BMO Thanks. For someone who doesn't know Ruby, you are creating and calling a lambda with the greatest of ease!

you can remove the parentheses around n (37b): ->n{(2..n).sum{|b|n.digits(b).sum}+n}

@ConorO'Brien thanks!

Well, google "ruby lambda" did the trick ;P But I stand corrected in that you were able to save two bytes.

Python 2, 57 bytes
lambda n:sum(n/(k/n+2)**(k%n)%(k/n+2)for k in range(n*n))

This uses the formula $$a(n)=\sum_{b=2}^{n+1}\sum_{i=0}^{n-1}\left\lfloor\frac{n}{b^i}\right\rfloor\bmod b,$$ which works since \$\left\lfloor\frac{n}{(n+1)^0}\right\rfloor\bmod(n+1)=n\$.
Try it online!

APL (Dyalog Unicode), 14 bytes
+/∘∊⊢,⊢(⍴⊤⊣)¨⍳

Try it online!
Explanation
Some parentheses are implied and can be added (lighter than the "official" parenthesizing):
+/∘∊(⊢,(⊢(⍴⊤⊣)¨⍳))

This is a monadic atop. Given an argument Y, this function behaves like:
+/∘∊(⊢,(⊢(⍴⊤⊣)¨⍳))Y

The two functions are applied in order. We'll start from the right one:
⊢,(⊢(⍴⊤⊣)¨⍳)

The are three functions in this train, so this is a fork. Given an argument Y, it acts as:
(⊢Y),((⊢Y)(⍴⊤⊣)¨⍳Y)

We can easily reduce to this (monadic ⊢ returns its argument, hence called identity):
Y,Y(⍴⊤⊣)¨⍳Y

Now, we know that Y is an integer (simple scalar, i.e. number or character), since we're given one. Therefore ⍳Y, with ⎕IO=1, returns 1 2 ... Y. ⍳Y actually returns an array with shape Y (Y must be a vector), where every scalar is the index of itself in the array (that's why monadic ⍳ is called the index generator). These indices are vectors, except for the case where 1≡⍴Y, where they are scalars (this is our case).
Let's parse the middle function, (⍴⊤⊣)¨, next. ⍴⊤⊣ is the operand of ¨ (each), and the function is dyadic, so the ¨ operator will first reshape each length-1 argument to the shape of the other (that is, take the element and use it to replace every scalar in the other argument), and then apply the function to each pair of the two arguments. In this case, ⍳Y is a vector and Y is a scalar, so, if n≡⍴⍳Y, then Y will be converted to n⍴Y (⍴ represents the shape (monadic) and reshape (dyadic) functions). That is, in simpler terms, Y will be converted to an array containing Y times Y.
Now, for each pair, let's call the left argument X and the right Z (so that we don't conflict with the input Y). ⍴⊤⊣ is a dyadic fork, so it will expand to:
(X⍴Z)⊤X⊣Z

Let's make the easy first step of reducing X⊣Z to X (dyadic ⊣ is the left function):
(X⍴Z)⊤X

The ⍴ in X⍴Z is, again, the reshape function, so X⍴Z, in our case, is simply X times Z. ⊤ is the encode function. Given two arrays of numbers, where the left array is the base of each digit in the result (doesn't need to be integer or positive), i.e. the encoding, and the right is an array of numbers, returns the transposed array of those numbers in the specified encoding (transposition is the reversal of an array's dimensions relative to its elements). The representation of a digit is based on the quotient of the division of the number and the product of the less significant bases. If any base is 0, it acts as base +∞. The arguments' scalars are all simple. Since X is a positive integer, and X⍴Z is a vector of equal elements, this is really just a case of converting X to base Z and reshaping to X digits. For \$X,Z\in\mathbb N\$, \$X_Z\$ (\$X\$ in base \$Z\$) can't have more than \$X\$ digits, since \$X_1\$ has \$X\$ digits. Therefore, X⍴Z is enough for our purposes.
The result of Y(⍴⊤⊣)¨⍳Y is, therefore, Y converted to each base from 1 to Y, possibly with leading zeroes. However, there is one issue: in APL, base 1 isn't special-cased, while this challenge does special-case it, so we have to include the sum of the base-1 digits of Y ourselves. Fortunately, this sum is just Y, since \$Y_1=\underbrace{[1,1,...,1]}_Y\$, so the sum is simply \$Y\times1=Y\$. It follows that we have to add Y somewhere into the array. This is how we do it:
Y,Y(⍴⊤⊣)¨⍳Y

I have already included this part here. Dyadic , is the catenate function, it concatenates its arguments on their last axes, and errors if that's not possible. Here, we simply concatenate the scalar Y to the vector Y(⍴⊤⊣)¨⍳Y, so that we increment the sum we're going to calculate by Y, as explained above.
The final part is the left function of our atop, +/∘∊:
+/∘∊Y,Y(⍴⊤⊣)¨⍳Y

∘ is the compose operator. f∘g Y is the same as f g Y. However, we're using it here so that our train doesn't fork on the ∊. So, we can reduce:
+/∊Y,Y(⍴⊤⊣)¨⍳Y

Now, it's time for the sum, but wait... there's a problem. The array isn't flat, so we can't just sum its elements before flattening it first. The enlist function ∊ flattens an array. Now that the array has been flattened, we finally use +/ to sum it. / is the reduce operator, it applies a dyadic function between an array's elements on its second-to-last axis, with right-to-left priority. If the rank (number of dimensions, i.e. length of shape) of the array doesn't decrease, the array is then enclosed, although this is not the case here. The function that's applied here is +, which is the plus function that adds the pairs on the last axes of two arrays (and errors if the arrays can't be added like that). Here, it simply adds two numbers a number of times so that the reduce is completed.
Lo and behold, our train:
+/∘∊⊢,⊢(⍴⊤⊣)¨⍳

+1 Impressive explanation. Not shorter, but no parens: +/∘∊⊢,⊢⊤¨⍨⊢⍴¨⍳

@Adám Thanks! I was almost sleeping when I wrote it. :-P

@Adám Regarding your version, it looks like it's a tad more difficult to understand. ;-)

Java 8, 76 65 bytes
n->{int r=n,b=n,N;for(;b>1;b--)for(N=n;N>0;N/=b)r+=N%b;return r;}

-11 bytes thanks to @OlivierGrégoire.
Try it online.
Explanation:
n->{           // Method with integer as both parameter and return-type
  int r=n,     //  Result-sum, starting at the input to account for Base-1
      b=n,     //  Base, starting at the input
      N;       //  Temp integer
  for(;b>1     //  Loop the Base `b` in the range [n, 1):
      ;b--)    //    After every iteration: Go to the next Base (downwards)
    for(N=n;   //   Set `N` to the input `n`
        N>0;   //   Loop as long as `N` isn't 0 yet:
        N/=b)  //     After every iteration: Divide `N` by the Base `b`
      r+=N%b;  //    Increase the result `r` by `N` modulo the Base `b`
  return r;}   //  Return the result-sum `r`

There is no need for i, so... 65 bytes.

@OlivierGrégoire Damn, I'm an idiot. Thanks a lot! Hmm, now I also need to golf my derived C and Whitespace answers.. ;)

Whitespace, 153 bytes
[S S S N
_Push_0][S N
S _Duplicate_0][T   N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve_input][S N
S _Duplicate_input][N
S S N
_Create_Label_OUTER_LOOP][S N
S _Duplicate_top][S S S T   N
_Push_1][T  S S T   _Subtract][N
T   S S N
_If_0_Jump_to_Label_PRINT][S S S N
_Push_0][S N
S _Duplicate_0][T   T   T   _Retrieve_input][N
S S T   N
_Create_Label_INNER_LOOP][S N
S _Duplicate][N
T   S S S N
_If_0_Jump_to_Label_AFTER_INNER_LOOP][S N
T   _Swap_top_two][S T  S S T   N
_Copy_1st_item_to_top][S T  S S T   T   N
_Copy_3rd_item_to_top][T    S T T   _Modulo][T  S S S _Add][S N
T   _Swap_top_two][S T  S S T   S N
_Copy_2nd_item_to_top][T    S T S _Integer_divide][N
S N
T   N
_Jump_to_Label_INNER_LOOP][N
S S S S N
_Create_Label_AFTER_INNER_LOOP][S N
N
_Discard_top][S T   S S T   S N
_Copy_2nd_item_to_top][T    S S S _Add][S N
T   _Swap_top_two][S S S T  N
_Push_1][T  S S T   _Subtract][N
S N
N
_Jump_to_Label_OUTER_LOOP][N
S S S N
_Create_Label_PRINT][S N
N
_Discard_top][T N
S T _Print_as_integer]

Letters S (space), T (tab), and N (new-line) added as highlighting only.
[..._some_action] added as explanation only.
Try it online (with raw spaces, tabs and new-lines only).
Port of my Java 8 answer, because Whitespace has no Base conversion builtins at all.
Example run: input = 3
Command    Explanation                     Stack            Heap   STDIN  STDOUT  STDERR

SSSN       Push 0                          [0]
SNS        Duplicate 0                     [0,0]
TNTT       Read STDIN as integer           [0]              {0:3}  3
TTT        Retrieve input from heap 0      [3]              {0:3}
SNS        Duplicate 3                     [3,3]            {0:3}
NSSN       Create Label_OUTER_LOOP         [3,3]            {0:3}
 SNS       Duplicate 3                     [3,3,3]          {0:3}
 SSSTN     Push 1                          [3,3,3,1]        {0:3}
 TSST      Subtract (3-1)                  [3,3,2]          {0:3}
 NTSSN     If 0: Jump to Label_PRINT       [3,3]            {0:3}
 SSSN      Push 0                          [3,3,0]          {0:3}
 SNS       Duplicate 0                     [3,3,0,0]        {0:3}
 TTT       Retrieve input from heap 0      [3,3,0,3]        {0:3}
 NSSTN     Create Label_INNER_LOOP         [3,3,0,3]        {0:3}
  SNS      Duplicate 3                     [3,3,0,3,3]      {0:3}
  NTSSSN   If 0: Jump to Label_AFTER_IL    [3,3,0,3]        {0:3}
  SNT      Swap top two                    [3,3,3,0]        {0:3}
  STSSTN   Copy (0-indexed) 1st            [3,3,3,0,3]      {0:3}
  STSSTTN  Copy (0-indexed) 3rd            [3,3,3,0,3,3]    {0:3}
  TSTT     Modulo (3%3)                    [3,3,3,0,0]      {0:3}
  TSSS     Add (0+0)                       [3,3,3,0]        {0:3}
  SNT      Swap top two                    [3,3,0,3]        {0:3}
  STSSTSN  Copy (0-indexed) 2nd            [3,3,0,3,3]      {0:3}
  TSTS     Integer divide (3/3)            [3,3,0,1]        {0:3}
  NSNTN    Jump to LABEL_INNER_LOOP        [3,3,0,1]        {0:3}

  SNS      Duplicate 1                     [3,3,0,1,1]      {0:3}
  NTSSSN   If 0: Jump to Label_AFTER_IL    [3,3,0,1]        {0:3}
  SNT      Swap top two                    [3,3,1,0]        {0:3}
  STSSTN   Copy (0-indexed) 1st            [3,3,1,0,1]      {0:3}
  STSSTTN  Copy (0-indexed) 3rd            [3,3,1,0,1,3]    {0:3}
  TSTT     Modulo (1%3)                    [3,3,1,0,1]      {0:3}
  TSSS     Add (0+1)                       [3,3,1,1]        {0:3}
  SNT      Swap top two                    [3,3,1,1]        {0:3}
  STSSTSN  Copy (0-indexed) 2nd            [3,3,1,1,3]      {0:3}
  TSTS     Integer divide (1/3)            [3,3,1,0]        {0:3}
  NSNTN    Jump to LABEL_INNER_LOOP        [3,3,1,0]        {0:3}

  SNS      Duplicate 0                     [3,3,1,0,0]      {0:3}
  NTSSSN   If 0: Jump to Label_AFTER_IL    [3,3,1,0]        {0:3}
 NSSSSN    Create Label_AFTER_IL           [3,3,1,0]        {0:3}
  SNN      Discard top                     [3,3,1]          {0:3}
  STSSTSN  Copy (0-indexed) 2nd            [3,3,1,3]        {0:3}
  TSSS     Add (1+3)                       [3,3,4]          {0:3}
  SNT      Swap top two                    [3,4,3]          {0:3}
  SSSTN    Push 1                          [3,4,3,1]        {0:3}
  TSST     Subtract (3-1)                  [3,4,2]          {0:3}
  NSNN     Jump to LABEL_OUTER_LOOP        [3,4,2]          {0:3}

 SNS       Duplicate 2                     [3,4,2,2]        {0:3}
 SSSTN     Push 1                          [3,4,2,2,1]      {0:3}
 TSST      Subtract (2-1)                  [3,4,2,1]        {0:3}
 NTSSN     If 0: Jump to Label_PRINT       [3,4,2]          {0:3}
 SSSN      Push 0                          [3,4,2,0]        {0:3}
 SNS       Duplicate 0                     [3,4,2,0,0]      {0:3}
 TTT       Retrieve input from heap 0      [3,4,2,0,3]      {0:3}
 NSSTN     Create Label_INNER_LOOP         [3,4,2,0,3]      {0:3}
  SNS      Duplicate 3                     [3,4,2,0,3,3]    {0:3}
  NTSSSN   If 0: Jump to Label_AFTER_IL    [3,4,2,0,3]      {0:3}
  SNT      Swap top two                    [3,4,2,3,0]      {0:3}
  STSSTN   Copy (0-indexed) 1st            [3,4,2,3,0,3]    {0:3}
  STSSTTN  Copy (0-indexed) 3rd            [3,4,2,3,0,3,2]  {0:3}
  TSTT     Modulo (3%2)                    [3,4,2,3,0,1]    {0:3}
  TSSS     Add (0+1)                       [3,4,2,3,1]      {0:3}
  SNT      Swap top two                    [3,4,2,1,3]      {0:3}
  STSSTSN  Copy (0-indexed) 2nd            [3,4,2,1,3,2]    {0:3}
  TSTS     Integer divide (3/2)            [3,4,2,1,1]      {0:3}
  NSNTN    Jump to LABEL_INNER_LOOP        [3,4,2,1,1]      {0:3}

  SNS      Duplicate 1                     [3,4,2,1,1,1]    {0:3}
  NTSSSN   If 0: Jump to Label_AFTER_IL    [3,4,2,1,1]      {0:3}
  SNT      Swap top two                    [3,4,2,1,1]      {0:3}
  STSSTN   Copy (0-indexed) 1st            [3,4,2,1,1,1]    {0:3}
  STSSTTN  Copy (0-indexed) 3rd            [3,4,2,1,1,1,2]  {0:3}
  TSTT     Modulo (1%2)                    [3,4,2,1,1,1]    {0:3}
  TSSS     Add (1+1)                       [3,4,2,1,2]      {0:3}
  SNT      Swap top two                    [3,4,2,2,1]      {0:3}
  STSSTSN  Copy (0-indexed) 2nd            [3,4,2,2,1,2]    {0:3}
  TSTS     Integer divide (1/2)            [3,4,2,2,0]      {0:3}
  NSNTN    Jump to LABEL_INNER_LOOP        [3,4,2,2,0]      {0:3}

  SNS      Duplicate 0                     [3,4,2,2,0,0]    {0:3}
  NTSSSN   If 0: Jump to Label_AFTER_IL    [3,4,2,2,0]      {0:3}
 NSSSSN    Create Label_AFTER_IL           [3,4,2,2,0]      {0:3}
  SNN      Discard top                     [3,4,2,2]        {0:3}
  STSSTSN  Copy (0-indexed) 2nd            [3,4,2,2,4]      {0:3}
  TSSS     Add (2+4)                       [3,4,2,6]        {0:3}
  SNT      Swap top two                    [3,4,6,2]        {0:3}
  SSSTN    Push 1                          [3,4,6,2,1]      {0:3}
  TSST     Subtract (2-1)                  [3,4,6,1]        {0:3}
  NSNN     Jump to LABEL_OUTER_LOOP        [3,4,6,1]        {0:3}

 SNS       Duplicate 1                     [3,4,6,1,1]      {0:3}
 SSSTN     Push 1                          [3,4,6,1,1,1]    {0:3}
 TSST      Subtract (1-1)                  [3,4,6,1,0]      {0:3}
 NTSSN     If 0: Jump to Label_PRINT       [3,4,6,1]        {0:3}
NSSSSN     Create Label_PRINT              [3,4,6,1]        {0:3}
 SNN       Discard top                     [3,4,6]          {0:3}
 TNST      Print top (6) to STDOUT as int  [3,4]            {0:3}         6
                                                                                error

Program stops with an error: No exit found. (Although I could add three trailing newlines NNN to get rid of that error.)

SAS, 81 74 bytes
data;input n;s=n;do b=2to n;do i=0to n;s+mod(int(n/b**i),b);end;end;cards;

Input is entered after the cards; statement, on newlines, like so:
data;input n;s=n;do b=2to n;do i=0to n;s+mod(int(n/b**i),b);end;end;cards;
1
2
3
4
5
6
7
8
9
10
36
37
64
65

Outputs a dataset containing the answer s (along with helper variables), with a row for each input value

Ungolfed:
data; /* Implicit dataset creation */
input n; /* Read a line of input */

s=n; /* Sum = n to start with (the sum of base 1 digits of n is equal to n) */
do b=2to n; /* For base = 2 to n */
    do i=0to n; /* For each place in the output base (output base must always have less than or equal to n digits) */

        /* Decimal value of current place in the output base = b^i      */
        /* Remainder = int(b / decimal_value)                           */
        /* Current place digit = mod(remainder, base)                   */
        s+mod(int(n/b**i),b);
    end;
end;

cards;
1
2
3

Japt -x, 6 bytes
ÆìXÄ x

Try it
õ!ìU c

Try it

J, 24 23 bytes
+1#.1#.]#.inv"0~2+i.@<:

Try it online!

R, 60 bytes
function(n){if(n-1)for(i in 2:n)F=F+sum(n%/%i^(0:n)%%i)
n+F}

Try it online!
Fails for n>143 since 144^144 is larger than a double can get. Thanks to Josh Eller for suggesting replacing log(n,i) with simply n.
The below will work for n>143; not sure at what point it will stop working.
R, 67 bytes
function(n){if(n-1)for(i in 2:n)F=F+sum(n%/%i^(0:log(n,i))%%i)
n+F}

Try it online!
Uses the classic n%/%i^(0:log(n,i))%%i method to extract the base-i digits for n for each base b>1, then sums them and accumulates the sum in F, which is initialized to 0, then adding n (the base 1 representation of n) to F and returning the result. For n=1, it skips the bases and simply adds n to F.

I don't know any R, but instead of using 0:log(n,i), couldn't you use 0:n? There's always going to be at most n digits in any base representation of n, and everything after the initial log(n,i) digits should be 0, so it won't affect the sum.

@JoshEller I suppose I could. It would start to fail for n=144, since 143^143 is around 1.6e308 and 144^144 evaluates to Inf. Thanks!

Perl 6, 45 41 bytes
{$^a+sum map {|polymod $a: $_ xx*},2..$a}

-4 bytes thanks to Jo King
Try it online!

36 bytes

Husk, 6 bytes
I really wish that there was something like M for cmap :(
Σ§ṁ`Bḣ

Try it online or test all!
Explanation
Σ§ṁ`Bḣ  -- example input: 5
 §      -- fork the argument..
     ḣ  -- | range: [1,2,3,4,5]
   `B   -- | convert argument to base: (`asBase` 5)
  ṁ     -- | and concatMap: cmap (`asBase` 5) [1,2,3,4,5]
        -- : [1,1,1,1,1,1,0,1,1,2,1,1,1,0]
Σ       -- sum: 13

Alternatively, 6 bytes
ΣΣṠMBḣ

Try it online or test all!
Explanation
ΣΣṠMBḣ  -- example input: 5
  Ṡ     -- apply ..
     ḣ  -- | range: [1,2,3,4,5]
           .. to function applied to itself
   MB   -- | map over left argument of base
        -- : [[1,1,1,1,1],[1,0,1],[1,2],[1,1],[1,0]]
 Σ      -- flatten: [1,1,1,1,1,1,0,1,1,2,1,1,1,0]
Σ       -- sum: 13

05AB1E (legacy), 5 bytes
LвOO+

Try it online!
Explanation:
LвOO+  //Full program
L      //push [1 .. input]
 в     //for each element b, push digits of input converted to base b
  O    //sum each element
   O   //sum each sum
    +  //add input

In 05AB1E (legacy), base 1 of 5 is [0,0,0,0,0], not [1,1,1,1,1]. Therefore after summing the range, add the input to account for the missing base 1.
I am using 05AB1E (legacy) because in current 05AB1E, base 1 of 5 is [1]. In order to account for this, I would either need to decrement the result by 1 or remove the first element of the range, both of which would cost 1 byte.

Desmos, 127 bytes
$$f\left(n\right)=\sum_{b=2}^{n+1}\sum_{i=0}^{n-1}\operatorname{mod}\left(\operatorname{floor}\left(\frac{n}{b^i}\right),b\right)$$
f\left(n\right)=\sum_{b=2}^{n+1}\sum_{i=0}^{n-1}\operatorname{mod}\left(\operatorname{floor}\left(\frac{n}{b^i}\right),b\right)

Try it here! Defines a function \$f\$, called as \$f\left(n\right)\$. Uses the formula given in Dennis's answer.
Here is the resulting graph (point at \$(65, 932)\$):

Desmos, 56 bytes
This might not work on all browsers, but it works on mine. Just copy and paste the formula. This is \$f_2(n)\$ in the above link.
f(n)=\sum_{b=2}^{n+1}\sum_{i=0}^{n-1}mod(floor(n/b^i),b)

The second sum can run to n, saving 3 bytes as ^n  should then suffice.

Also you could change \sum_{b=2}^{n+1} to n+\sum_{b=2}^n saving another 2 bytes

Python 2, 61 bytes
f=lambda n,b=2.:n and n%b+f(n//b,b)+(n//b>1/n==0and f(n,b+1))

Try it online!
Though this is longer the Dennis's solution off which it's based, I find the method too amusing to not share.
The goal is to recurse both on lopping off the last digit n->n/b and incrementing the base b->b+1, but we want to prevent the base from being increased after one or more digits have been lopped off. This is achieved by make the base b a float, so that after the update n->n//b, the float b infects n with its floatness. In this way, whether n is a float or not is a bit-flag for whether we've removed any digits from n.
We require that the condition 1/n==0 is met to recurse into incrementing b, which integers n satisfy because floor division is done, but floats fails. (n=1 also fails but we don't want to recurse on it anyway.) Otherwise, floats work just like integers in the function because we're careful to do floor division n//b, and the output is a whole-number float.

JavaScript (without recursion), 77 bytes
Returns correct value for "any" number. Try it online
f=(n,b,s)=>{while((s=s||(t=b=n))>1){t+=b%s;b=(m=(b/s|0))||n;s=s-!m}return t;}

JavaScript (with recursion), 54 bytes
Returns correct value for maximum number 3867 ("Maximum call stack size exceeded" is thrown for larger input). Try it online
f=(n,b,s)=>(s=s||(b=n))-1?b%s+f(n,(m=b/s|0)||n,s-!m):b

Jelly, 4 bytes
bRFS

Try it online!
How it works
bRFS  Main link. Argument: n

 R    Range; yield [1, ..., n].
b     Convert n to back k, for each k to the right.
  F   Flatten the resulting 2D array of digits.
   S  Take the sum.

JavaScript (ES6), 42 bytes
This version is almost identical to my main answer but relies on arithmetic underflow to stop the recursion. The highest supported value depends on the size of the call stack.
f=(n,b=1,x)=>b>n?n:~~x%b+f(n,b+!x,x?x/b:n)

Try it online!

JavaScript (ES6),  51 48  44 bytes
f=(n,b=2,x=n)=>b>n?n:x%b+f(n,b+!x,x?x/b|0:n)

Try it online!
Commented
f = (             // f = recursive function taking:
  n,              // - n = input
  b = 2,          // - b = current base, initialized to 2
  x = n           // - x = current value being converted in base b
) =>              //
  b > n ?         // if b is greater than n:
    n             //   stop recursion and return n, which is the sum of the digits of n
                  //   once converted to unary
  :               // else:
    x % b +       //   add x modulo b to the final result
    f(            //   and add the result of a recursive call:
      n,          //     pass n unchanged
      b + !x,     //     increment b if x = 0
      x ?         //     if x is not equal to 0:
        x / b | 0 //       update x to floor(x / b)
      :           //     else:
        n         //       reset x to n
    )             //   end of recursive call

APL (Dyalog Unicode), 22 bytes
{1⊥⍵,∊(1+⍳⍵-1)⊥⍣¯1¨⊂⍵}

Try it online!

Pari/GP, 30 bytes
n->n+sum(b=2,n,sumdigits(n,b))

Try it online!

C (gcc), 67 56 bytes
b,a,s;e(n){for(b=a=n;a>1;a--)for(s=n;s;s/=a)b+=s%a;n=b;}

Port of my Java 8 answer.
-11 bytes thanks to @OlivierGrégoire's golf on my Java answer.
Try it online.
Explanation:
b,             // Result integer
a,             // Base integer
s;             // Temp integer
e(n){          // Method with integer as parameter
  for(b=a=n;   //  Set the result `b` to input `n` to account for Base-1
               //  And set Base `a` to input `n` as well
      a>1      //  Loop the Base `a` in the range [input, 1):
      ;a--)    //    After every iteration: Go to the next Base (downwards)
    for(s=n;   //   Set `s` to input `n`
        s;     //   Inner loop as long as `s` is not 0 yet:
        s/=a)  //     After every iteration: Divide `s` by Base `a`
      b+=s%a;  //    Add `s` modulo Base `a` to the result `b`
  n=b;}        //  Set input `n` to result `b` to 'return it'

tinylisp, 71 bytes
(load library
(d S(q((N)(sum(map sum(map* to-base(1to N)(repeat-val N N

Try it online!

Pyth, 7 bytes
+ssjLQS

Test suite
Explanation:
+ssjLQS   | Full program
+ssjLQSQQ | with implicit variables filled
----------+--------------------------------------------------
    L SQ  | Map over each d in [1..input]:
   j Q    |  input to base d as a list (unary is a list of 0)
 ss       | Sum of sums
+       Q | Add input (to account for unary)

Attache, 25 bytes
{Sum!`'^^ToBase[_,2:_]'_}

Try it online!
Explanation
{Sum!`'^^ToBase[_,2:_]'_}
{                       }   anonymous lambda, input: _
                            example: 5
         ToBase[_,   ]      convert `_`
                  2:_       ...to each base from 2 to `_`
                            example: [[1, 0, 1], [1, 2], [1, 1], [1, 0]]
                      '_    append `_`
                            example: [[1, 0, 1], [1, 2], [1, 1], [1, 0], 5]
       ^^                   fold...
     `'                     the append operator over the list
                            example: [1, 0, 1, 1, 2, 1, 1, 1, 0, 5]
 Sum!                       take the sum
                            example: 13

Charcoal, 12 bytes
ＩΣＥＩθΣ↨Ｉθ⁺²ι

Try it online! Link is to verbose version of code. Charcoal can't convert to base 1, but fortunately the digit sum is the same as the conversion to base \$n + 1\$. Explanation:
    θ           First input
   Ｉ            Cast to integer
  Ｅ             Map over implicit range
        θ       First input
       Ｉ        Cast to integer
      ↨         Converted to base
           ι    Current index
         ⁺      Plus
          ²     Literal 2
     Σ          Sum
 Σ              Grand total
Ｉ               Cast to string
                Implicitly print

Retina 0.8.2, 49 bytes
.+
$*
1
11$`;$_¶
+`\b(1+);(\1)+
$1;$#2$*1,
1+;

1

Try it online! Link includes test cases. Explanation:
.+
$*

Convert to unary.
1
11$`;$_¶

List all the numbers from 2 to \$n + 1\$ (since that's easier than base 1 conversion).
+`\b(1+);(\1)+
$1;$#2$*1,

Use repeated divmod to convert the original number to each base.
1+;

Delete the list of bases, leaving just the base conversion digits.
1

Take the sum and convert to decimal.

Desmos, 51 bytes
Inspired by Conor O'Brien's answer and looking at the OEIS-entry I came up with my own Desmos-solution:
h(n)=n^2-\sum_{p=2}^n(p-1)\sum_{k=1}^n floor(n/p^k)

Try it online!

APL(NARS), 29 chars, 58 bytes
{+/+/¨⍵{(⍺⍴⍨⌊1+⍺⍟⍵)⊤⍵}⍨¨1+⍳⍵}

little test on how to use:
  h←{+/+/¨⍵{(⍺⍴⍨⌊1+⍺⍟⍵)⊤⍵}⍨¨1+⍳⍵}
  h¨1 2 4 10 36 37 64 65
1 3 8 35 297 334 883 932